xref: /btstack/src/ble/sm.c (revision 2fca4dad957cd7b88f4657ed51e89c12615dda72)
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
23*2fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24*2fca4dadSMilanka Ringwald  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
253deb3ec6SMatthias Ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
263deb3ec6SMatthias Ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
273deb3ec6SMatthias Ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
283deb3ec6SMatthias Ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
293deb3ec6SMatthias Ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
303deb3ec6SMatthias Ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
313deb3ec6SMatthias Ringwald  * SUCH DAMAGE.
323deb3ec6SMatthias Ringwald  *
333deb3ec6SMatthias Ringwald  * Please inquire about commercial licensing options at
343deb3ec6SMatthias Ringwald  * [email protected]
353deb3ec6SMatthias Ringwald  *
363deb3ec6SMatthias Ringwald  */
37ab2c6ae4SMatthias Ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "sm.c"
393deb3ec6SMatthias Ringwald 
403deb3ec6SMatthias Ringwald #include <string.h>
413deb3ec6SMatthias Ringwald #include <inttypes.h>
423deb3ec6SMatthias Ringwald 
433edc84c5SMatthias Ringwald #include "ble/le_device_db.h"
4459c6af15SMatthias Ringwald #include "ble/core.h"
453edc84c5SMatthias Ringwald #include "ble/sm.h"
4661f37892SMatthias Ringwald #include "bluetooth_company_id.h"
47d7f1c72eSMatthias Ringwald #include "btstack_bool.h"
48d1a1f6a4SMatthias Ringwald #include "btstack_crypto.h"
490e2df43fSMatthias Ringwald #include "btstack_debug.h"
500e2df43fSMatthias Ringwald #include "btstack_event.h"
510e2df43fSMatthias Ringwald #include "btstack_linked_list.h"
520e2df43fSMatthias Ringwald #include "btstack_memory.h"
53899e6e02SMatthias Ringwald #include "btstack_tlv.h"
54f7a05cdaSMatthias Ringwald #include "gap.h"
550e2df43fSMatthias Ringwald #include "hci.h"
5613377825SMatthias Ringwald #include "hci_dump.h"
570e2df43fSMatthias Ringwald #include "l2cap.h"
583deb3ec6SMatthias Ringwald 
591a682202SMatthias Ringwald #if !defined(ENABLE_LE_PERIPHERAL) && !defined(ENABLE_LE_CENTRAL)
601a682202SMatthias Ringwald #error "LE Security Manager used, but neither ENABLE_LE_PERIPHERAL nor ENABLE_LE_CENTRAL defined. Please add at least one to btstack_config.h."
611a682202SMatthias Ringwald #endif
621a682202SMatthias Ringwald 
637ece0eaaSMatthias Ringwald #if defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION) && (!defined(ENABLE_CLASSIC) || !defined(ENABLE_LE_SECURE_CONNECTIONS))
647ece0eaaSMatthias Ringwald #error "Cross Transport Key Derivation requires support for LE Secure Connections and BR/EDR (Classic)"
656857ad8fSMatthias Ringwald #endif
666857ad8fSMatthias Ringwald 
67d1a1f6a4SMatthias Ringwald // assert SM Public Key can be sent/received
68d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
69d1a1f6a4SMatthias Ringwald #if HCI_ACL_PAYLOAD_SIZE < 69
70d1a1f6a4SMatthias Ringwald #error "HCI_ACL_PAYLOAD_SIZE must be at least 69 bytes when using LE Secure Conection. Please increase HCI_ACL_PAYLOAD_SIZE or disable ENABLE_LE_SECURE_CONNECTIONS"
71d1a1f6a4SMatthias Ringwald #endif
72d1a1f6a4SMatthias Ringwald #endif
73d1a1f6a4SMatthias Ringwald 
7442134bc6SMatthias Ringwald #if defined(ENABLE_LE_PERIPHERAL) && defined(ENABLE_LE_CENTRAL)
7542134bc6SMatthias Ringwald #define IS_RESPONDER(role) (role)
7642134bc6SMatthias Ringwald #else
7742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7842134bc6SMatthias Ringwald // only central - never responder (avoid 'unused variable' warnings)
7942134bc6SMatthias Ringwald #define IS_RESPONDER(role) (0 && role)
8042134bc6SMatthias Ringwald #else
8142134bc6SMatthias Ringwald // only peripheral - always responder (avoid 'unused variable' warnings)
8242134bc6SMatthias Ringwald #define IS_RESPONDER(role) (1 || role)
8342134bc6SMatthias Ringwald #endif
8442134bc6SMatthias Ringwald #endif
8542134bc6SMatthias Ringwald 
867a766ebfSMatthias Ringwald #if defined(ENABLE_LE_SIGNED_WRITE) || defined(ENABLE_LE_SECURE_CONNECTIONS)
87d1a1f6a4SMatthias Ringwald #define USE_CMAC_ENGINE
887a766ebfSMatthias Ringwald #endif
897a766ebfSMatthias Ringwald 
906857ad8fSMatthias Ringwald 
91968b2eafSMatthias Ringwald #define BTSTACK_TAG32(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))
92899e6e02SMatthias Ringwald 
933deb3ec6SMatthias Ringwald //
943deb3ec6SMatthias Ringwald // SM internal types and globals
953deb3ec6SMatthias Ringwald //
963deb3ec6SMatthias Ringwald 
973deb3ec6SMatthias Ringwald typedef enum {
983deb3ec6SMatthias Ringwald     DKG_W4_WORKING,
993deb3ec6SMatthias Ringwald     DKG_CALC_IRK,
1003deb3ec6SMatthias Ringwald     DKG_CALC_DHK,
1013deb3ec6SMatthias Ringwald     DKG_READY
1023deb3ec6SMatthias Ringwald } derived_key_generation_t;
1033deb3ec6SMatthias Ringwald 
1043deb3ec6SMatthias Ringwald typedef enum {
1053deb3ec6SMatthias Ringwald     RAU_IDLE,
106fbd4e238SMatthias Ringwald     RAU_GET_RANDOM,
1073deb3ec6SMatthias Ringwald     RAU_W4_RANDOM,
1083deb3ec6SMatthias Ringwald     RAU_GET_ENC,
1093deb3ec6SMatthias Ringwald     RAU_W4_ENC,
1103deb3ec6SMatthias Ringwald } random_address_update_t;
1113deb3ec6SMatthias Ringwald 
1123deb3ec6SMatthias Ringwald typedef enum {
1133deb3ec6SMatthias Ringwald     CMAC_IDLE,
1143deb3ec6SMatthias Ringwald     CMAC_CALC_SUBKEYS,
1153deb3ec6SMatthias Ringwald     CMAC_W4_SUBKEYS,
1163deb3ec6SMatthias Ringwald     CMAC_CALC_MI,
1173deb3ec6SMatthias Ringwald     CMAC_W4_MI,
1183deb3ec6SMatthias Ringwald     CMAC_CALC_MLAST,
1193deb3ec6SMatthias Ringwald     CMAC_W4_MLAST
1203deb3ec6SMatthias Ringwald } cmac_state_t;
1213deb3ec6SMatthias Ringwald 
1223deb3ec6SMatthias Ringwald typedef enum {
1233deb3ec6SMatthias Ringwald     JUST_WORKS,
12427c32905SMatthias Ringwald     PK_RESP_INPUT,       // Initiator displays PK, responder inputs PK
12527c32905SMatthias Ringwald     PK_INIT_INPUT,       // Responder displays PK, initiator inputs PK
12647fb4255SMatthias Ringwald     PK_BOTH_INPUT,       // Only input on both, both input PK
12747fb4255SMatthias Ringwald     NUMERIC_COMPARISON,  // Only numerical compparison (yes/no) on on both sides
12847fb4255SMatthias Ringwald     OOB                  // OOB available on one (SC) or both sides (legacy)
1293deb3ec6SMatthias Ringwald } stk_generation_method_t;
1303deb3ec6SMatthias Ringwald 
1313deb3ec6SMatthias Ringwald typedef enum {
1323deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_IDLE,
1333deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PENDING,
1343deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_CONFIRM,
1353deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PASSKEY,
1363deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_DECLINE
1373deb3ec6SMatthias Ringwald } sm_user_response_t;
1383deb3ec6SMatthias Ringwald 
1393deb3ec6SMatthias Ringwald typedef enum {
1403deb3ec6SMatthias Ringwald     SM_AES128_IDLE,
1413deb3ec6SMatthias Ringwald     SM_AES128_ACTIVE
1423deb3ec6SMatthias Ringwald } sm_aes128_state_t;
1433deb3ec6SMatthias Ringwald 
1443deb3ec6SMatthias Ringwald typedef enum {
1453deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_IDLE,
1463deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_GENERAL,
1473deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FOR_CONNECTION,
1483deb3ec6SMatthias Ringwald } address_resolution_mode_t;
1493deb3ec6SMatthias Ringwald 
1503deb3ec6SMatthias Ringwald typedef enum {
151a66b030fSMatthias Ringwald     ADDRESS_RESOLUTION_SUCCEEDED,
1523deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FAILED,
1533deb3ec6SMatthias Ringwald } address_resolution_event_t;
154901c000fSMatthias Ringwald 
155901c000fSMatthias Ringwald typedef enum {
15634b6528fSMatthias Ringwald     EC_KEY_GENERATION_IDLE,
1577df18c15SMatthias Ringwald     EC_KEY_GENERATION_ACTIVE,
1587df18c15SMatthias Ringwald     EC_KEY_GENERATION_DONE,
1597df18c15SMatthias Ringwald } ec_key_generation_state_t;
1607df18c15SMatthias Ringwald 
1617df18c15SMatthias Ringwald typedef enum {
1623cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_NEEDED = 1 << 0,
1633cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1,
1643cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2,
165901c000fSMatthias Ringwald } sm_state_var_t;
166901c000fSMatthias Ringwald 
167c59d0c92SMatthias Ringwald typedef enum {
168c59d0c92SMatthias Ringwald     SM_SC_OOB_IDLE,
169d1a1f6a4SMatthias Ringwald     SM_SC_OOB_W4_RANDOM,
170c59d0c92SMatthias Ringwald     SM_SC_OOB_W2_CALC_CONFIRM,
171c59d0c92SMatthias Ringwald     SM_SC_OOB_W4_CONFIRM,
172c59d0c92SMatthias Ringwald } sm_sc_oob_state_t;
173c59d0c92SMatthias Ringwald 
1746420f61eSMatthias Ringwald typedef uint8_t sm_key24_t[3];
1756420f61eSMatthias Ringwald typedef uint8_t sm_key56_t[7];
1766420f61eSMatthias Ringwald typedef uint8_t sm_key256_t[32];
1776420f61eSMatthias Ringwald 
1783deb3ec6SMatthias Ringwald //
1793deb3ec6SMatthias Ringwald // GLOBAL DATA
1803deb3ec6SMatthias Ringwald //
1813deb3ec6SMatthias Ringwald 
1822d2d4d3cSMatthias Ringwald static bool sm_initialized;
1832d2d4d3cSMatthias Ringwald 
184841468bbSMatthias Ringwald static bool test_use_fixed_local_csrk;
185841468bbSMatthias Ringwald static bool test_use_fixed_local_irk;
1863deb3ec6SMatthias Ringwald 
187192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
188192365feSMatthias Ringwald static uint8_t test_pairing_failure;
189192365feSMatthias Ringwald #endif
190192365feSMatthias Ringwald 
1913deb3ec6SMatthias Ringwald // configuration
1923deb3ec6SMatthias Ringwald static uint8_t sm_accepted_stk_generation_methods;
1933deb3ec6SMatthias Ringwald static uint8_t sm_max_encryption_key_size;
1943deb3ec6SMatthias Ringwald static uint8_t sm_min_encryption_key_size;
1953deb3ec6SMatthias Ringwald static uint8_t sm_auth_req = 0;
1963deb3ec6SMatthias Ringwald static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1973deb3ec6SMatthias Ringwald static uint8_t sm_slave_request_security;
1984b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
1991979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
2003deb3ec6SMatthias Ringwald 
201c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
202c123d999SMatthias Ringwald static bool sm_sc_only_mode;
203c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
204c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
205c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
206c59d0c92SMatthias Ringwald #endif
207c59d0c92SMatthias Ringwald 
208899e6e02SMatthias Ringwald 
2091979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
210899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
211899e6e02SMatthias Ringwald static void *                sm_tlv_context;
212899e6e02SMatthias Ringwald 
2133deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2143deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2153deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2163deb3ec6SMatthias Ringwald 
2173deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2183deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2193deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2203deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2213deb3ec6SMatthias Ringwald 
2223deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2233deb3ec6SMatthias Ringwald // ..
2243deb3ec6SMatthias Ringwald 
2253deb3ec6SMatthias Ringwald // random address update
2263deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2273deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2283deb3ec6SMatthias Ringwald 
229d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
230514d35fcSMatthias Ringwald // CMAC Calculation: General
231d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
232d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
233d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
234d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2357a766ebfSMatthias Ringwald #endif
236514d35fcSMatthias Ringwald 
237514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2387a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
239d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
240d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
241d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
242d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2437a766ebfSMatthias Ringwald #endif
244514d35fcSMatthias Ringwald 
245514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
246514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
247aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
248514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
249514d35fcSMatthias Ringwald #endif
2503deb3ec6SMatthias Ringwald 
2513deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2523deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2533deb3ec6SMatthias Ringwald static int       sm_address_resolution_ah_calculation_active;
2543deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2553deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2563deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2573deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2588f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2593deb3ec6SMatthias Ringwald 
260d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2613deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2623deb3ec6SMatthias Ringwald 
263d1a1f6a4SMatthias Ringwald // crypto
264d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
265d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
266d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
267d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2687df1ef2fSMatthias Ringwald #endif
2697df1ef2fSMatthias Ringwald 
270d1a1f6a4SMatthias Ringwald // temp storage for random data
271d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
272d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
273d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
274d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2753deb3ec6SMatthias Ringwald 
276e03e489aSMatthias Ringwald // to receive hci events
277e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
278e03e489aSMatthias Ringwald 
27989a78d34SMatthias Ringwald /* to dispatch sm event */
28089a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28189a78d34SMatthias Ringwald 
282ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
283ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
284ece00d2dSMatthias Ringwald 
28509e4d397SMatthias Ringwald // LE Secure Connections
28609e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
28709e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
288fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
28909e4d397SMatthias Ringwald #endif
290df86eb96SMatthias Ringwald 
2913deb3ec6SMatthias Ringwald //
2923deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2933deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2943deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2953deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2963deb3ec6SMatthias Ringwald //
2973deb3ec6SMatthias Ringwald 
2983deb3ec6SMatthias Ringwald // data needed for security setup
2993deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3003deb3ec6SMatthias Ringwald 
301ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3023deb3ec6SMatthias Ringwald 
3033deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3043deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
305dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3063deb3ec6SMatthias Ringwald 
3073deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
308715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
309715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3109a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3123deb3ec6SMatthias Ringwald 
3133deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3143deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3153deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
316a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
31727c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3183deb3ec6SMatthias Ringwald 
3193deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3203deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3213deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3233deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3263deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3273deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3283deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3293deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3303deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3313deb3ec6SMatthias Ringwald 
33268437d83SMatthias Ringwald     uint8_t   sm_state_vars;
333e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
334fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
335446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
336446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
337d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
338e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
339e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
340446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
341446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3422bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
343a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3447df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
345e53be891SMatthias Ringwald #endif
34627c32905SMatthias Ringwald 
3473deb3ec6SMatthias Ringwald     // Phase 3
3483deb3ec6SMatthias Ringwald 
3493deb3ec6SMatthias Ringwald     // key distribution, we generate
3503deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3513deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3523deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3533deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3543deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3553deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3563deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3573deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3583deb3ec6SMatthias Ringwald 
3593deb3ec6SMatthias Ringwald     // key distribution, received from peer
3603deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3613deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3623deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3633deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3643deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3653deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3663deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3673deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3683deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
369715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
370715a43d1SMatthias Ringwald     int       sm_le_device_index;
371715a43d1SMatthias Ringwald #endif
372e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
373e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
374e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
375e0a03c85SMatthias Ringwald #endif
3763deb3ec6SMatthias Ringwald } sm_setup_context_t;
3773deb3ec6SMatthias Ringwald 
3783deb3ec6SMatthias Ringwald //
3793deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3803deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3813deb3ec6SMatthias Ringwald 
3823deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3837149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3843deb3ec6SMatthias Ringwald 
3856b65794dSMilanka Ringwald // @return 1 if oob data is available
3863deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3873deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3884acf7b7bSMatthias Ringwald static int (*sm_get_sc_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_sc_peer_confirm, uint8_t * oob_sc_peer_random);
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 
4736b65794dSMilanka Ringwald // @return 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;
143111d10bdaSMatthias Ringwald             // compare Identity Address
143211d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
143311d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1434c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1435c7e2c1a5SMatthias Ringwald 
14363deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14373deb3ec6SMatthias Ringwald             le_db_index = i;
14383deb3ec6SMatthias Ringwald             break;
14393deb3ec6SMatthias Ringwald         }
1440c7e2c1a5SMatthias Ringwald     } else {
1441c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1442c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14433deb3ec6SMatthias Ringwald     }
14443deb3ec6SMatthias Ringwald 
14453deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14463deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1447c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14483deb3ec6SMatthias Ringwald         int i;
1449092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14503deb3ec6SMatthias Ringwald             bd_addr_t address;
1451adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14523deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1453adf5eaa9SMatthias Ringwald             // skip unused entries
1454adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14553deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14565df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14573deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14583deb3ec6SMatthias Ringwald                 le_db_index = i;
14593deb3ec6SMatthias Ringwald                 break;
14603deb3ec6SMatthias Ringwald             }
14613deb3ec6SMatthias Ringwald         }
14623deb3ec6SMatthias Ringwald     }
14633deb3ec6SMatthias Ringwald 
14643deb3ec6SMatthias Ringwald     // if not found, add to db
146502b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14663deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14673deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
146802b02cffSMatthias Ringwald         new_to_le_device_db = true;
14693deb3ec6SMatthias Ringwald     }
14703deb3ec6SMatthias Ringwald 
14713deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14723deb3ec6SMatthias Ringwald 
147302b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
147402b02cffSMatthias Ringwald         if (!new_to_le_device_db){
147502b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
147602b02cffSMatthias Ringwald         }
147702b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
147802b02cffSMatthias Ringwald #else
147902b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
148002b02cffSMatthias Ringwald #endif
148102b02cffSMatthias Ringwald 
148248163929SMatthias 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);
1483e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14847710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
148548163929SMatthias Ringwald 
1486eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14873deb3ec6SMatthias Ringwald         // store local CSRK
1488715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1489715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14903deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
14913deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14923deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
14933deb3ec6SMatthias Ringwald         }
14943deb3ec6SMatthias Ringwald 
14953deb3ec6SMatthias Ringwald         // store remote CSRK
14963deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14973deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
14983deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
14993deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15003deb3ec6SMatthias Ringwald         }
1501eda85fbfSMatthias Ringwald #endif
150278f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
150378f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1504e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
150578f44163SMatthias Ringwald             uint8_t zero_rand[8];
150678f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
150778f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15083dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
150978f44163SMatthias Ringwald         }
151078f44163SMatthias Ringwald 
1511e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151278f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151378f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1514e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15153deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15163dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
151778f44163SMatthias Ringwald 
15183deb3ec6SMatthias Ringwald         }
15193deb3ec6SMatthias Ringwald     }
152055f09f49SMatthias Ringwald }
152155f09f49SMatthias Ringwald 
152255f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
152355f09f49SMatthias Ringwald 
152455f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
152555f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
152655f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
152755f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
152855f09f49SMatthias Ringwald 
152955f09f49SMatthias Ringwald     if (bonding_enabled){
153055f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
153127ef8bc8SMatthias Ringwald     } else {
153227ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153327ef8bc8SMatthias Ringwald     }
15343deb3ec6SMatthias Ringwald }
15353deb3ec6SMatthias Ringwald 
1536688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1537f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1538688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1539688a08f9SMatthias Ringwald }
1540688a08f9SMatthias Ringwald 
1541688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1542688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1543688a08f9SMatthias Ringwald }
1544688a08f9SMatthias Ringwald 
15459af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1546688a08f9SMatthias Ringwald 
1547dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1548945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1549f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1550dc300847SMatthias Ringwald 
1551b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1552b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15531f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1554b90c4e75SMatthias Ringwald     } else {
1555b90c4e75SMatthias 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);
1556b35a3de2SMatthias Ringwald     }
1557b35a3de2SMatthias Ringwald }
1558b35a3de2SMatthias Ringwald 
1559688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
156042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1561688a08f9SMatthias Ringwald         // Responder
15624acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15634acf7b7bSMatthias Ringwald             // generate Nb
15644acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15656ca80073SMatthias 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);
15664acf7b7bSMatthias Ringwald         } else {
1567688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15684acf7b7bSMatthias Ringwald         }
1569688a08f9SMatthias Ringwald     } else {
1570688a08f9SMatthias Ringwald         // Initiator role
1571688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1572688a08f9SMatthias Ringwald             case JUST_WORKS:
1573dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1574688a08f9SMatthias Ringwald                 break;
1575688a08f9SMatthias Ringwald 
157647fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1577bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1578688a08f9SMatthias Ringwald                 break;
1579688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1580688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158147fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15824ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1583b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1584688a08f9SMatthias Ringwald                 } else {
1585dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1586688a08f9SMatthias Ringwald                 }
1587688a08f9SMatthias Ringwald                 break;
1588688a08f9SMatthias Ringwald             case OOB:
158965a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1590688a08f9SMatthias Ringwald                 break;
15917bbeb3adSMilanka Ringwald             default:
15927bbeb3adSMilanka Ringwald                 btstack_assert(false);
15937bbeb3adSMilanka Ringwald                 break;
1594688a08f9SMatthias Ringwald         }
1595688a08f9SMatthias Ringwald     }
1596688a08f9SMatthias Ringwald }
1597688a08f9SMatthias Ringwald 
1598aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1599688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1600688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1601688a08f9SMatthias Ringwald 
1602c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1603c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1604a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1605c59d0c92SMatthias Ringwald         return;
1606c59d0c92SMatthias Ringwald     }
1607c59d0c92SMatthias Ringwald 
1608bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1609bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16106857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16112bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1612b4f65634SMatthias Ringwald #endif
1613bd57ffebSMatthias Ringwald 
1614bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1615aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16166535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1617bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1618aec94140SMatthias Ringwald             break;
1619688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1620688a08f9SMatthias Ringwald             // check
1621688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1622bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1623688a08f9SMatthias Ringwald                 break;
1624688a08f9SMatthias Ringwald             }
1625bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1626688a08f9SMatthias Ringwald             break;
1627901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1628901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1629901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1630901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1631901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1632019005a0SMatthias Ringwald             break;
1633019005a0SMatthias Ringwald         }
16340346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16356535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1636bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16370346c37cSMatthias Ringwald             break;
16380346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16396535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1640bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16410346c37cSMatthias Ringwald             break;
16420346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1643b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1644b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1645b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1646b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16476535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16486535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1649893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1650bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1651019005a0SMatthias Ringwald             break;
1652901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16536535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1655901c000fSMatthias Ringwald                 // responder
1656901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1657901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1658901c000fSMatthias Ringwald                 } else {
1659901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1660901c000fSMatthias Ringwald                 }
1661901c000fSMatthias Ringwald             } else {
1662901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1663901c000fSMatthias Ringwald             }
1664901c000fSMatthias Ringwald             break;
1665901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1666901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1667901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1668aec94140SMatthias Ringwald                 break;
1669aec94140SMatthias Ringwald             }
167042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1671901c000fSMatthias Ringwald                 // responder
1672901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1673901c000fSMatthias Ringwald             } else {
1674901c000fSMatthias Ringwald                 // initiator
1675901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1676bd57ffebSMatthias Ringwald             }
1677901c000fSMatthias Ringwald             break;
16786857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
167957132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16806535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168157132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16822bacf595SMatthias Ringwald             break;
168357132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16842bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16852bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16862bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16878974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168855160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16898974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16902bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16912bacf595SMatthias Ringwald             } else {
16922bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16932bacf595SMatthias Ringwald             }
16940ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16952bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16962bacf595SMatthias Ringwald             break;
1697e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1698e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1699e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1700e0a03c85SMatthias Ringwald             break;
1701e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1702e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1703e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1704e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1705e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1706e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1707e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1708c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1709e0a03c85SMatthias Ringwald             break;
1710bdb14b0eSMatthias Ringwald #endif
1711bd57ffebSMatthias Ringwald         default:
1712bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1713bd57ffebSMatthias Ringwald             break;
1714bd57ffebSMatthias Ringwald     }
171570b44dd4SMatthias Ringwald     sm_trigger_run();
1716aec94140SMatthias Ringwald }
1717aec94140SMatthias Ringwald 
1718688a08f9SMatthias 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){
1719dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1720aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17216535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17226535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1723aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1724aec94140SMatthias Ringwald     log_info("f4 key");
1725aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1726aec94140SMatthias Ringwald     log_info("f4 message");
1727dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1728d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1729aec94140SMatthias Ringwald }
1730aec94140SMatthias Ringwald 
17310346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17320346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17330346c37cSMatthias Ringwald 
17340346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17358334d3d8SMatthias Ringwald 
17368334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17378334d3d8SMatthias Ringwald 
173840c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17390346c37cSMatthias Ringwald     // calculate salt for f5
17400346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17410346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17426535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1743d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17440346c37cSMatthias Ringwald }
17450346c37cSMatthias Ringwald 
17460346c37cSMatthias 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){
17470346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17480346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17490346c37cSMatthias Ringwald 
17500346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17510346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17566535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17576535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17580346c37cSMatthias Ringwald     log_info("f5 key");
17590346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17600346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17610346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1762d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17630346c37cSMatthias Ringwald }
17640346c37cSMatthias Ringwald 
17650346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17660346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17670346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17680346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17696535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17706535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
177142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17720346c37cSMatthias Ringwald         // responder
17730346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17740346c37cSMatthias Ringwald     } else {
17750346c37cSMatthias Ringwald         // initiator
17760346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17770346c37cSMatthias Ringwald     }
17780346c37cSMatthias Ringwald }
17790346c37cSMatthias Ringwald 
17800346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17810346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17820346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17830346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17840346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17850346c37cSMatthias Ringwald     // 1..52 setup before
17860346c37cSMatthias Ringwald     log_info("f5 key");
17870346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17880346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17890346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1790d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17910346c37cSMatthias Ringwald }
1792f92edc8eSMatthias Ringwald 
17930346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17940346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17950346c37cSMatthias Ringwald }
17960346c37cSMatthias Ringwald 
179731f061fbSMatthias 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){
17986535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18006535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18026535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18036535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
180431f061fbSMatthias Ringwald }
180531f061fbSMatthias Ringwald 
180631f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180731f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180831f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1809dc300847SMatthias Ringwald     log_info("f6 key");
1810dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1811dc300847SMatthias Ringwald     log_info("f6 message");
1812dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1813d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1814dc300847SMatthias Ringwald }
1815dc300847SMatthias Ringwald 
1816f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1817f92edc8eSMatthias Ringwald // - U is 256 bits
1818f92edc8eSMatthias Ringwald // - V is 256 bits
1819f92edc8eSMatthias Ringwald // - X is 128 bits
1820f92edc8eSMatthias Ringwald // - Y is 128 bits
1821bd57ffebSMatthias 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){
1822bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1823bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18246535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18256535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18266535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1827f92edc8eSMatthias Ringwald     log_info("g2 key");
1828f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1829f92edc8eSMatthias Ringwald     log_info("g2 message");
18302bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1831d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1832f92edc8eSMatthias Ringwald }
1833f92edc8eSMatthias Ringwald 
1834b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1835f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
183642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1837f92edc8eSMatthias Ringwald         // responder
1838fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1839f92edc8eSMatthias Ringwald     } else {
1840f92edc8eSMatthias Ringwald         // initiator
1841fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1842f92edc8eSMatthias Ringwald     }
1843f92edc8eSMatthias Ringwald }
1844f92edc8eSMatthias Ringwald 
1845945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18469af0f475SMatthias Ringwald     uint8_t z = 0;
184740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18489af0f475SMatthias Ringwald         // some form of passkey
18499af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18504ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18519af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18529af0f475SMatthias Ringwald     }
1853fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18549af0f475SMatthias Ringwald }
1855688a08f9SMatthias Ringwald 
1856688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1857a680ba6bSMatthias Ringwald     // OOB
1858a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18594acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18604acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18614acf7b7bSMatthias Ringwald         } else {
18624acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18634acf7b7bSMatthias Ringwald         }
1864a680ba6bSMatthias Ringwald         return;
1865a680ba6bSMatthias Ringwald     }
1866a680ba6bSMatthias Ringwald 
1867688a08f9SMatthias Ringwald     uint8_t z = 0;
186840c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1869688a08f9SMatthias Ringwald         // some form of passkey
1870688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1871688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18724ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1873688a08f9SMatthias Ringwald     }
1874fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1875688a08f9SMatthias Ringwald }
1876688a08f9SMatthias Ringwald 
18770346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1878505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18793cf37b8cSMatthias Ringwald 
18803cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18813cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18823cf37b8cSMatthias Ringwald         return;
18833cf37b8cSMatthias Ringwald     } else {
18843cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18853cf37b8cSMatthias Ringwald     }
1886d1a1f6a4SMatthias Ringwald }
18873cf37b8cSMatthias Ringwald 
1888d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1889f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1890f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1891f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1892f3582630SMatthias Ringwald 
1893d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1894d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1895d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1896d1a1f6a4SMatthias Ringwald     // trigger next step
1897d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1898d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1899d1a1f6a4SMatthias Ringwald     }
190070b44dd4SMatthias Ringwald     sm_trigger_run();
1901dc300847SMatthias Ringwald }
1902dc300847SMatthias Ringwald 
1903dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1904dc300847SMatthias Ringwald     // calculate DHKCheck
1905dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1906dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1907dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19086535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19096535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1910dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1911dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1912dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1913dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1914dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1915dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1916dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1917dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1919dc300847SMatthias Ringwald         // responder
192031f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
192131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1922dc300847SMatthias Ringwald     } else {
1923dc300847SMatthias Ringwald         // initiator
192431f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1926dc300847SMatthias Ringwald     }
1927dc300847SMatthias Ringwald }
1928dc300847SMatthias Ringwald 
1929019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1930019005a0SMatthias Ringwald     // validate E = f6()
1931019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1932019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1933019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19346535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19356535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1936019005a0SMatthias Ringwald 
1937019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1938019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1939019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1940019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1941019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1942019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1943019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1944019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
194542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1946019005a0SMatthias Ringwald         // responder
194731f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1949019005a0SMatthias Ringwald     } else {
1950019005a0SMatthias Ringwald         // initiator
195131f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
195231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1953019005a0SMatthias Ringwald     }
1954019005a0SMatthias Ringwald }
19552bacf595SMatthias Ringwald 
195655c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19572bacf595SMatthias Ringwald 
19582bacf595SMatthias Ringwald //
19592bacf595SMatthias Ringwald // Link Key Conversion Function h6
19602bacf595SMatthias Ringwald //
196157132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19622bacf595SMatthias Ringwald // - W is 128 bits
19632bacf595SMatthias Ringwald // - keyID is 32 bits
19642bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19652bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19662bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19672bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19682bacf595SMatthias Ringwald     log_info("h6 key");
19692bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19702bacf595SMatthias Ringwald     log_info("h6 message");
19712bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1972d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19732bacf595SMatthias Ringwald }
197457132f12SMatthias Ringwald //
197557132f12SMatthias Ringwald // Link Key Conversion Function h7
197657132f12SMatthias Ringwald //
197757132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197857132f12SMatthias Ringwald // - SALT is 128 bits
197957132f12SMatthias Ringwald // - W    is 128 bits
198057132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
198157132f12SMatthias Ringwald 	const uint16_t message_len = 16;
198257132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
198357132f12SMatthias Ringwald 	log_info("h7 key");
198457132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
198557132f12SMatthias Ringwald 	log_info("h7 message");
198657132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198757132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198857132f12SMatthias Ringwald }
19892bacf595SMatthias Ringwald 
1990b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1991b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1992b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1993b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
199457132f12SMatthias Ringwald 
1995c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1996b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19972bacf595SMatthias Ringwald }
19982bacf595SMatthias Ringwald 
1999e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2000e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2001e0a03c85SMatthias Ringwald }
2002e0a03c85SMatthias Ringwald 
20032bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20042bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20052bacf595SMatthias Ringwald }
20062bacf595SMatthias Ringwald 
2007e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2008e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2009e0a03c85SMatthias Ringwald }
2010e0a03c85SMatthias Ringwald 
2011c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
201257132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
201357132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
201457132f12SMatthias Ringwald }
2015e0a03c85SMatthias Ringwald 
2016e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2017e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2018e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2019e0a03c85SMatthias Ringwald }
2020e0a03c85SMatthias Ringwald 
2021c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2022e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2023e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2024e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2025e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2026e0a03c85SMatthias Ringwald }
2027e0a03c85SMatthias Ringwald 
2028c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2029c18be159SMatthias 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;
2030c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2031c18be159SMatthias Ringwald }
2032c18be159SMatthias Ringwald 
20339af0f475SMatthias Ringwald #endif
20349af0f475SMatthias Ringwald 
203555c62cf5SMatthias Ringwald #endif
203655c62cf5SMatthias Ringwald 
2037613da3deSMatthias Ringwald // key management legacy connections:
2038613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2039613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2040613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2041613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2042613da3deSMatthias Ringwald 
2043613da3deSMatthias Ringwald // key management secure connections:
2044613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2045613da3deSMatthias Ringwald 
204642134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20475829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20485829ebe2SMatthias Ringwald     int encryption_key_size;
20495829ebe2SMatthias Ringwald     int authenticated;
20505829ebe2SMatthias Ringwald     int authorized;
20513dc3a67dSMatthias Ringwald     int secure_connection;
20525829ebe2SMatthias Ringwald 
20535829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20545829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20553dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20563dc3a67dSMatthias 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);
20575829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20585829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20595829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20603dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20615829ebe2SMatthias Ringwald }
206242134bc6SMatthias Ringwald #endif
2063bd57ffebSMatthias Ringwald 
206442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
206559066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20666535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
206759066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
206859066796SMatthias Ringwald     // re-establish used key encryption size
206959066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20704ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
207159066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20724ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20733dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20743dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
207559066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
207659066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
207759066796SMatthias Ringwald }
207842134bc6SMatthias Ringwald #endif
207959066796SMatthias Ringwald 
20803deb3ec6SMatthias Ringwald // distributed key generation
2081d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20823deb3ec6SMatthias Ringwald     switch (dkg_state){
20833deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20843deb3ec6SMatthias Ringwald             // already busy?
20853deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2086d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20873deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2088d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2089d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2090d1a1f6a4SMatthias 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);
2091d7f1c72eSMatthias Ringwald                 return true;
20923deb3ec6SMatthias Ringwald             }
20933deb3ec6SMatthias Ringwald             break;
20943deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20953deb3ec6SMatthias Ringwald             // already busy?
20963deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2097d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20983deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2099d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2100d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2101d1a1f6a4SMatthias 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);
2102d7f1c72eSMatthias Ringwald                 return true;
21033deb3ec6SMatthias Ringwald             }
21043deb3ec6SMatthias Ringwald             break;
21053deb3ec6SMatthias Ringwald         default:
21063deb3ec6SMatthias Ringwald             break;
21073deb3ec6SMatthias Ringwald     }
2108d7f1c72eSMatthias Ringwald     return false;
2109d7f1c72eSMatthias Ringwald }
21103deb3ec6SMatthias Ringwald 
21113deb3ec6SMatthias Ringwald // random address updates
2112d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21133deb3ec6SMatthias Ringwald     switch (rau_state){
2114fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2115fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21165b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2117d7f1c72eSMatthias Ringwald             return true;
21183deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21193deb3ec6SMatthias Ringwald             // already busy?
21203deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2121d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2122d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2123d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2124d7f1c72eSMatthias Ringwald                 return true;
21253deb3ec6SMatthias Ringwald             }
21263deb3ec6SMatthias Ringwald             break;
21273deb3ec6SMatthias Ringwald         default:
21283deb3ec6SMatthias Ringwald             break;
21293deb3ec6SMatthias Ringwald     }
2130d7f1c72eSMatthias Ringwald     return false;
2131d7f1c72eSMatthias Ringwald }
21323deb3ec6SMatthias Ringwald 
21333deb3ec6SMatthias Ringwald // CSRK Lookup
2134d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2135d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2136d7f1c72eSMatthias Ringwald 
21373deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21383deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21393deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2140665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2141665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21423deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21433deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21443deb3ec6SMatthias Ringwald                 // and start lookup
21453deb3ec6SMatthias 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);
21463deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21473deb3ec6SMatthias Ringwald                 break;
21483deb3ec6SMatthias Ringwald             }
21493deb3ec6SMatthias Ringwald         }
21503deb3ec6SMatthias Ringwald     }
21513deb3ec6SMatthias Ringwald 
21523deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21533deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2154665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21553deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2156665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21573deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21583deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21593deb3ec6SMatthias Ringwald         }
21603deb3ec6SMatthias Ringwald     }
21613deb3ec6SMatthias Ringwald 
21623deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21633deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2164092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2165092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2166adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21673deb3ec6SMatthias Ringwald             bd_addr_t addr;
21683deb3ec6SMatthias Ringwald             sm_key_t irk;
21693deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21703deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21713deb3ec6SMatthias Ringwald 
2172adf5eaa9SMatthias Ringwald             // skip unused entries
2173adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2174adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2175adf5eaa9SMatthias Ringwald                 continue;
2176adf5eaa9SMatthias Ringwald             }
2177adf5eaa9SMatthias Ringwald 
21785df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21793deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2180a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21813deb3ec6SMatthias Ringwald                 break;
21823deb3ec6SMatthias Ringwald             }
21833deb3ec6SMatthias Ringwald 
2184a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2185a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21863deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21873deb3ec6SMatthias Ringwald                 continue;
21883deb3ec6SMatthias Ringwald             }
21893deb3ec6SMatthias Ringwald 
21903deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21913deb3ec6SMatthias Ringwald 
21923deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21938314c363SMatthias Ringwald             log_info_key("IRK", irk);
21943deb3ec6SMatthias Ringwald 
21956535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2196d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21973deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2198d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2199d1a1f6a4SMatthias 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);
2200d7f1c72eSMatthias Ringwald             return true;
22013deb3ec6SMatthias Ringwald         }
22023deb3ec6SMatthias Ringwald 
2203092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22043deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22053deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22063deb3ec6SMatthias Ringwald         }
22073deb3ec6SMatthias Ringwald     }
2208d7f1c72eSMatthias Ringwald     return false;
2209d7f1c72eSMatthias Ringwald }
22103deb3ec6SMatthias Ringwald 
2211d7f1c72eSMatthias Ringwald // SC OOB
2212d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2213c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2214c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2215c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2216c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2217c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2218c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2219d7f1c72eSMatthias Ringwald             return true;
2220c59d0c92SMatthias Ringwald         default:
2221c59d0c92SMatthias Ringwald             break;
2222c59d0c92SMatthias Ringwald     }
2223c59d0c92SMatthias Ringwald #endif
2224d7f1c72eSMatthias Ringwald     return false;
2225d7f1c72eSMatthias Ringwald }
2226275aafe8SMatthias Ringwald 
2227687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2228687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2229687a03c8SMatthias Ringwald }
2230687a03c8SMatthias Ringwald 
223141d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2232d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2233d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
223441d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2235e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
223641d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
223741d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
223841d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2239f4935286SMatthias Ringwald 
2240f4935286SMatthias Ringwald             // general
2241f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2242f4935286SMatthias Ringwald                 uint8_t buffer[2];
2243f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2244f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2245f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2246687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2247f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2248f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2249f4935286SMatthias Ringwald                 break;
2250f4935286SMatthias Ringwald             }
2251f4935286SMatthias Ringwald 
225241d32297SMatthias Ringwald             // responder side
225341d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
225441d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
225541d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2256d7f1c72eSMatthias Ringwald                 return true;
22574b8b5afeSMatthias Ringwald 
22584b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22594b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22604b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22614b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2262e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22634b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22644b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2265d7f1c72eSMatthias Ringwald                         return true;
22664b8b5afeSMatthias Ringwald                     default:
22674b8b5afeSMatthias Ringwald                         break;
22684b8b5afeSMatthias Ringwald                 }
22694b8b5afeSMatthias Ringwald                 break;
22704b8b5afeSMatthias Ringwald #endif
227141d32297SMatthias Ringwald             default:
227241d32297SMatthias Ringwald                 break;
227341d32297SMatthias Ringwald         }
227441d32297SMatthias Ringwald     }
2275d7f1c72eSMatthias Ringwald     return false;
2276d7f1c72eSMatthias Ringwald }
22773deb3ec6SMatthias Ringwald 
2278d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22793deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2280d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22813deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22827149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2283665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22843deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22853deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22861979f09cSMatthias Ringwald         bool done = true;
22873deb3ec6SMatthias Ringwald         int err;
228842134bc6SMatthias Ringwald         UNUSED(err);
228934b6528fSMatthias Ringwald 
229034b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
229134b6528fSMatthias Ringwald         // assert ec key is ready
2292505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2293178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2294178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
229534b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
229634b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
229734b6528fSMatthias Ringwald             }
229834b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
229934b6528fSMatthias Ringwald                 continue;
230034b6528fSMatthias Ringwald             }
230134b6528fSMatthias Ringwald         }
230234b6528fSMatthias Ringwald #endif
230334b6528fSMatthias Ringwald 
23043deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
230542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23063deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23073deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
230842134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2309549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
231006cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
231187014f74SMatthias Ringwald #endif
231287014f74SMatthias Ringwald #endif
231334c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23145567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
231534c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2316549ad5d2SMatthias Ringwald #endif
2317c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2318c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2319c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2320c18be159SMatthias Ringwald #endif
232187014f74SMatthias Ringwald 				// just lock context
232287014f74SMatthias Ringwald 				break;
23233deb3ec6SMatthias Ringwald             default:
23241979f09cSMatthias Ringwald                 done = false;
23253deb3ec6SMatthias Ringwald                 break;
23263deb3ec6SMatthias Ringwald         }
23273deb3ec6SMatthias Ringwald         if (done){
23287149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23297149bde5SMatthias 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);
23303deb3ec6SMatthias Ringwald         }
23313deb3ec6SMatthias Ringwald     }
2332d7f1c72eSMatthias Ringwald }
2333d7f1c72eSMatthias Ringwald 
2334403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2335403280b9SMatthias Ringwald     int i;
2336403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2337403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2338403280b9SMatthias Ringwald     uint8_t action = 0;
2339403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2340403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2341403280b9SMatthias Ringwald             bool clear_flag = true;
2342403280b9SMatthias Ringwald             switch (i){
2343403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2344403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2345403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2346403280b9SMatthias Ringwald                 default:
2347403280b9SMatthias Ringwald                     break;
2348403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2349403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2350403280b9SMatthias Ringwald                     num_actions--;
2351403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2352403280b9SMatthias Ringwald                     break;
2353403280b9SMatthias Ringwald             }
2354403280b9SMatthias Ringwald             if (clear_flag){
2355403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2356403280b9SMatthias Ringwald             }
2357403280b9SMatthias Ringwald             action = i;
2358403280b9SMatthias Ringwald             break;
2359403280b9SMatthias Ringwald         }
2360403280b9SMatthias Ringwald     }
2361403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2362403280b9SMatthias Ringwald 
2363403280b9SMatthias Ringwald     // send keypress notification
2364403280b9SMatthias Ringwald     uint8_t buffer[2];
2365403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2366403280b9SMatthias Ringwald     buffer[1] = action;
2367687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2368403280b9SMatthias Ringwald 
2369403280b9SMatthias Ringwald     // try
2370403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2371403280b9SMatthias Ringwald }
2372403280b9SMatthias Ringwald 
2373403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2374403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2375403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2376403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2377403280b9SMatthias Ringwald         uint8_t buffer[17];
2378403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2379403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2380687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2381403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2382403280b9SMatthias Ringwald         return;
2383403280b9SMatthias Ringwald     }
2384403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2385403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2386403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2387403280b9SMatthias Ringwald         uint8_t buffer[11];
2388403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2389403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2390403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2391687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2392403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2393403280b9SMatthias Ringwald         return;
2394403280b9SMatthias Ringwald     }
2395403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2396403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2397403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2398403280b9SMatthias Ringwald         uint8_t buffer[17];
2399403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2400403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2401687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2402403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2403403280b9SMatthias Ringwald         return;
2404403280b9SMatthias Ringwald     }
2405403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2406403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2407403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2408403280b9SMatthias Ringwald         bd_addr_t local_address;
2409403280b9SMatthias Ringwald         uint8_t buffer[8];
2410403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2411403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2412403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2413403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2414403280b9SMatthias Ringwald                 // public or static random
2415403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2416403280b9SMatthias Ringwald                 break;
2417403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2418403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2419403280b9SMatthias Ringwald                 // fallback to public
2420403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2421403280b9SMatthias Ringwald                 buffer[1] = 0;
2422403280b9SMatthias Ringwald                 break;
2423403280b9SMatthias Ringwald             default:
2424403280b9SMatthias Ringwald                 btstack_assert(false);
2425403280b9SMatthias Ringwald                 break;
2426403280b9SMatthias Ringwald         }
2427403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2428687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2429403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2430403280b9SMatthias Ringwald         return;
2431403280b9SMatthias Ringwald     }
2432403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2433403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2434403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2435403280b9SMatthias Ringwald 
2436403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2437403280b9SMatthias Ringwald         // hack to reproduce test runs
2438403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2439403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2440403280b9SMatthias Ringwald                     }
2441403280b9SMatthias Ringwald 
2442403280b9SMatthias Ringwald                     // store local CSRK
2443403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2444403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2445403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2446403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2447403280b9SMatthias Ringwald                     }
2448403280b9SMatthias Ringwald #endif
2449403280b9SMatthias Ringwald 
2450403280b9SMatthias Ringwald         uint8_t buffer[17];
2451403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2452403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2453687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2454403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2455403280b9SMatthias Ringwald         return;
2456403280b9SMatthias Ringwald     }
2457403280b9SMatthias Ringwald     btstack_assert(false);
2458403280b9SMatthias Ringwald }
2459403280b9SMatthias Ringwald 
2460bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2461bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2462bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2463bbd73538SMatthias Ringwald     // - use secure connections
2464bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2465bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2466bbd73538SMatthias 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;
2467bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2468bbd73538SMatthias Ringwald     // - need identity address / public addr
2469bbd73538SMatthias 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);
2470bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2471bbd73538SMatthias 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)
2472bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2473bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2474bbd73538SMatthias 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.
2475bbd73538SMatthias Ringwald     uint8_t link_key[16];
2476bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2477bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2478bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2479bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2480bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2481bbd73538SMatthias Ringwald         return false;
2482bbd73538SMatthias Ringwald     }
2483bbd73538SMatthias Ringwald     // get started (all of the above are true)
2484bbd73538SMatthias Ringwald     return true;
2485bbd73538SMatthias Ringwald #else
2486bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2487bbd73538SMatthias Ringwald 	return false;
2488bbd73538SMatthias Ringwald #endif
2489bbd73538SMatthias Ringwald }
2490bbd73538SMatthias Ringwald 
24916f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24926f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24936f7422f1SMatthias 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;
24946f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24956f7422f1SMatthias Ringwald     } else {
24966f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24976f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24986f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24996f7422f1SMatthias Ringwald     }
25006f7422f1SMatthias Ringwald }
25016f7422f1SMatthias Ringwald 
2502af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2503af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2504af7ef9d1SMatthias 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;
2505af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2506af7ef9d1SMatthias Ringwald     } else {
2507af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2508af7ef9d1SMatthias Ringwald     }
2509af7ef9d1SMatthias Ringwald }
2510af7ef9d1SMatthias Ringwald 
2511d7f1c72eSMatthias Ringwald static void sm_run(void){
2512d7f1c72eSMatthias Ringwald 
2513d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2514d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2515d7f1c72eSMatthias Ringwald 
2516d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2517d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2518d7f1c72eSMatthias Ringwald 
2519d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2520d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2521d7f1c72eSMatthias Ringwald 
2522d7f1c72eSMatthias Ringwald     bool done;
2523d7f1c72eSMatthias Ringwald 
2524d7f1c72eSMatthias Ringwald     //
2525d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2526d7f1c72eSMatthias Ringwald     //
2527d7f1c72eSMatthias Ringwald 
2528d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2529d7f1c72eSMatthias Ringwald     if (done) return;
2530d7f1c72eSMatthias Ringwald 
2531d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2532d7f1c72eSMatthias Ringwald     if (done) return;
2533d7f1c72eSMatthias Ringwald 
2534d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2535d7f1c72eSMatthias Ringwald     if (done) return;
2536d7f1c72eSMatthias Ringwald 
2537d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2538d7f1c72eSMatthias Ringwald     if (done) return;
2539d7f1c72eSMatthias Ringwald 
2540d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2541d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2542d7f1c72eSMatthias Ringwald 
2543d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2544d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2545d7f1c72eSMatthias Ringwald     if (done) return;
2546d7f1c72eSMatthias Ringwald 
2547d7f1c72eSMatthias Ringwald     //
2548d7f1c72eSMatthias Ringwald     // active connection handling
2549d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2550d7f1c72eSMatthias Ringwald 
2551d7f1c72eSMatthias Ringwald     while (true) {
2552d7f1c72eSMatthias Ringwald 
2553d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2554d7f1c72eSMatthias Ringwald 
2555d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25563deb3ec6SMatthias Ringwald 
25573deb3ec6SMatthias Ringwald         //
25583deb3ec6SMatthias Ringwald         // active connection handling
25593deb3ec6SMatthias Ringwald         //
25603deb3ec6SMatthias Ringwald 
25613cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25623cf37b8cSMatthias Ringwald         if (!connection) {
25633cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25643cf37b8cSMatthias Ringwald             return;
25653cf37b8cSMatthias Ringwald         }
25663cf37b8cSMatthias Ringwald 
25673deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25687149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25697149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25707149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2571b170b20fSMatthias Ringwald             return;
2572b170b20fSMatthias Ringwald         }
25733deb3ec6SMatthias Ringwald 
25743d7fe1e9SMatthias Ringwald         // send keypress notifications
2575dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2576403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2577d7471931SMatthias Ringwald             return;
25783d7fe1e9SMatthias Ringwald         }
25793d7fe1e9SMatthias Ringwald 
25803deb3ec6SMatthias Ringwald         int key_distribution_flags;
258142134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2582b6afa23eSMatthias Ringwald 		int err;
2583b6afa23eSMatthias Ringwald 		UNUSED(err);
25849b75de03SMatthias Ringwald         bool have_ltk;
25859b75de03SMatthias Ringwald         uint8_t ltk[16];
25863deb3ec6SMatthias Ringwald 
25873deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2588dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2589dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2590dd4a08fbSMatthias Ringwald         }
25913deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25923deb3ec6SMatthias Ringwald 
2593f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2594aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2595aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2596aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2597aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2598aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2599aec94140SMatthias Ringwald                 break;
2600688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2601688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2602688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2603688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2604688a08f9SMatthias Ringwald                 break;
2605dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2606dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2607dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2608dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2609dc300847SMatthias Ringwald                 break;
2610019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2611b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2612019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26130346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26140346c37cSMatthias Ringwald                 break;
26150346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2616b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26170346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26180346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26190346c37cSMatthias Ringwald                 break;
26200346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2621b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26220346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26230346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26240346c37cSMatthias Ringwald                 break;
26250346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2626b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26270346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26280346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2629019005a0SMatthias Ringwald                 break;
2630bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2631b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2632bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2633b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2634bd57ffebSMatthias Ringwald                 break;
2635e0a03c85SMatthias Ringwald #endif
2636e0a03c85SMatthias Ringwald 
263742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26383deb3ec6SMatthias Ringwald             // initiator side
2639f32b7a88SMatthias Ringwald 
26405567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2641f32b7a88SMatthias Ringwald 				sm_reset_setup();
2642f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2643daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2644f32b7a88SMatthias Ringwald 
26453deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26469c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26475567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26483deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2649c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2650c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26513deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26523deb3ec6SMatthias Ringwald                 return;
26533deb3ec6SMatthias Ringwald             }
26543deb3ec6SMatthias Ringwald 
2655b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2656b26f445fSMatthias Ringwald 				sm_reset_setup();
2657b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2658b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2659d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2660b26f445fSMatthias Ringwald 
26611ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26623deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2663687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26643deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26653deb3ec6SMatthias Ringwald                 break;
266642134bc6SMatthias Ringwald #endif
26673deb3ec6SMatthias Ringwald 
266827c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
266941d32297SMatthias Ringwald 
2670c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26711979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26721979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
267327c32905SMatthias Ringwald                 uint8_t buffer[65];
267427c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
267527c32905SMatthias Ringwald                 //
2676fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2677fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2678e53be891SMatthias Ringwald 
2679349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2680349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2681349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2682349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2683349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2684349d0adbSMatthias Ringwald                 }
2685349d0adbSMatthias Ringwald #endif
2686349d0adbSMatthias Ringwald 
268745a61d50SMatthias Ringwald                 // stk generation method
268845a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
268945a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
269045a61d50SMatthias Ringwald                     case JUST_WORKS:
269147fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
269242134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269307036a04SMatthias Ringwald                             // responder
26941979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2695b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
269627c32905SMatthias Ringwald                         } else {
269707036a04SMatthias Ringwald                             // initiator
2698c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
269927c32905SMatthias Ringwald                         }
270045a61d50SMatthias Ringwald                         break;
270145a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
270245a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
270347fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
270407036a04SMatthias Ringwald                         // use random TK for display
27056535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27066535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
270745a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
270807036a04SMatthias Ringwald 
270942134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
271045a61d50SMatthias Ringwald                             // responder
2711c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
271245a61d50SMatthias Ringwald                         } else {
271345a61d50SMatthias Ringwald                             // initiator
2714c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271545a61d50SMatthias Ringwald                         }
27161979f09cSMatthias Ringwald                         trigger_user_response = true;
271745a61d50SMatthias Ringwald                         break;
271845a61d50SMatthias Ringwald                     case OOB:
271965a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272065a9a04eSMatthias Ringwald                             // responder
272165a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
272265a9a04eSMatthias Ringwald                         } else {
272365a9a04eSMatthias Ringwald                             // initiator
272465a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272565a9a04eSMatthias Ringwald                         }
272645a61d50SMatthias Ringwald                         break;
27277bbeb3adSMilanka Ringwald                     default:
27287bbeb3adSMilanka Ringwald                         btstack_assert(false);
27297bbeb3adSMilanka Ringwald                         break;
273045a61d50SMatthias Ringwald                 }
273145a61d50SMatthias Ringwald 
2732687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
273327c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2734644c6a1dSMatthias Ringwald 
2735b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2736644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2737644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2738644c6a1dSMatthias Ringwald                 }
2739b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2740b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2741b90c4e75SMatthias Ringwald                 }
274227c32905SMatthias Ringwald                 break;
274327c32905SMatthias Ringwald             }
2744c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2745e53be891SMatthias Ringwald                 uint8_t buffer[17];
2746e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27479af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
274842134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2749c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2750e53be891SMatthias Ringwald                 } else {
2751c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2752e53be891SMatthias Ringwald                 }
2753687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2754e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2755e53be891SMatthias Ringwald                 break;
2756e53be891SMatthias Ringwald             }
2757c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2758e53be891SMatthias Ringwald                 uint8_t buffer[17];
2759e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2760e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27619d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27624ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
276340c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
276442134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
276545a61d50SMatthias Ringwald                         // responder
2766c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
276745a61d50SMatthias Ringwald                     } else {
276845a61d50SMatthias Ringwald                         // initiator
2769c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
277045a61d50SMatthias Ringwald                     }
277145a61d50SMatthias Ringwald                 } else {
277240c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
277342134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2774e53be891SMatthias Ringwald                         // responder
277547fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
277640c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2777901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27782886623dSMatthias Ringwald                         } else {
277940c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27802886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2781446a8c36SMatthias Ringwald                         }
2782e53be891SMatthias Ringwald                     } else {
2783136d331aSMatthias Ringwald                         // initiator
2784c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2785e53be891SMatthias Ringwald                     }
278645a61d50SMatthias Ringwald                 }
2787687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2788e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2789e53be891SMatthias Ringwald                 break;
2790e53be891SMatthias Ringwald             }
2791c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2792e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2793e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2794e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2795dc300847SMatthias Ringwald 
279642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2797c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2798e53be891SMatthias Ringwald                 } else {
2799c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2800e53be891SMatthias Ringwald                 }
2801e083ca23SMatthias Ringwald 
2802687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2803e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2804e53be891SMatthias Ringwald                 break;
2805e53be891SMatthias Ringwald             }
2806e53be891SMatthias Ringwald 
2807e53be891SMatthias Ringwald #endif
280842134bc6SMatthias Ringwald 
280942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2810dd12a62bSMatthias Ringwald 
281187014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
281287014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
281387014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2814687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2815c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
281687014f74SMatthias Ringwald 				break;
281787014f74SMatthias Ringwald 			}
281887014f74SMatthias Ringwald 
281938196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
282038196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
282138196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
282238196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
282338196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
282438196718SMatthias Ringwald 						// start using context by loading security info
282538196718SMatthias Ringwald 						sm_reset_setup();
282638196718SMatthias Ringwald 						sm_load_security_info(connection);
282738196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
282838196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
282938196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
283042646f38SMatthias Ringwald                             sm_reencryption_started(connection);
283138196718SMatthias Ringwald                             sm_trigger_run();
283238196718SMatthias Ringwald 							break;
283338196718SMatthias Ringwald 						}
283438196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
283538196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
283638196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
283738196718SMatthias Ringwald 						return;
283838196718SMatthias Ringwald 					default:
283938196718SMatthias Ringwald 						// just wait until IRK lookup is completed
284038196718SMatthias Ringwald 						break;
284138196718SMatthias Ringwald 				}
284238196718SMatthias Ringwald 				break;
284338196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
284438196718SMatthias Ringwald 
2845b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2846b6afa23eSMatthias Ringwald                 sm_reset_setup();
28479b75de03SMatthias Ringwald 
28489b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28499b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28509b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28519b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28529b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28539b75de03SMatthias Ringwald                         if (have_ltk){
28549b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
285519a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28569b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28579b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28589b75de03SMatthias Ringwald                         }
28599b75de03SMatthias Ringwald                         break;
28609b75de03SMatthias Ringwald                     default:
28619b75de03SMatthias Ringwald                         break;
28629b75de03SMatthias Ringwald                 }
28639b75de03SMatthias Ringwald 
2864b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2865d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
286639543d07SMatthias Ringwald 
2867b6afa23eSMatthias Ringwald 				// recover pairing request
2868b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2869b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2870b6afa23eSMatthias Ringwald 
2871b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2872b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2873b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2874b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2875b6afa23eSMatthias Ringwald                     }
2876b6afa23eSMatthias Ringwald #endif
28779305033eSMatthias Ringwald 				if (err != 0){
2878f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2879b6afa23eSMatthias Ringwald 					sm_trigger_run();
2880b6afa23eSMatthias Ringwald 					break;
2881b6afa23eSMatthias Ringwald 				}
2882b6afa23eSMatthias Ringwald 
2883b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2884b6afa23eSMatthias Ringwald 
2885b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2886b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2887b6afa23eSMatthias 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);
2888b6afa23eSMatthias Ringwald 					break;
2889b6afa23eSMatthias Ringwald 				}
2890b6afa23eSMatthias Ringwald 
2891b6afa23eSMatthias Ringwald 				/* fall through */
2892b6afa23eSMatthias Ringwald 
28933deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28941ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2895f55bd529SMatthias Ringwald 
2896f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28973deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28981ad129beSMatthias Ringwald 
2899f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2900f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2901f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2902f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2903f55bd529SMatthias Ringwald                 }
2904f55bd529SMatthias Ringwald #endif
2905f55bd529SMatthias Ringwald                 // setup in response
2906f55bd529SMatthias 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);
2907f55bd529SMatthias 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);
2908f55bd529SMatthias Ringwald 
2909f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29109a90d41aSMatthias 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));
2911f55bd529SMatthias Ringwald 
291227c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2913c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29140b8af2a5SMatthias Ringwald                 } else {
29150b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
291627c32905SMatthias Ringwald                 }
29170b8af2a5SMatthias Ringwald 
2918687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29193deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2920446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2921c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29223deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2923446a8c36SMatthias Ringwald                 }
29243deb3ec6SMatthias Ringwald                 return;
292542134bc6SMatthias Ringwald #endif
29263deb3ec6SMatthias Ringwald 
29273deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29283deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29293deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29309c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
293142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29323deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29333deb3ec6SMatthias Ringwald                 } else {
29343deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29353deb3ec6SMatthias Ringwald                 }
2936687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29373deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29383deb3ec6SMatthias Ringwald                 break;
29393deb3ec6SMatthias Ringwald             }
29403deb3ec6SMatthias Ringwald 
2941d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29423deb3ec6SMatthias Ringwald                 // already busy?
29433deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2944d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2945d1a1f6a4SMatthias 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);
2946d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2947d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2948f3582630SMatthias 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);
29493deb3ec6SMatthias Ringwald                 break;
29503deb3ec6SMatthias Ringwald 
29513deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29523deb3ec6SMatthias Ringwald                 // already busy?
29533deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29543deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2955d1a1f6a4SMatthias 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);
2956d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2957d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2958f3582630SMatthias 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);
29593deb3ec6SMatthias Ringwald                 break;
2960d1a1f6a4SMatthias Ringwald 
29613deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29623deb3ec6SMatthias Ringwald                 // already busy?
29633deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29643deb3ec6SMatthias Ringwald                 // calculate STK
296542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2966d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29673deb3ec6SMatthias Ringwald                 } else {
2968d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29693deb3ec6SMatthias Ringwald                 }
2970d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2971d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2972f3582630SMatthias 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);
29733deb3ec6SMatthias Ringwald                 break;
2974d1a1f6a4SMatthias Ringwald 
29753deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29763deb3ec6SMatthias Ringwald                 // already busy?
29773deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29783deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29799ad0dd7cSMatthias Ringwald 
29809ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29819ad0dd7cSMatthias Ringwald                 // r' = padding || r
29829ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29839ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29846535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29859ad0dd7cSMatthias Ringwald 
29863deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2987d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2988d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2989f3582630SMatthias 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);
2990d1a1f6a4SMatthias Ringwald                 break;
2991d1a1f6a4SMatthias Ringwald 
29923deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29933deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29943deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29959c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
299642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29973deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29983deb3ec6SMatthias Ringwald                 } else {
29993deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30003deb3ec6SMatthias Ringwald                 }
3001687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30023deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30033deb3ec6SMatthias Ringwald                 return;
30043deb3ec6SMatthias Ringwald             }
300542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30063deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30073deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30089c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30093deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30103deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30113deb3ec6SMatthias Ringwald                 return;
30123deb3ec6SMatthias Ringwald             }
3013d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
30143deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30159c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30165567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30173deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30183deb3ec6SMatthias Ringwald                 return;
30193deb3ec6SMatthias Ringwald             }
3020dd12a62bSMatthias Ringwald 
3021dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30223deb3ec6SMatthias Ringwald                 // already busy?
30233deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30243deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3025c61cfe5aSMatthias Ringwald 
3026dd12a62bSMatthias Ringwald 				sm_reset_setup();
3027dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3028dd12a62bSMatthias Ringwald 
302942646f38SMatthias Ringwald 				sm_reencryption_started(connection);
303042646f38SMatthias Ringwald 
3031c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3032c61cfe5aSMatthias Ringwald                 // r' = padding || r
3033c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3034c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30356535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3036c61cfe5aSMatthias Ringwald 
30373deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3038d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3039d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3040f3582630SMatthias 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);
30413deb3ec6SMatthias Ringwald                 return;
304242134bc6SMatthias Ringwald #endif
304342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
304442134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
304542134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
304642134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
304742134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
304842134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
304942134bc6SMatthias Ringwald                 return;
305042134bc6SMatthias Ringwald             }
305142134bc6SMatthias Ringwald #endif
30523deb3ec6SMatthias Ringwald 
30533deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3054403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3055403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30563deb3ec6SMatthias Ringwald                     return;
30573deb3ec6SMatthias Ringwald                 }
30583deb3ec6SMatthias Ringwald 
30593deb3ec6SMatthias Ringwald                 // keys are sent
306042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30613deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
306261d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30633deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3064f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3065f5020412SMatthias Ringwald                         // start CTKD right away
3066f5020412SMatthias Ringwald                         continue;
30673deb3ec6SMatthias Ringwald                     } else {
30683deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30693deb3ec6SMatthias Ringwald                     }
30703deb3ec6SMatthias Ringwald                 } else {
30711dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30723deb3ec6SMatthias Ringwald                 }
30733deb3ec6SMatthias Ringwald                 break;
30743deb3ec6SMatthias Ringwald 
3075c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3076c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3077c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3078c18be159SMatthias Ringwald                 sm_reset_setup();
3079c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3080c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3081c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3082c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3083c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3084c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3085c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3086c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3087c18be159SMatthias Ringwald 
3088c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3089c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3090c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3091c18be159SMatthias Ringwald                 // Plus signing key if supported
3092c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3093c18be159SMatthias Ringwald #endif
3094c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3095c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3096c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3097c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3098c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3099c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3100c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3101c18be159SMatthias Ringwald 
3102c18be159SMatthias Ringwald                 // set state and send pairing response
3103c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3104c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3105c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3106c18be159SMatthias Ringwald                 break;
3107c18be159SMatthias Ringwald 
3108c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3109c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3110c18be159SMatthias Ringwald                 sm_reset_setup();
3111c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3112c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3113c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3114c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3115c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3116c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3117c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3118c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3119c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3120c18be159SMatthias Ringwald 
3121c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3122c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3123c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3124c18be159SMatthias Ringwald                 // Plus signing key if supported
3125c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3126c18be159SMatthias Ringwald #endif
3127c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3128c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3129c18be159SMatthias Ringwald 
3130c18be159SMatthias 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:
3131c18be159SMatthias Ringwald                 // - the IO Capability field,
3132c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3133c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3134c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3135c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3136c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3137c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3138c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3139c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3140c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3141c18be159SMatthias Ringwald 
3142c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3143c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3144c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3145c18be159SMatthias Ringwald 
3146c18be159SMatthias Ringwald                 // set state and send pairing response
3147c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3148c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3149c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3150c18be159SMatthias Ringwald                 break;
3151c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3152c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3153c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3154c18be159SMatthias Ringwald                     return;
3155c18be159SMatthias Ringwald                 }
3156c18be159SMatthias Ringwald                 // keys are sent
3157c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3158c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
315961d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3160c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3161c18be159SMatthias Ringwald                         break;
3162c18be159SMatthias Ringwald                     }
3163c18be159SMatthias Ringwald                 }
3164c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3165c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3166c18be159SMatthias Ringwald                 continue;
3167c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3168c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3169c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3170c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3171c18be159SMatthias Ringwald                 break;
3172c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3173c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3174c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3175c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3176c18be159SMatthias Ringwald                 break;
3177c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3178c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3179c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3180c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3181c18be159SMatthias Ringwald                 break;
3182c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3183c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3184c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3185c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3186c18be159SMatthias Ringwald                 break;
3187c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3188c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3189c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3190c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3191c18be159SMatthias Ringwald                 break;
3192c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3193c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3194c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3195c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3196c18be159SMatthias Ringwald                 break;
3197c18be159SMatthias Ringwald #endif
3198c18be159SMatthias Ringwald 
31993deb3ec6SMatthias Ringwald             default:
32003deb3ec6SMatthias Ringwald                 break;
32013deb3ec6SMatthias Ringwald         }
32023deb3ec6SMatthias Ringwald 
32033deb3ec6SMatthias Ringwald         // check again if active connection was released
32047149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32053deb3ec6SMatthias Ringwald     }
32063deb3ec6SMatthias Ringwald }
32073deb3ec6SMatthias Ringwald 
3208d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3209d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3210f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
321104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
321204678764SMatthias Ringwald 
3213f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3214f3582630SMatthias Ringwald     if (connection == NULL) return;
3215f3582630SMatthias Ringwald 
3216d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
321704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3218f3582630SMatthias 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);
3219d1a1f6a4SMatthias Ringwald }
32203deb3ec6SMatthias Ringwald 
3221d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3222f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322404678764SMatthias Ringwald 
3225f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3226f3582630SMatthias Ringwald     if (connection == NULL) return;
3227f3582630SMatthias Ringwald 
32288314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32293deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
323070b44dd4SMatthias Ringwald     sm_trigger_run();
3231d1a1f6a4SMatthias Ringwald }
3232d1a1f6a4SMatthias Ringwald 
3233d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3234d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3235f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323704678764SMatthias Ringwald 
3238f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3239f3582630SMatthias Ringwald     if (connection == NULL) return;
3240f3582630SMatthias Ringwald 
3241d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
324204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3243f3582630SMatthias 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);
3244d1a1f6a4SMatthias Ringwald }
3245d1a1f6a4SMatthias Ringwald 
3246d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3247f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324904678764SMatthias Ringwald 
3250f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3251f3582630SMatthias Ringwald     if (connection == NULL) return;
3252f3582630SMatthias Ringwald 
3253d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3254d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3255f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
325670b44dd4SMatthias Ringwald         sm_trigger_run();
32573deb3ec6SMatthias Ringwald         return;
32583deb3ec6SMatthias Ringwald     }
325942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32603deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
326170b44dd4SMatthias Ringwald         sm_trigger_run();
32623deb3ec6SMatthias Ringwald     } else {
3263d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3264d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3265f3582630SMatthias 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);
32663deb3ec6SMatthias Ringwald     }
32673deb3ec6SMatthias Ringwald }
3268d1a1f6a4SMatthias Ringwald 
3269d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
327004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3271f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327204678764SMatthias Ringwald 
3273f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3274f3582630SMatthias Ringwald     if (connection == NULL) return;
3275f3582630SMatthias Ringwald 
32763deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32778314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
327842134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32793deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
32803deb3ec6SMatthias Ringwald     } else {
32813deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
32823deb3ec6SMatthias Ringwald     }
328370b44dd4SMatthias Ringwald     sm_trigger_run();
3284d1a1f6a4SMatthias Ringwald }
3285d1a1f6a4SMatthias Ringwald 
3286d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3287d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3288f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
328904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329004678764SMatthias Ringwald 
3291f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3292f3582630SMatthias Ringwald     if (connection == NULL) return;
3293f3582630SMatthias Ringwald 
3294d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
32953deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
32963deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
32973deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
32983deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
32993deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33003deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3301d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
330204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3303f3582630SMatthias 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);
33043deb3ec6SMatthias Ringwald }
3305d1a1f6a4SMatthias Ringwald 
33062a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3307d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3308d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
330904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3310f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
331104678764SMatthias Ringwald 
3312f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3313f3582630SMatthias Ringwald     if (connection == NULL) return;
3314f3582630SMatthias Ringwald 
3315d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33163deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33173deb3ec6SMatthias Ringwald 
33183deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33193deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33203deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33213deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33223deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3323d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
332404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3325f3582630SMatthias 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);
33263deb3ec6SMatthias Ringwald }
33272a526f21SMatthias Ringwald #endif
3328d1a1f6a4SMatthias Ringwald 
3329d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3330d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3331f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
333304678764SMatthias Ringwald 
3334f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3335f3582630SMatthias Ringwald     if (connection == NULL) return;
3336f3582630SMatthias Ringwald 
33378314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33383deb3ec6SMatthias Ringwald     // calc CSRK next
3339d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
334004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3341f3582630SMatthias 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);
3342d1a1f6a4SMatthias Ringwald }
3343d1a1f6a4SMatthias Ringwald 
3344d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3345f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
334604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
334704678764SMatthias Ringwald 
3348f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3349f3582630SMatthias Ringwald     if (connection == NULL) return;
3350f3582630SMatthias Ringwald 
3351d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33528314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33533deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33543deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33553deb3ec6SMatthias Ringwald     } else {
33563deb3ec6SMatthias Ringwald         // no keys to send, just continue
335742134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
335861d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3359c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3360c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3361c5a72e35SMatthias Ringwald             } else {
33623deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33633deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3364c5a72e35SMatthias Ringwald             }
33653deb3ec6SMatthias Ringwald         } else {
3366af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33673deb3ec6SMatthias Ringwald         }
33682bacf595SMatthias Ringwald     }
336970b44dd4SMatthias Ringwald     sm_trigger_run();
3370d1a1f6a4SMatthias Ringwald }
3371d1a1f6a4SMatthias Ringwald 
337242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3373d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3374f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
337504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
337604678764SMatthias Ringwald 
3377f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3378f3582630SMatthias Ringwald     if (connection == NULL) return;
3379f3582630SMatthias Ringwald 
33803deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33818314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3382d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
338370b44dd4SMatthias Ringwald     sm_trigger_run();
3384d1a1f6a4SMatthias Ringwald }
3385d1a1f6a4SMatthias Ringwald #endif
3386d1a1f6a4SMatthias Ringwald 
3387d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3388d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3389d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339004678764SMatthias Ringwald 
3391d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3392d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3393d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3394d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3395d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3396a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
339770b44dd4SMatthias Ringwald         sm_trigger_run();
33983deb3ec6SMatthias Ringwald         return;
33993deb3ec6SMatthias Ringwald     }
3400d1a1f6a4SMatthias Ringwald     // no match, try next
3401d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
340270b44dd4SMatthias Ringwald     sm_trigger_run();
34033deb3ec6SMatthias Ringwald }
34043deb3ec6SMatthias Ringwald 
3405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3406d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3407d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
340804678764SMatthias Ringwald 
3409d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3410d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
341170b44dd4SMatthias Ringwald     sm_trigger_run();
34127df18c15SMatthias Ringwald }
3413d1a1f6a4SMatthias Ringwald 
3414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3415d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3416d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341704678764SMatthias Ringwald 
3418d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3419d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
342070b44dd4SMatthias Ringwald     sm_trigger_run();
34217df18c15SMatthias Ringwald }
3422d1a1f6a4SMatthias Ringwald 
3423d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3424d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3425d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342604678764SMatthias Ringwald 
34276535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3428e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3429e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3430e91ddb40SMatthias Ringwald 
343170b44dd4SMatthias Ringwald     sm_trigger_run();
343251fa0b28SMatthias Ringwald }
34337df18c15SMatthias Ringwald 
3434d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3435d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34363deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34373deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34383deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34393deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34403deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34414ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34424ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34433deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34443deb3ec6SMatthias Ringwald             break;
34453deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34463deb3ec6SMatthias Ringwald         default:
34473deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34484ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
3449e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
34503deb3ec6SMatthias Ringwald             break;
34513deb3ec6SMatthias Ringwald     }
345270b44dd4SMatthias Ringwald     sm_trigger_run();
34533deb3ec6SMatthias Ringwald }
34543deb3ec6SMatthias Ringwald 
3455c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34566ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3457f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3458f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3459f3582630SMatthias Ringwald     if (connection == NULL) return;
3460c59d0c92SMatthias Ringwald 
346165a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
346270b44dd4SMatthias Ringwald     sm_trigger_run();
346365a9a04eSMatthias Ringwald }
3464d1a1f6a4SMatthias Ringwald 
34656ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34666ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34676ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34686ca80073SMatthias Ringwald     if (connection == NULL) return;
34696ca80073SMatthias Ringwald 
3470b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
347170b44dd4SMatthias Ringwald     sm_trigger_run();
3472d1a1f6a4SMatthias Ringwald }
3473f1c1783eSMatthias Ringwald #endif
3474f1c1783eSMatthias Ringwald 
3475d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3476f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3477f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3478f3582630SMatthias Ringwald     if (connection == NULL) return;
3479f3582630SMatthias Ringwald 
3480d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
348170b44dd4SMatthias Ringwald     sm_trigger_run();
3482d1a1f6a4SMatthias Ringwald }
3483d1a1f6a4SMatthias Ringwald 
3484d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3485f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3486f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3487f3582630SMatthias Ringwald     if (connection == NULL) return;
3488f3582630SMatthias Ringwald 
3489caf15bf3SMatthias Ringwald     sm_reset_tk();
3490caf15bf3SMatthias Ringwald     uint32_t tk;
34915ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
34923deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3493d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
34943deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
34954ea43905SMatthias Ringwald         if (tk >= 999999u){
34964ea43905SMatthias Ringwald             tk = tk - 999999u;
34973deb3ec6SMatthias Ringwald         }
3498caf15bf3SMatthias Ringwald     } else {
3499caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35004b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3501caf15bf3SMatthias Ringwald     }
3502f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
350342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35043deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35053deb3ec6SMatthias Ringwald     } else {
3506b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3507b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3508b41539d5SMatthias Ringwald         } else {
35093deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35103deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35113deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35123deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3513f3582630SMatthias 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);
35143deb3ec6SMatthias Ringwald             }
35153deb3ec6SMatthias Ringwald         }
3516b41539d5SMatthias Ringwald     }
351770b44dd4SMatthias Ringwald     sm_trigger_run();
35183deb3ec6SMatthias Ringwald }
3519d1a1f6a4SMatthias Ringwald 
3520d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3521f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3522f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3523f3582630SMatthias Ringwald     if (connection == NULL) return;
3524f3582630SMatthias Ringwald 
3525d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3526d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3527d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3528d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
352970b44dd4SMatthias Ringwald     sm_trigger_run();
3530d1a1f6a4SMatthias Ringwald }
3531d1a1f6a4SMatthias Ringwald 
3532d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3533f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3534f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3535f3582630SMatthias Ringwald     if (connection == NULL) return;
3536f3582630SMatthias Ringwald 
3537d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35383deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35394ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35403deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35414ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35428b3ffec5SMatthias 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);
35433deb3ec6SMatthias Ringwald }
3544899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3545899e6e02SMatthias Ringwald     // warn about default ER/IR
35461979f09cSMatthias Ringwald     bool warning = false;
3547899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35481979f09cSMatthias Ringwald         warning = true;
3549899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3550899e6e02SMatthias Ringwald     }
3551899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35521979f09cSMatthias Ringwald         warning = true;
3553899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3554899e6e02SMatthias Ringwald     }
355521045273SMatthias Ringwald     if (warning) {
3556899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3557899e6e02SMatthias Ringwald     }
355821045273SMatthias Ringwald }
3559899e6e02SMatthias Ringwald 
3560899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35611979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35629305033eSMatthias Ringwald     if (arg != NULL){
3563899e6e02SMatthias Ringwald         // key generated, store in tlv
35644ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3565899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3566e0d13a19SMilanka Ringwald         UNUSED(status);
3567899e6e02SMatthias Ringwald     }
3568899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35698d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3570841468bbSMatthias Ringwald 
3571841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3572841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3573841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3574841468bbSMatthias Ringwald     }
3575841468bbSMatthias Ringwald 
357670b44dd4SMatthias Ringwald     sm_trigger_run();
3577899e6e02SMatthias Ringwald }
3578899e6e02SMatthias Ringwald 
3579899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
35801979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35819305033eSMatthias Ringwald     if (arg != 0){
3582899e6e02SMatthias Ringwald         // key generated, store in tlv
35834ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3584899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3585e0d13a19SMilanka Ringwald         UNUSED(status);
3586899e6e02SMatthias Ringwald     }
3587899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3588899e6e02SMatthias Ringwald 
3589899e6e02SMatthias Ringwald     // try load ir
35904ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3591899e6e02SMatthias Ringwald     if (key_size == 16){
3592899e6e02SMatthias Ringwald         // ok, let's continue
3593899e6e02SMatthias Ringwald         log_info("IR from TLV");
3594899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3595899e6e02SMatthias Ringwald     } else {
3596899e6e02SMatthias Ringwald         // invalid, generate new random one
35971979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3598899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3599899e6e02SMatthias Ringwald     }
3600899e6e02SMatthias Ringwald }
36013deb3ec6SMatthias Ringwald 
3602f664b5e8SMatthias 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){
3603f664b5e8SMatthias Ringwald 
3604f664b5e8SMatthias Ringwald     // connection info
3605f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3606f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3607f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3608f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3609f664b5e8SMatthias Ringwald 
3610f664b5e8SMatthias Ringwald     // security properties
3611f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3612f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3613f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3614f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3615f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3616f664b5e8SMatthias Ringwald 
3617f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3618f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3619f664b5e8SMatthias Ringwald 
3620f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3621f664b5e8SMatthias Ringwald }
3622f664b5e8SMatthias Ringwald 
3623d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36243deb3ec6SMatthias Ringwald 
3625cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3626cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36279ec2630cSMatthias Ringwald 
36283deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3629711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3630fbe050beSMatthias Ringwald     uint8_t           status;
3631f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3632f664b5e8SMatthias Ringwald 
36333deb3ec6SMatthias Ringwald     switch (packet_type) {
36343deb3ec6SMatthias Ringwald 
36353deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36360e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36373deb3ec6SMatthias Ringwald 
36383deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
36393deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3640be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
36413deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3642899e6e02SMatthias Ringwald 
3643899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3644899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36459305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
36464ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3647899e6e02SMatthias Ringwald                             if (key_size == 16){
3648899e6e02SMatthias Ringwald                                 // ok, let's continue
3649899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3650899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3651899e6e02SMatthias Ringwald                             } else {
3652899e6e02SMatthias Ringwald                                 // invalid, generate random one
36531979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3654899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3655899e6e02SMatthias Ringwald                             }
3656899e6e02SMatthias Ringwald                         } else {
3657899e6e02SMatthias Ringwald                             sm_validate_er_ir();
36588d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3659841468bbSMatthias Ringwald 
3660841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3661841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3662841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3663841468bbSMatthias Ringwald                             }
3664899e6e02SMatthias Ringwald                         }
36651bf086daSMatthias Ringwald 
36661bf086daSMatthias Ringwald                         // restart random address updates after power cycle
36671bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
36683deb3ec6SMatthias Ringwald 					}
36693deb3ec6SMatthias Ringwald 					break;
3670c18be159SMatthias Ringwald 
36712d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
36722d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
36732d095694SMatthias Ringwald 			        // ignore if connection failed
36742d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
36753deb3ec6SMatthias Ringwald 
36762d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
36772d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
36782d095694SMatthias Ringwald 			        if (!sm_conn) break;
36792d095694SMatthias Ringwald 
36802d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
36812d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
36822d095694SMatthias Ringwald                                        con_handle,
36832d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3684f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
36852d095694SMatthias Ringwald                                        addr);
36862d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
36872d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
36882d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
36892d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3690c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
36912d095694SMatthias Ringwald 			        break;
36922d095694SMatthias Ringwald #endif
3693c18be159SMatthias Ringwald 
3694c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3695c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3696c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3697c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3698c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3699c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3700c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3701c18be159SMatthias Ringwald 			        break;
3702c18be159SMatthias Ringwald #endif
3703c18be159SMatthias Ringwald 
37043deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37053deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37063deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3707f664b5e8SMatthias Ringwald                             // ignore if connection failed
3708f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37093deb3ec6SMatthias Ringwald 
3710711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3711711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37123deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37133deb3ec6SMatthias Ringwald 
3714f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3715f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3716f664b5e8SMatthias Ringwald                                                con_handle,
3717f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3718f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3719f664b5e8SMatthias Ringwald                                                addr);
3720687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3721f664b5e8SMatthias Ringwald 
3722f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3723b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3724b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3725ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3726ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3727f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3728b892db1cSMatthias Ringwald                             }
3729b892db1cSMatthias Ringwald #endif
3730b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3731b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3732ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3733ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37343deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37353deb3ec6SMatthias Ringwald                             }
3736b892db1cSMatthias Ringwald #endif
37373deb3ec6SMatthias Ringwald                             break;
37383deb3ec6SMatthias Ringwald 
37393deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3740711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3741711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37423deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37433deb3ec6SMatthias Ringwald 
37443deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37453deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37463deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37473deb3ec6SMatthias Ringwald                                 break;
37483deb3ec6SMatthias Ringwald                             }
3749c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3750778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3751778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3752e53be891SMatthias Ringwald                                 break;
3753e53be891SMatthias Ringwald                             }
37543deb3ec6SMatthias Ringwald 
37553deb3ec6SMatthias Ringwald                             // store rand and ediv
37569c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3757f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3758549ad5d2SMatthias Ringwald 
3759549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3760549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37614ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37626c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
376306cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3764549ad5d2SMatthias Ringwald                                     break;
3765549ad5d2SMatthias Ringwald                                 }
37666c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37676c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37686c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37696c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37706c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
37716c39055aSMatthias Ringwald                                         break;
37726c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
37736c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
37746c39055aSMatthias Ringwald                                         break;
37756c39055aSMatthias Ringwald                                     default:
37766c39055aSMatthias Ringwald                                         // wait for irk look doen
37776c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
37786c39055aSMatthias Ringwald                                         break;
37796c39055aSMatthias Ringwald                                 }
37806c39055aSMatthias Ringwald                                 break;
37816c39055aSMatthias Ringwald                             }
3782549ad5d2SMatthias Ringwald 
3783549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
378406cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3785549ad5d2SMatthias Ringwald #else
3786549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3787549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3788549ad5d2SMatthias Ringwald #endif
37893deb3ec6SMatthias Ringwald                             break;
3790804d3e67SMatthias Ringwald 
37913deb3ec6SMatthias Ringwald                         default:
37923deb3ec6SMatthias Ringwald                             break;
37933deb3ec6SMatthias Ringwald                     }
37943deb3ec6SMatthias Ringwald                     break;
37953deb3ec6SMatthias Ringwald 
37963deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
37973b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3798711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37993deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38003deb3ec6SMatthias Ringwald 
38013b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38023deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38033deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38043deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
380503a9359aSMatthias Ringwald 
3806fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3807fbe050beSMatthias Ringwald 
38085567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
380903a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3810fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3811fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38128d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38138d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38148d4eef95SMatthias Ringwald                                 } else {
381503a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38168d4eef95SMatthias Ringwald                                 }
3817fbe050beSMatthias Ringwald                             } else {
3818e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3819cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38203b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3821cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38223b7fd749SMatthias Ringwald                             }
3823fbe050beSMatthias Ringwald 
3824fbe050beSMatthias Ringwald                             // emit re-encryption complete
382573102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3826fbe050beSMatthias Ringwald 
3827c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3828c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3829c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38300ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
383103a9359aSMatthias Ringwald                             }
383203a9359aSMatthias Ringwald 
38333deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38343deb3ec6SMatthias Ringwald                             break;
3835fbe050beSMatthias Ringwald 
38363deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3837fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3838dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
383942134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38403deb3ec6SMatthias Ringwald                                 // slave
3841bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3842bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3843bbf8db22SMatthias Ringwald                                 } else {
3844f3582630SMatthias 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);
3845bbf8db22SMatthias Ringwald                                 }
38463deb3ec6SMatthias Ringwald                             } else {
38473deb3ec6SMatthias Ringwald                                 // master
384861d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38493deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38503deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3851f3582630SMatthias 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);
38523deb3ec6SMatthias Ringwald                                 } else {
38533deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38543deb3ec6SMatthias Ringwald                                 }
38553deb3ec6SMatthias Ringwald                             }
38563deb3ec6SMatthias Ringwald                             break;
3857c18be159SMatthias Ringwald 
3858c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3859c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3860c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3861c18be159SMatthias Ringwald                             // prepare for pairing request
3862c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3863c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3864c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3865c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3866c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3867c18be159SMatthias Ringwald                             }
3868c18be159SMatthias Ringwald                             break;
3869c18be159SMatthias Ringwald #endif
38703deb3ec6SMatthias Ringwald                         default:
38713deb3ec6SMatthias Ringwald                             break;
38723deb3ec6SMatthias Ringwald                     }
38733deb3ec6SMatthias Ringwald                     break;
38743deb3ec6SMatthias Ringwald 
38753deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3876711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3877711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38783deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38793deb3ec6SMatthias Ringwald 
38803deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
38813deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
38823deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
38833deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
38845567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
38855567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
38865567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38875567aa60SMatthias Ringwald                             } else {
38883deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38895567aa60SMatthias Ringwald                             }
38903deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38913deb3ec6SMatthias Ringwald                             break;
38923deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
389342134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38943deb3ec6SMatthias Ringwald                                 // slave
3895f3582630SMatthias 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);
38963deb3ec6SMatthias Ringwald                             } else {
38973deb3ec6SMatthias Ringwald                                 // master
38983deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38993deb3ec6SMatthias Ringwald                             }
39003deb3ec6SMatthias Ringwald                             break;
39013deb3ec6SMatthias Ringwald                         default:
39023deb3ec6SMatthias Ringwald                             break;
39033deb3ec6SMatthias Ringwald                     }
39043deb3ec6SMatthias Ringwald                     break;
39053deb3ec6SMatthias Ringwald 
39063deb3ec6SMatthias Ringwald 
39073deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3908711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3909711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3910711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39113deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39123deb3ec6SMatthias Ringwald 
391303f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39147f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39157f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39167f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39177f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39187f3f442dSMatthias Ringwald                             break;
39197f3f442dSMatthias Ringwald                         default:
392068a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39210ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39227f3f442dSMatthias Ringwald                             break;
392303f736b1SMatthias Ringwald                     }
3924accbde80SMatthias Ringwald 
39253deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39263deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39273deb3ec6SMatthias Ringwald                     break;
39283deb3ec6SMatthias Ringwald 
39293deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
393033373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
39319091c5f5SMatthias Ringwald                         // set local addr for le device db
393233373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39330c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
393433373e40SMatthias Ringwald                     }
393565b44ffdSMatthias Ringwald                     break;
393665b44ffdSMatthias Ringwald                 default:
393765b44ffdSMatthias Ringwald                     break;
39383deb3ec6SMatthias Ringwald 			}
393965b44ffdSMatthias Ringwald             break;
394065b44ffdSMatthias Ringwald         default:
394165b44ffdSMatthias Ringwald             break;
39423deb3ec6SMatthias Ringwald 	}
39433deb3ec6SMatthias Ringwald 
39443deb3ec6SMatthias Ringwald     sm_run();
39453deb3ec6SMatthias Ringwald }
39463deb3ec6SMatthias Ringwald 
39473deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39483deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39493deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39503deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39513deb3ec6SMatthias Ringwald }
39523deb3ec6SMatthias Ringwald 
3953945888f5SMatthias Ringwald 
395431c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3955945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3956945888f5SMatthias Ringwald     switch (method){
3957945888f5SMatthias Ringwald         case JUST_WORKS:
395847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3959945888f5SMatthias Ringwald             return 1;
3960945888f5SMatthias Ringwald         default:
3961945888f5SMatthias Ringwald             return 0;
3962945888f5SMatthias Ringwald     }
3963945888f5SMatthias Ringwald }
396407036a04SMatthias Ringwald // responder
3965945888f5SMatthias Ringwald 
3966688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3967688a08f9SMatthias Ringwald     switch (method){
3968688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3969688a08f9SMatthias Ringwald             return 1;
3970688a08f9SMatthias Ringwald         default:
3971688a08f9SMatthias Ringwald             return 0;
3972688a08f9SMatthias Ringwald     }
3973688a08f9SMatthias Ringwald }
397440c5d850SMatthias Ringwald 
397540c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
397640c5d850SMatthias Ringwald     switch (method){
397740c5d850SMatthias Ringwald         case PK_RESP_INPUT:
397840c5d850SMatthias Ringwald         case PK_INIT_INPUT:
397947fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
398040c5d850SMatthias Ringwald             return 1;
398140c5d850SMatthias Ringwald         default:
398240c5d850SMatthias Ringwald             return 0;
398340c5d850SMatthias Ringwald     }
398440c5d850SMatthias Ringwald }
398540c5d850SMatthias Ringwald 
398631c09488SMatthias Ringwald #endif
3987688a08f9SMatthias Ringwald 
39883deb3ec6SMatthias Ringwald /**
39893deb3ec6SMatthias Ringwald  * @return ok
39903deb3ec6SMatthias Ringwald  */
39913deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
39923deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
39933deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
39943deb3ec6SMatthias Ringwald         case JUST_WORKS:
39954ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
39963deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
39973deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
399847fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
39994ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
40003deb3ec6SMatthias Ringwald         case OOB:
40014ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
400247fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40034ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40043deb3ec6SMatthias Ringwald         default:
40053deb3ec6SMatthias Ringwald             return 0;
40063deb3ec6SMatthias Ringwald     }
40073deb3ec6SMatthias Ringwald }
40083deb3ec6SMatthias Ringwald 
40098334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40108334d3d8SMatthias Ringwald 
40114c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40124c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40134c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40144c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40154c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40164c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40174c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40184c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40194c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40207a2e6387SMatthias Ringwald             11, // 0x07 master identification
40214c1d1092SMatthias Ringwald             17, // 0x08 identification information
40224c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40234c1d1092SMatthias Ringwald             17, // 0x0a signing information
40244c1d1092SMatthias Ringwald             2,  // 0x0b security request
40254c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40264c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40274c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
40284c1d1092SMatthias Ringwald     };
40293deb3ec6SMatthias Ringwald 
4030c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4031b170b20fSMatthias Ringwald         sm_run();
4032b170b20fSMatthias Ringwald     }
4033b170b20fSMatthias Ringwald 
40343deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
40354ea43905SMatthias Ringwald     if (size == 0u) return;
40364c1d1092SMatthias Ringwald 
40374c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
40384c1d1092SMatthias Ringwald 
40394c1d1092SMatthias Ringwald     // validate pdu size
40404c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
40417a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
40423deb3ec6SMatthias Ringwald 
4043711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
40443deb3ec6SMatthias Ringwald     if (!sm_conn) return;
40453deb3ec6SMatthias Ringwald 
40464c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
404768a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
40480ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4049accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
40503deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
40513deb3ec6SMatthias Ringwald         return;
40523deb3ec6SMatthias Ringwald     }
40533deb3ec6SMatthias Ringwald 
40544c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
40553deb3ec6SMatthias Ringwald 
40563deb3ec6SMatthias Ringwald     int err;
405742134bc6SMatthias Ringwald     UNUSED(err);
40583deb3ec6SMatthias Ringwald 
40594c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
40603d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
40613d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
40623d7fe1e9SMatthias Ringwald         buffer[1] = 3;
40633d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
40643d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
40653d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
40663d7fe1e9SMatthias Ringwald         return;
40673d7fe1e9SMatthias Ringwald     }
40683d7fe1e9SMatthias Ringwald 
4069a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
4070212d735eSMatthias Ringwald     int have_ltk;
4071212d735eSMatthias Ringwald     uint8_t ltk[16];
4072a6ca6916SDavid Lechner #endif
4073212d735eSMatthias Ringwald 
40743deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
40753deb3ec6SMatthias Ringwald 
4076c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
40773deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
40783deb3ec6SMatthias Ringwald             return;
40793deb3ec6SMatthias Ringwald 
408042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
408142134bc6SMatthias Ringwald 
40823deb3ec6SMatthias Ringwald         // Initiator
40833deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
40844c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
40853deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40863deb3ec6SMatthias Ringwald                 break;
40873deb3ec6SMatthias Ringwald             }
408834c39fbdSMatthias Ringwald 
40892c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
40902c041b42SMatthias Ringwald             if (sm_sc_only_mode){
40912c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
40922c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
4093f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
40942c041b42SMatthias Ringwald                     break;
40952c041b42SMatthias Ringwald                 }
40962c041b42SMatthias Ringwald             }
40972c041b42SMatthias Ringwald #endif
40982c041b42SMatthias Ringwald 
409934c39fbdSMatthias Ringwald             // IRK complete?
410034c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
410134c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
4102dc8ca372SMatthias Ringwald                     // start pairing
41033deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
41043deb3ec6SMatthias Ringwald                     break;
4105e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4106e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4107e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
41088549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
41098549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
41108549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
41115567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4112e061bbd4SMatthias Ringwald                     } else {
4113dc8ca372SMatthias Ringwald                         // start pairing
4114e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4115e061bbd4SMatthias Ringwald                     }
4116e061bbd4SMatthias Ringwald                     break;
411734c39fbdSMatthias Ringwald                 default:
41183deb3ec6SMatthias Ringwald                     // otherwise, store security request
41193deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
41203deb3ec6SMatthias Ringwald                     break;
4121dc8ca372SMatthias Ringwald             }
4122dc8ca372SMatthias Ringwald             break;
41233deb3ec6SMatthias Ringwald 
41243deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4125aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4126aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4127aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4128aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4129aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4130aacfafc3SMatthias Ringwald                 break;
4131aacfafc3SMatthias Ringwald             }
4132aacfafc3SMatthias Ringwald 
4133aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41344c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41353deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41363deb3ec6SMatthias Ringwald                 break;
41373deb3ec6SMatthias Ringwald             }
41380af429c6SMatthias Ringwald 
41393deb3ec6SMatthias Ringwald             // store pairing request
41406535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41416535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41423deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41430af429c6SMatthias Ringwald 
41440af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41450af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41460af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41470af429c6SMatthias Ringwald                 err = test_pairing_failure;
41480af429c6SMatthias Ringwald             }
41490af429c6SMatthias Ringwald #endif
41500af429c6SMatthias Ringwald 
41519305033eSMatthias Ringwald             if (err != 0){
4152f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41533deb3ec6SMatthias Ringwald                 break;
41543deb3ec6SMatthias Ringwald             }
4155b41539d5SMatthias Ringwald 
4156b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4157b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4158f3582630SMatthias 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);
4159b41539d5SMatthias Ringwald                 break;
4160b41539d5SMatthias Ringwald             }
4161b41539d5SMatthias Ringwald 
4162136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4163136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41648cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41658cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4166136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4167136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4168136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4169c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4170136d331aSMatthias Ringwald                     }
41718cba5ca3SMatthias Ringwald                 } else {
4172c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
41738cba5ca3SMatthias Ringwald                 }
4174136d331aSMatthias Ringwald                 break;
4175136d331aSMatthias Ringwald             }
4176136d331aSMatthias Ringwald #endif
41773deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
41783deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
41793deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
41803deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4181f3582630SMatthias 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);
41823deb3ec6SMatthias Ringwald             }
41833deb3ec6SMatthias Ringwald             break;
41843deb3ec6SMatthias Ringwald 
41853deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
41864c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
41873deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41883deb3ec6SMatthias Ringwald                 break;
41893deb3ec6SMatthias Ringwald             }
41903deb3ec6SMatthias Ringwald 
41913deb3ec6SMatthias Ringwald             // store s_confirm
41929c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4193192365feSMatthias Ringwald 
4194aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4195aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4196aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4197aa9b34e5SMatthias Ringwald                 break;
4198aa9b34e5SMatthias Ringwald             }
4199aa9b34e5SMatthias Ringwald 
4200192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4201192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4202192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4203192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4204192365feSMatthias Ringwald             }
4205192365feSMatthias Ringwald #endif
42063deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42073deb3ec6SMatthias Ringwald             break;
42083deb3ec6SMatthias Ringwald 
42093deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42104c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42113deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42123deb3ec6SMatthias Ringwald                 break;;
42133deb3ec6SMatthias Ringwald             }
42143deb3ec6SMatthias Ringwald 
42153deb3ec6SMatthias Ringwald             // received random value
42169c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42173deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42183deb3ec6SMatthias Ringwald             break;
421942134bc6SMatthias Ringwald #endif
42203deb3ec6SMatthias Ringwald 
422142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42223deb3ec6SMatthias Ringwald         // Responder
42233deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42243deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42253deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42264c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42273deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42283deb3ec6SMatthias Ringwald                 break;;
42293deb3ec6SMatthias Ringwald             }
42303deb3ec6SMatthias Ringwald 
42313deb3ec6SMatthias Ringwald             // store pairing request
4232212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4233212d735eSMatthias Ringwald 
4234212d735eSMatthias Ringwald             // check if IRK completed
4235212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4236212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4237212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42383deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42393deb3ec6SMatthias Ringwald                     break;
4240212d735eSMatthias Ringwald                 default:
4241212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4242212d735eSMatthias Ringwald                     break;
4243212d735eSMatthias Ringwald             }
4244212d735eSMatthias Ringwald             break;
424542134bc6SMatthias Ringwald #endif
42463deb3ec6SMatthias Ringwald 
424727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4248c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42494c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
425027c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
425127c32905SMatthias Ringwald                 break;
425227c32905SMatthias Ringwald             }
4253bccf5e67SMatthias Ringwald 
4254e53be891SMatthias Ringwald             // store public key for DH Key calculation
4255fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4256fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4257bccf5e67SMatthias Ringwald 
425802658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
425902658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
426002658749SMatthias Ringwald                 log_info("Remote PK matches ours");
426102658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
426202658749SMatthias Ringwald                 break;
426302658749SMatthias Ringwald             }
426402658749SMatthias Ringwald 
4265d1a1f6a4SMatthias Ringwald             // validate public key
4266d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
42679305033eSMatthias Ringwald             if (err != 0){
426802658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4269349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4270bccf5e67SMatthias Ringwald                 break;
4271bccf5e67SMatthias Ringwald             }
4272891bb64aSMatthias Ringwald 
4273d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4274f3582630SMatthias 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);
42753cf37b8cSMatthias Ringwald 
427665a9a04eSMatthias Ringwald 
427765a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
427842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4279136d331aSMatthias Ringwald                 // responder
4280c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4281136d331aSMatthias Ringwald             } else {
4282136d331aSMatthias Ringwald                 // initiator
4283a1e31e9cSMatthias Ringwald                 // stk generation method
4284a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4285a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4286a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
428747fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4288c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4289a1e31e9cSMatthias Ringwald                         break;
4290a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
429107036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
429207036a04SMatthias Ringwald                         break;
429307036a04SMatthias Ringwald                     case PK_INIT_INPUT:
429447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
429507036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
429607036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
429707036a04SMatthias Ringwald                             break;
429807036a04SMatthias Ringwald                         }
4299b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4300a1e31e9cSMatthias Ringwald                         break;
4301a1e31e9cSMatthias Ringwald                     case OOB:
4302d1a1f6a4SMatthias Ringwald                         // generate Nx
43034acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43046ca80073SMatthias 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);
4305a1e31e9cSMatthias Ringwald                         break;
43067bbeb3adSMilanka Ringwald                     default:
43077bbeb3adSMilanka Ringwald                         btstack_assert(false);
43087bbeb3adSMilanka Ringwald                         break;
4309a1e31e9cSMatthias Ringwald                 }
4310136d331aSMatthias Ringwald             }
431127c32905SMatthias Ringwald             break;
4312e53be891SMatthias Ringwald 
4313c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43144c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
431545a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
431645a61d50SMatthias Ringwald                 break;
431745a61d50SMatthias Ringwald             }
431845a61d50SMatthias Ringwald             // received confirm value
431945a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
432045a61d50SMatthias Ringwald 
4321192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4322192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4323192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4324192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4325192365feSMatthias Ringwald             }
4326192365feSMatthias Ringwald #endif
432742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
432845a61d50SMatthias Ringwald                 // responder
432907036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
433007036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
433107036a04SMatthias Ringwald                         // still waiting for passkey
433207036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
433307036a04SMatthias Ringwald                         break;
433407036a04SMatthias Ringwald                     }
433507036a04SMatthias Ringwald                 }
4336b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
433745a61d50SMatthias Ringwald             } else {
433845a61d50SMatthias Ringwald                 // initiator
4339945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43406ca80073SMatthias 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);
4341f1c1783eSMatthias Ringwald                 } else {
4342c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
434345a61d50SMatthias Ringwald                 }
4344f1c1783eSMatthias Ringwald             }
434545a61d50SMatthias Ringwald             break;
434645a61d50SMatthias Ringwald 
4347c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43484c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4349e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4350136d331aSMatthias Ringwald                 break;
4351e53be891SMatthias Ringwald             }
4352e53be891SMatthias Ringwald 
4353e53be891SMatthias Ringwald             // received random value
4354e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4355e53be891SMatthias Ringwald 
43565a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4357ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4358d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4359d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4360d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
436165a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4362d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4363688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4364ae451ec5SMatthias Ringwald                  break;
43655a293e6eSMatthias Ringwald             }
43666f52a196SMatthias Ringwald 
43674acf7b7bSMatthias Ringwald             // OOB
43684acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
43694acf7b7bSMatthias Ringwald 
43704acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
43714acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
43724acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43734ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
43744acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
43754acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
43764acf7b7bSMatthias Ringwald                     } else {
43776535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
43784acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
43794acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
43804acf7b7bSMatthias Ringwald                     }
43814acf7b7bSMatthias Ringwald                 }  else {
43824ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
43834acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
43844acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
43854acf7b7bSMatthias Ringwald                     } else {
43866535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
43874acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
43884acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
43894acf7b7bSMatthias Ringwald                     }
43904acf7b7bSMatthias Ringwald                 }
43914acf7b7bSMatthias Ringwald 
4392a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
43934acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4394a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4395a680ba6bSMatthias Ringwald                      break;
4396a680ba6bSMatthias Ringwald                 }
43974acf7b7bSMatthias Ringwald             }
4398a680ba6bSMatthias Ringwald 
4399a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4400688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4401e53be891SMatthias Ringwald             break;
4402e53be891SMatthias Ringwald 
4403901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4404901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44053cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4406901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4407901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4408901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4409901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4410901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4411901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4412901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4413c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4414901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4415d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44164c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4417e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4418e53be891SMatthias Ringwald                 break;
4419e53be891SMatthias Ringwald             }
4420e53be891SMatthias Ringwald             // store DHKey Check
4421901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4422e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4423446a8c36SMatthias Ringwald 
4424901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4425901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4426019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4427bd57ffebSMatthias Ringwald             }
4428bd57ffebSMatthias Ringwald             break;
442927c32905SMatthias Ringwald #endif
443027c32905SMatthias Ringwald 
443142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44323deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44334c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44343deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
443527c32905SMatthias Ringwald                 break;
44363deb3ec6SMatthias Ringwald             }
44373deb3ec6SMatthias Ringwald 
44383deb3ec6SMatthias Ringwald             // received confirm value
44399c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44403deb3ec6SMatthias Ringwald 
4441192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4442192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4443192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4444192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4445192365feSMatthias Ringwald             }
4446192365feSMatthias Ringwald #endif
44473deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44483deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44495611a760SMatthias 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);
44503deb3ec6SMatthias Ringwald             }
44513deb3ec6SMatthias Ringwald 
44523deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44533deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4454f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44553deb3ec6SMatthias Ringwald                 break;
44563deb3ec6SMatthias Ringwald             }
44573deb3ec6SMatthias Ringwald 
44583deb3ec6SMatthias Ringwald             // wait for user action?
44593deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44603deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44613deb3ec6SMatthias Ringwald                 break;
44623deb3ec6SMatthias Ringwald             }
44633deb3ec6SMatthias Ringwald 
44643deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4465f3582630SMatthias 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);
44663deb3ec6SMatthias Ringwald             break;
44673deb3ec6SMatthias Ringwald 
44683deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
44694c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
44703deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
44713deb3ec6SMatthias Ringwald                 break;;
44723deb3ec6SMatthias Ringwald             }
44733deb3ec6SMatthias Ringwald 
44743deb3ec6SMatthias Ringwald             // received random value
44759c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
44763deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
44773deb3ec6SMatthias Ringwald             break;
447842134bc6SMatthias Ringwald #endif
44793deb3ec6SMatthias Ringwald 
44803deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
44814c1d1092SMatthias Ringwald             switch(sm_pdu_code){
44823deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
44833deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
44849c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
44853deb3ec6SMatthias Ringwald                     break;
44863deb3ec6SMatthias Ringwald 
44873deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
44883deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4489f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
44909c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
44913deb3ec6SMatthias Ringwald                     break;
44923deb3ec6SMatthias Ringwald 
44933deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
44943deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
44959c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
44963deb3ec6SMatthias Ringwald                     break;
44973deb3ec6SMatthias Ringwald 
44983deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
44993deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
45003deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4501724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
45023deb3ec6SMatthias Ringwald                     break;
45033deb3ec6SMatthias Ringwald 
45043deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45053deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45069c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45073deb3ec6SMatthias Ringwald                     break;
45083deb3ec6SMatthias Ringwald                 default:
45093deb3ec6SMatthias Ringwald                     // Unexpected PDU
45103deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45113deb3ec6SMatthias Ringwald                     break;
45123deb3ec6SMatthias Ringwald             }
45133deb3ec6SMatthias Ringwald             // done with key distribution?
451461d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45153deb3ec6SMatthias Ringwald 
45163deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45173deb3ec6SMatthias Ringwald 
451842134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45196f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45203deb3ec6SMatthias Ringwald                 } else {
4521625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4522625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4523bbf8db22SMatthias Ringwald                     } else {
4524f3582630SMatthias 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);
4525625f00b2SMatthias Ringwald                     }
45263deb3ec6SMatthias Ringwald                 }
45273deb3ec6SMatthias Ringwald             }
45283deb3ec6SMatthias Ringwald             break;
4529c18be159SMatthias Ringwald 
4530c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4531c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4532c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4533c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4534c18be159SMatthias Ringwald                 break;
4535c18be159SMatthias Ringwald             }
4536c18be159SMatthias Ringwald             // store pairing response
4537c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4538c18be159SMatthias Ringwald 
4539c18be159SMatthias Ringwald             // validate encryption key size
4540c18be159SMatthias 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));
4541c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4542c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4543c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4544c18be159SMatthias Ringwald             }
4545c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4546c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4547c18be159SMatthias Ringwald                 break;
4548c18be159SMatthias Ringwald             }
4549c18be159SMatthias Ringwald 
4550c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4551c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4552c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4553c18be159SMatthias Ringwald 
4554c18be159SMatthias Ringwald             // skip receive if there are none
455561d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4556c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4557c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4558c18be159SMatthias Ringwald             } else {
4559c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4560c18be159SMatthias Ringwald             }
4561c18be159SMatthias Ringwald             break;
4562c18be159SMatthias Ringwald 
4563c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4564c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4565c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4566c18be159SMatthias Ringwald                 break;
4567c18be159SMatthias Ringwald             }
4568c18be159SMatthias Ringwald             // store pairing request
4569c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4570c18be159SMatthias Ringwald             // validate encryption key size
4571c18be159SMatthias 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));
4572c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4573c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4574c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4575c18be159SMatthias Ringwald             }
4576c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4577c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4578c18be159SMatthias Ringwald                 break;
4579c18be159SMatthias Ringwald             }
4580c18be159SMatthias Ringwald             // trigger response
4581c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4582c18be159SMatthias Ringwald             break;
4583c18be159SMatthias Ringwald 
4584c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4585c18be159SMatthias Ringwald             switch(sm_pdu_code){
4586c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4587c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4588c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4589c18be159SMatthias Ringwald                     break;
4590c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4591c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4592c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4593c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4594c18be159SMatthias Ringwald                     break;
4595c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4596c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4597c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4598c18be159SMatthias Ringwald                     break;
4599c18be159SMatthias Ringwald                 default:
4600c18be159SMatthias Ringwald                     // Unexpected PDU
4601c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4602c18be159SMatthias Ringwald                     break;
4603c18be159SMatthias Ringwald             }
4604c18be159SMatthias Ringwald 
4605c18be159SMatthias Ringwald             // all keys received
460661d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4607c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4608c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4609c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4610c18be159SMatthias Ringwald                 } else {
4611c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4612c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4613c18be159SMatthias Ringwald                 }
4614c18be159SMatthias Ringwald             }
4615c18be159SMatthias Ringwald             break;
4616c18be159SMatthias Ringwald #endif
4617c18be159SMatthias Ringwald 
46183deb3ec6SMatthias Ringwald         default:
46193deb3ec6SMatthias Ringwald             // Unexpected PDU
46203deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46212d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46223deb3ec6SMatthias Ringwald             break;
46233deb3ec6SMatthias Ringwald     }
46243deb3ec6SMatthias Ringwald 
462570b44dd4SMatthias Ringwald     // try to send next pdu
462670b44dd4SMatthias Ringwald     sm_trigger_run();
46273deb3ec6SMatthias Ringwald }
46283deb3ec6SMatthias Ringwald 
46293deb3ec6SMatthias Ringwald // Security Manager Client API
4630a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46313deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46323deb3ec6SMatthias Ringwald }
46333deb3ec6SMatthias Ringwald 
46344acf7b7bSMatthias 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)){
4635a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4636a680ba6bSMatthias Ringwald }
4637a680ba6bSMatthias Ringwald 
463889a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
463989a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
464089a78d34SMatthias Ringwald }
464189a78d34SMatthias Ringwald 
464267f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
464367f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
464467f708e0SMatthias Ringwald }
464567f708e0SMatthias Ringwald 
46463deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46473deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46483deb3ec6SMatthias Ringwald }
46493deb3ec6SMatthias Ringwald 
46503deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46513deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46523deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46533deb3ec6SMatthias Ringwald }
46543deb3ec6SMatthias Ringwald 
46553deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
465698d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
465798d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
465898d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
465998d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
466098d95509SMatthias Ringwald     }
466198d95509SMatthias Ringwald #endif
46623deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
46633deb3ec6SMatthias Ringwald }
46643deb3ec6SMatthias Ringwald 
46653deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
46663deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
46673deb3ec6SMatthias Ringwald }
46683deb3ec6SMatthias Ringwald 
466942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
46703deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
46713deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
46723deb3ec6SMatthias Ringwald }
467342134bc6SMatthias Ringwald #endif
46743deb3ec6SMatthias Ringwald 
46753deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
46766535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
46773deb3ec6SMatthias Ringwald }
46783deb3ec6SMatthias Ringwald 
46793deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
46806535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
46813deb3ec6SMatthias Ringwald }
46823deb3ec6SMatthias Ringwald 
46833deb3ec6SMatthias Ringwald // Testing support only
46843deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
46856535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4686103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4687841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
46883deb3ec6SMatthias Ringwald }
46893deb3ec6SMatthias Ringwald 
46903deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4691841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
46923deb3ec6SMatthias Ringwald }
46933deb3ec6SMatthias Ringwald 
4694d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4695d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4696d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4697d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
469834b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
469970b44dd4SMatthias Ringwald     sm_trigger_run();
4700d1a1f6a4SMatthias Ringwald }
4701674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
470234b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4703674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4704674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4705674e5b4aSMatthias Ringwald }
4706d1a1f6a4SMatthias Ringwald #endif
4707d1a1f6a4SMatthias Ringwald 
4708192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4709192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4710192365feSMatthias Ringwald     test_pairing_failure = reason;
4711192365feSMatthias Ringwald }
4712192365feSMatthias Ringwald #endif
4713192365feSMatthias Ringwald 
47143deb3ec6SMatthias Ringwald void sm_init(void){
47152d2d4d3cSMatthias Ringwald 
47162d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47172d2d4d3cSMatthias Ringwald 
4718899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4719899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4720899e6e02SMatthias Ringwald 
47213deb3ec6SMatthias Ringwald     // defaults
47223deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47233deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4724b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4725b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4726b4343428SMatthias Ringwald 
47273deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47283deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47293deb3ec6SMatthias Ringwald 
47305ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47311979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4732caf15bf3SMatthias Ringwald 
4733d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4734d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47357a766ebfSMatthias Ringwald #endif
47368d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4737fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47383deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47393deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47403deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47413deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47423deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47433deb3ec6SMatthias Ringwald 
47443deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47457149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47463deb3ec6SMatthias Ringwald 
4747841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47483deb3ec6SMatthias Ringwald 
474984c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
475084c0c5c7SMatthias Ringwald 
4751e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4752e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4753e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4754e03e489aSMatthias Ringwald 
4755d1a1f6a4SMatthias Ringwald     //
4756d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4757d1a1f6a4SMatthias Ringwald 
475851bd74d1SMatthias Ringwald     // init le_device_db
475951bd74d1SMatthias Ringwald     le_device_db_init();
476051bd74d1SMatthias Ringwald 
4761b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4762e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
476327c32905SMatthias Ringwald 
476409e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4765674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4766a3aba2f9SMatthias Ringwald #endif
47672d2d4d3cSMatthias Ringwald 
47682d2d4d3cSMatthias Ringwald     sm_initialized = true;
47693deb3ec6SMatthias Ringwald }
47703deb3ec6SMatthias Ringwald 
477115537ea4SMatthias Ringwald void sm_deinit(void){
477215537ea4SMatthias Ringwald     sm_initialized = false;
477315537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
477415537ea4SMatthias Ringwald }
477515537ea4SMatthias Ringwald 
47764b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
47774b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4778caf15bf3SMatthias Ringwald }
4779caf15bf3SMatthias Ringwald 
47806c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
47811979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
47826c39055aSMatthias Ringwald }
47836c39055aSMatthias Ringwald 
4784711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4785711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
47863deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
47873deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
47883deb3ec6SMatthias Ringwald }
47893deb3ec6SMatthias Ringwald 
479077e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
479177e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
479277e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
479377e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
479477e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
479577e2e5edSMatthias Ringwald }
479677e2e5edSMatthias Ringwald #endif
479777e2e5edSMatthias Ringwald 
47986bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4799711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4800711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48013deb3ec6SMatthias Ringwald     if (!sm_conn) return;
48026bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
48036bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
48043deb3ec6SMatthias Ringwald }
48053deb3ec6SMatthias Ringwald 
48063deb3ec6SMatthias Ringwald // request pairing
4807711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4808711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48093deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48103deb3ec6SMatthias Ringwald 
48117af5dcd5SMatthias Ringwald     bool have_ltk;
48127af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48133deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
481442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
481524c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
481624c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
481724c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48187af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48197af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48207af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48217af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48227af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48237af5dcd5SMatthias Ringwald                         if (have_ltk){
48247af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
482524c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48267af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48277af5dcd5SMatthias Ringwald                             break;
48287af5dcd5SMatthias Ringwald                         }
48297af5dcd5SMatthias Ringwald                         /* fall through */
48307af5dcd5SMatthias Ringwald 
48317af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48327af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48337af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48347af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48357af5dcd5SMatthias Ringwald                         break;
48367af5dcd5SMatthias Ringwald                     default:
48377af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48387af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48397af5dcd5SMatthias Ringwald                         break;
48407af5dcd5SMatthias Ringwald                 }
484124c20dc4SMatthias Ringwald                 break;
484224c20dc4SMatthias Ringwald             default:
484324c20dc4SMatthias Ringwald                 break;
484424c20dc4SMatthias Ringwald         }
48453deb3ec6SMatthias Ringwald     } else {
48463deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4847175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4848175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48493deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48503deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48513dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4852f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4853f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4854f53ec649SMatthias Ringwald                         if (have_ltk){
4855c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48565567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4857c245ca32SMatthias Ringwald                             break;
4858f53ec649SMatthias Ringwald                         }
4859cf373d3aSMatthias Ringwald                         /* fall through */
4860c245ca32SMatthias Ringwald 
486134c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48623deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
48633deb3ec6SMatthias Ringwald                         break;
48643deb3ec6SMatthias Ringwald                     default:
4865d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
486609ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48673deb3ec6SMatthias Ringwald                         break;
48683deb3ec6SMatthias Ringwald                 }
4869175b7faaSMatthias Ringwald                 break;
4870cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4871cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4872cb6d7eb0SMatthias Ringwald                 break;
4873175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
487409ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4875175b7faaSMatthias Ringwald                 break;
4876175b7faaSMatthias Ringwald             default:
4877175b7faaSMatthias Ringwald                 break;
48783deb3ec6SMatthias Ringwald         }
48793deb3ec6SMatthias Ringwald     }
488070b44dd4SMatthias Ringwald     sm_trigger_run();
48813deb3ec6SMatthias Ringwald }
48823deb3ec6SMatthias Ringwald 
48833deb3ec6SMatthias Ringwald // called by client app on authorization request
4884711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4885711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48863deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48873deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4888589f5a99SMatthias 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);
48893deb3ec6SMatthias Ringwald }
48903deb3ec6SMatthias Ringwald 
4891711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4892711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48933deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48943deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4895589f5a99SMatthias 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);
48963deb3ec6SMatthias Ringwald }
48973deb3ec6SMatthias Ringwald 
48983deb3ec6SMatthias Ringwald // GAP Bonding API
48993deb3ec6SMatthias Ringwald 
4900711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4901711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49023deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49033deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
49040af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
49050af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
49060af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49070af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49080af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49090af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49100af429c6SMatthias Ringwald #endif
49110af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4912de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4913de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4914de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
491547fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49160af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4917de2fd182SMatthias Ringwald                     break;
491847fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4919de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4920de2fd182SMatthias Ringwald                     break;
4921de2fd182SMatthias Ringwald                 case JUST_WORKS:
4922de2fd182SMatthias Ringwald                 case OOB:
4923de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4924de2fd182SMatthias Ringwald                     break;
49257bbeb3adSMilanka Ringwald                 default:
49267bbeb3adSMilanka Ringwald                     btstack_assert(false);
49277bbeb3adSMilanka Ringwald                     break;
4928de2fd182SMatthias Ringwald             }
49290af429c6SMatthias Ringwald             break;
49300af429c6SMatthias Ringwald         default:
49310af429c6SMatthias Ringwald             break;
49323deb3ec6SMatthias Ringwald     }
493370b44dd4SMatthias Ringwald     sm_trigger_run();
49343deb3ec6SMatthias Ringwald }
49353deb3ec6SMatthias Ringwald 
4936711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4937711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49383deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49393deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49403deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4941136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4942c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4943bbf8db22SMatthias Ringwald         } else {
4944f3582630SMatthias 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);
4945136d331aSMatthias Ringwald         }
49463deb3ec6SMatthias Ringwald     }
49470346c37cSMatthias Ringwald 
49480346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4949c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4950dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4951446a8c36SMatthias Ringwald     }
49520346c37cSMatthias Ringwald #endif
49530346c37cSMatthias Ringwald 
495470b44dd4SMatthias Ringwald     sm_trigger_run();
49553deb3ec6SMatthias Ringwald }
49563deb3ec6SMatthias Ringwald 
4957c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4958c8c46d51SMatthias Ringwald     // for now, it's the same
4959c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4960c8c46d51SMatthias Ringwald }
4961c8c46d51SMatthias Ringwald 
4962711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4963711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49643deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49653deb3ec6SMatthias Ringwald     sm_reset_tk();
4966f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
49673deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
49683deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4969f3582630SMatthias 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);
49703deb3ec6SMatthias Ringwald     }
49711c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49726535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
49736535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
497407036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
497507036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
497607036a04SMatthias Ringwald     }
49771c516d8fSMatthias Ringwald #endif
497870b44dd4SMatthias Ringwald     sm_trigger_run();
49793deb3ec6SMatthias Ringwald }
49803deb3ec6SMatthias Ringwald 
49813d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
49823d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49833d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49843d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4985dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
49864ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4987dd4a08fbSMatthias Ringwald     switch (action){
4988dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4989dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
49904ea43905SMatthias Ringwald             flags |= (1u << action);
4991dd4a08fbSMatthias Ringwald             break;
4992dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4993dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
49944ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4995dd4a08fbSMatthias Ringwald             break;
4996dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
49974ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4998dd4a08fbSMatthias Ringwald                 // erase actions queued
4999dd4a08fbSMatthias Ringwald                 num_actions--;
50004ea43905SMatthias Ringwald                 if (num_actions == 0u){
5001dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50024ea43905SMatthias Ringwald                     flags &= 0x19u;
5003dd4a08fbSMatthias Ringwald                 }
5004dd4a08fbSMatthias Ringwald                 break;
5005dd4a08fbSMatthias Ringwald             }
5006dd4a08fbSMatthias Ringwald             num_actions++;
50074ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5008dd4a08fbSMatthias Ringwald             break;
5009dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50104ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5011dd4a08fbSMatthias Ringwald                 // enter actions queued
5012dd4a08fbSMatthias Ringwald                 num_actions--;
50134ea43905SMatthias Ringwald                 if (num_actions == 0u){
5014dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50154ea43905SMatthias Ringwald                     flags &= 0x19u;
5016dd4a08fbSMatthias Ringwald                 }
5017dd4a08fbSMatthias Ringwald                 break;
5018dd4a08fbSMatthias Ringwald             }
5019dd4a08fbSMatthias Ringwald             num_actions++;
50204ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5021dd4a08fbSMatthias Ringwald             break;
5022dd4a08fbSMatthias Ringwald         default:
5023dd4a08fbSMatthias Ringwald             break;
5024dd4a08fbSMatthias Ringwald     }
5025dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
502670b44dd4SMatthias Ringwald     sm_trigger_run();
50273d7fe1e9SMatthias Ringwald }
50283d7fe1e9SMatthias Ringwald 
5029c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5030d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5031d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5032d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
503370b44dd4SMatthias Ringwald     sm_trigger_run();
5034d1a1f6a4SMatthias Ringwald }
5035c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50368334d3d8SMatthias Ringwald 
50378334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50388334d3d8SMatthias Ringwald 
5039c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5040c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5041d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5042d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5043c59d0c92SMatthias Ringwald     return 0;
5044c59d0c92SMatthias Ringwald }
5045c59d0c92SMatthias Ringwald #endif
5046c59d0c92SMatthias Ringwald 
50473deb3ec6SMatthias Ringwald /**
5048ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5049ba394633SMatthias Ringwald  * @param con_handle
5050ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5051ba394633SMatthias Ringwald  */
5052ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5053ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5054ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5055ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5056ba394633SMatthias Ringwald }
5057ba394633SMatthias Ringwald 
5058ba394633SMatthias Ringwald /**
50593deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50603deb3ec6SMatthias Ringwald  * @param handle
50616b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
50623deb3ec6SMatthias Ringwald  */
5063711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5064711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50653deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
50663deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
50673deb3ec6SMatthias Ringwald }
50683deb3ec6SMatthias Ringwald 
50698f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
507047ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
507147ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
507247ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
507347ba4de1SMatthias Ringwald             return 0;
507447ba4de1SMatthias Ringwald         default:
50758f57b085SMatthias Ringwald             return 1;
50768f57b085SMatthias Ringwald     }
507747ba4de1SMatthias Ringwald }
5078d70217a2SMatthias Ringwald 
507933373e40SMatthias Ringwald static uint8_t own_address_type(void){
5080b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5081b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5082b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5083b95a5a35SMatthias Ringwald         default:
5084b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5085b95a5a35SMatthias Ringwald     }
508633373e40SMatthias Ringwald }
50878f57b085SMatthias Ringwald 
50883deb3ec6SMatthias Ringwald // GAP LE API
50893deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
50903deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
50913deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5092b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
50938f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
50943deb3ec6SMatthias Ringwald     gap_random_address_update_start();
50953deb3ec6SMatthias Ringwald     gap_random_address_trigger();
50963deb3ec6SMatthias Ringwald }
50973deb3ec6SMatthias Ringwald 
50983deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
50993deb3ec6SMatthias Ringwald     return gap_random_adress_type;
51003deb3ec6SMatthias Ringwald }
51013deb3ec6SMatthias Ringwald 
51023deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
51033deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
51048f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51053deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51063deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51073deb3ec6SMatthias Ringwald }
51083deb3ec6SMatthias Ringwald 
5109667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51108f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51116535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5112e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
51137e252622SMatthias Ringwald }
51147e252622SMatthias Ringwald 
5115d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51163deb3ec6SMatthias Ringwald /*
51173deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51183deb3ec6SMatthias Ringwald  * @param adv_int_min
51193deb3ec6SMatthias Ringwald  * @param adv_int_max
51203deb3ec6SMatthias Ringwald  * @param adv_type
51213deb3ec6SMatthias Ringwald  * @param direct_address_type
51223deb3ec6SMatthias Ringwald  * @param direct_address
51233deb3ec6SMatthias Ringwald  * @param channel_map
51243deb3ec6SMatthias Ringwald  * @param filter_policy
51253deb3ec6SMatthias Ringwald  *
51263deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51273deb3ec6SMatthias Ringwald  */
51283deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51293deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5130b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51313deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51323deb3ec6SMatthias Ringwald }
5133d70217a2SMatthias Ringwald #endif
5134dcd6c9b5SMatthias Ringwald 
5135dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5136dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5137dcd6c9b5SMatthias Ringwald      // wrong connection
5138dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5139dcd6c9b5SMatthias Ringwald     // already encrypted
5140dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5141dcd6c9b5SMatthias Ringwald     // irk status?
5142dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5143dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5144dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5145dcd6c9b5SMatthias Ringwald             return 0;
5146dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5147dcd6c9b5SMatthias Ringwald             break;
5148dcd6c9b5SMatthias Ringwald         default:
5149dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5150dcd6c9b5SMatthias Ringwald             return 1;
5151dcd6c9b5SMatthias Ringwald     }
5152f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5153f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5154b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5155b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5156b15d5ceaSMatthias Ringwald     } else {
5157dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5158dcd6c9b5SMatthias Ringwald     }
5159b15d5ceaSMatthias Ringwald }
51603cdbe9dbSMatthias Ringwald 
51613cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
51623cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51633cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
51643cdbe9dbSMatthias Ringwald #else
51653cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
51663cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
51673cdbe9dbSMatthias Ringwald #endif
51683cdbe9dbSMatthias Ringwald }
5169052bbdc5SMatthias Ringwald 
5170052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5171052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5172052bbdc5SMatthias Ringwald }
51734f384501SMatthias Ringwald 
51744f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
51754f384501SMatthias Ringwald     uint16_t i;
51764f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
51774f384501SMatthias Ringwald         bd_addr_t entry_address;
51784f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
51794f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
51804f384501SMatthias Ringwald         // skip unused entries
51814f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
51824f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
51834f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
51844f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
51854f384501SMatthias Ringwald #endif
51864f384501SMatthias Ringwald             le_device_db_remove(i);
51874f384501SMatthias Ringwald             break;
51884f384501SMatthias Ringwald         }
51894f384501SMatthias Ringwald     }
51904f384501SMatthias Ringwald }
5191