xref: /btstack/src/ble/sm.c (revision c82679c3b2ae2362f4ecb86cdd8dfc65eb8cd1c4)
13deb3ec6SMatthias Ringwald /*
23deb3ec6SMatthias Ringwald  * Copyright (C) 2014 BlueKitchen GmbH
33deb3ec6SMatthias Ringwald  *
43deb3ec6SMatthias Ringwald  * Redistribution and use in source and binary forms, with or without
53deb3ec6SMatthias Ringwald  * modification, are permitted provided that the following conditions
63deb3ec6SMatthias Ringwald  * are met:
73deb3ec6SMatthias Ringwald  *
83deb3ec6SMatthias Ringwald  * 1. Redistributions of source code must retain the above copyright
93deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer.
103deb3ec6SMatthias Ringwald  * 2. Redistributions in binary form must reproduce the above copyright
113deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer in the
123deb3ec6SMatthias Ringwald  *    documentation and/or other materials provided with the distribution.
133deb3ec6SMatthias Ringwald  * 3. Neither the name of the copyright holders nor the names of
143deb3ec6SMatthias Ringwald  *    contributors may be used to endorse or promote products derived
153deb3ec6SMatthias Ringwald  *    from this software without specific prior written permission.
163deb3ec6SMatthias Ringwald  * 4. Any redistribution, use, or modification is done solely for
173deb3ec6SMatthias Ringwald  *    personal benefit and not for any commercial purpose or for
183deb3ec6SMatthias Ringwald  *    monetary gain.
193deb3ec6SMatthias Ringwald  *
203deb3ec6SMatthias Ringwald  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
213deb3ec6SMatthias Ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
223deb3ec6SMatthias Ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
233deb3ec6SMatthias Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
243deb3ec6SMatthias Ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
253deb3ec6SMatthias Ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
263deb3ec6SMatthias Ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
273deb3ec6SMatthias Ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
283deb3ec6SMatthias Ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
293deb3ec6SMatthias Ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
303deb3ec6SMatthias Ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
313deb3ec6SMatthias Ringwald  * SUCH DAMAGE.
323deb3ec6SMatthias Ringwald  *
333deb3ec6SMatthias Ringwald  * Please inquire about commercial licensing options at
343deb3ec6SMatthias Ringwald  * [email protected]
353deb3ec6SMatthias Ringwald  *
363deb3ec6SMatthias Ringwald  */
37ab2c6ae4SMatthias Ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "sm.c"
393deb3ec6SMatthias Ringwald 
403deb3ec6SMatthias Ringwald #include <string.h>
413deb3ec6SMatthias Ringwald #include <inttypes.h>
423deb3ec6SMatthias Ringwald 
433edc84c5SMatthias Ringwald #include "ble/le_device_db.h"
4459c6af15SMatthias Ringwald #include "ble/core.h"
453edc84c5SMatthias Ringwald #include "ble/sm.h"
4661f37892SMatthias Ringwald #include "bluetooth_company_id.h"
47d7f1c72eSMatthias Ringwald #include "btstack_bool.h"
48d1a1f6a4SMatthias Ringwald #include "btstack_crypto.h"
490e2df43fSMatthias Ringwald #include "btstack_debug.h"
500e2df43fSMatthias Ringwald #include "btstack_event.h"
510e2df43fSMatthias Ringwald #include "btstack_linked_list.h"
520e2df43fSMatthias Ringwald #include "btstack_memory.h"
53899e6e02SMatthias Ringwald #include "btstack_tlv.h"
54f7a05cdaSMatthias Ringwald #include "gap.h"
550e2df43fSMatthias Ringwald #include "hci.h"
5613377825SMatthias Ringwald #include "hci_dump.h"
570e2df43fSMatthias Ringwald #include "l2cap.h"
583deb3ec6SMatthias Ringwald 
591a682202SMatthias Ringwald #if !defined(ENABLE_LE_PERIPHERAL) && !defined(ENABLE_LE_CENTRAL)
601a682202SMatthias Ringwald #error "LE Security Manager used, but neither ENABLE_LE_PERIPHERAL nor ENABLE_LE_CENTRAL defined. Please add at least one to btstack_config.h."
611a682202SMatthias Ringwald #endif
621a682202SMatthias Ringwald 
637ece0eaaSMatthias Ringwald #if defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION) && (!defined(ENABLE_CLASSIC) || !defined(ENABLE_LE_SECURE_CONNECTIONS))
647ece0eaaSMatthias Ringwald #error "Cross Transport Key Derivation requires support for LE Secure Connections and BR/EDR (Classic)"
656857ad8fSMatthias Ringwald #endif
666857ad8fSMatthias Ringwald 
67d1a1f6a4SMatthias Ringwald // assert SM Public Key can be sent/received
68d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
69d1a1f6a4SMatthias Ringwald #if HCI_ACL_PAYLOAD_SIZE < 69
70d1a1f6a4SMatthias Ringwald #error "HCI_ACL_PAYLOAD_SIZE must be at least 69 bytes when using LE Secure Conection. Please increase HCI_ACL_PAYLOAD_SIZE or disable ENABLE_LE_SECURE_CONNECTIONS"
71d1a1f6a4SMatthias Ringwald #endif
72d1a1f6a4SMatthias Ringwald #endif
73d1a1f6a4SMatthias Ringwald 
7442134bc6SMatthias Ringwald #if defined(ENABLE_LE_PERIPHERAL) && defined(ENABLE_LE_CENTRAL)
7542134bc6SMatthias Ringwald #define IS_RESPONDER(role) (role)
7642134bc6SMatthias Ringwald #else
7742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7842134bc6SMatthias Ringwald // only central - never responder (avoid 'unused variable' warnings)
7942134bc6SMatthias Ringwald #define IS_RESPONDER(role) (0 && role)
8042134bc6SMatthias Ringwald #else
8142134bc6SMatthias Ringwald // only peripheral - always responder (avoid 'unused variable' warnings)
8242134bc6SMatthias Ringwald #define IS_RESPONDER(role) (1 || role)
8342134bc6SMatthias Ringwald #endif
8442134bc6SMatthias Ringwald #endif
8542134bc6SMatthias Ringwald 
867a766ebfSMatthias Ringwald #if defined(ENABLE_LE_SIGNED_WRITE) || defined(ENABLE_LE_SECURE_CONNECTIONS)
87d1a1f6a4SMatthias Ringwald #define USE_CMAC_ENGINE
887a766ebfSMatthias Ringwald #endif
897a766ebfSMatthias Ringwald 
906857ad8fSMatthias Ringwald 
91968b2eafSMatthias Ringwald #define BTSTACK_TAG32(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))
92899e6e02SMatthias Ringwald 
933deb3ec6SMatthias Ringwald //
943deb3ec6SMatthias Ringwald // SM internal types and globals
953deb3ec6SMatthias Ringwald //
963deb3ec6SMatthias Ringwald 
973deb3ec6SMatthias Ringwald typedef enum {
983deb3ec6SMatthias Ringwald     DKG_W4_WORKING,
993deb3ec6SMatthias Ringwald     DKG_CALC_IRK,
1003deb3ec6SMatthias Ringwald     DKG_CALC_DHK,
1013deb3ec6SMatthias Ringwald     DKG_READY
1023deb3ec6SMatthias Ringwald } derived_key_generation_t;
1033deb3ec6SMatthias Ringwald 
1043deb3ec6SMatthias Ringwald typedef enum {
1053deb3ec6SMatthias Ringwald     RAU_IDLE,
106fbd4e238SMatthias Ringwald     RAU_GET_RANDOM,
1073deb3ec6SMatthias Ringwald     RAU_W4_RANDOM,
1083deb3ec6SMatthias Ringwald     RAU_GET_ENC,
1093deb3ec6SMatthias Ringwald     RAU_W4_ENC,
1103deb3ec6SMatthias Ringwald     RAU_SET_ADDRESS,
1113deb3ec6SMatthias Ringwald } random_address_update_t;
1123deb3ec6SMatthias Ringwald 
1133deb3ec6SMatthias Ringwald typedef enum {
1143deb3ec6SMatthias Ringwald     CMAC_IDLE,
1153deb3ec6SMatthias Ringwald     CMAC_CALC_SUBKEYS,
1163deb3ec6SMatthias Ringwald     CMAC_W4_SUBKEYS,
1173deb3ec6SMatthias Ringwald     CMAC_CALC_MI,
1183deb3ec6SMatthias Ringwald     CMAC_W4_MI,
1193deb3ec6SMatthias Ringwald     CMAC_CALC_MLAST,
1203deb3ec6SMatthias Ringwald     CMAC_W4_MLAST
1213deb3ec6SMatthias Ringwald } cmac_state_t;
1223deb3ec6SMatthias Ringwald 
1233deb3ec6SMatthias Ringwald typedef enum {
1243deb3ec6SMatthias Ringwald     JUST_WORKS,
12527c32905SMatthias Ringwald     PK_RESP_INPUT,       // Initiator displays PK, responder inputs PK
12627c32905SMatthias Ringwald     PK_INIT_INPUT,       // Responder displays PK, initiator inputs PK
12747fb4255SMatthias Ringwald     PK_BOTH_INPUT,       // Only input on both, both input PK
12847fb4255SMatthias Ringwald     NUMERIC_COMPARISON,  // Only numerical compparison (yes/no) on on both sides
12947fb4255SMatthias Ringwald     OOB                  // OOB available on one (SC) or both sides (legacy)
1303deb3ec6SMatthias Ringwald } stk_generation_method_t;
1313deb3ec6SMatthias Ringwald 
1323deb3ec6SMatthias Ringwald typedef enum {
1333deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_IDLE,
1343deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PENDING,
1353deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_CONFIRM,
1363deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PASSKEY,
1373deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_DECLINE
1383deb3ec6SMatthias Ringwald } sm_user_response_t;
1393deb3ec6SMatthias Ringwald 
1403deb3ec6SMatthias Ringwald typedef enum {
1413deb3ec6SMatthias Ringwald     SM_AES128_IDLE,
1423deb3ec6SMatthias Ringwald     SM_AES128_ACTIVE
1433deb3ec6SMatthias Ringwald } sm_aes128_state_t;
1443deb3ec6SMatthias Ringwald 
1453deb3ec6SMatthias Ringwald typedef enum {
1463deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_IDLE,
1473deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_GENERAL,
1483deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FOR_CONNECTION,
1493deb3ec6SMatthias Ringwald } address_resolution_mode_t;
1503deb3ec6SMatthias Ringwald 
1513deb3ec6SMatthias Ringwald typedef enum {
152a66b030fSMatthias Ringwald     ADDRESS_RESOLUTION_SUCCEEDED,
1533deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FAILED,
1543deb3ec6SMatthias Ringwald } address_resolution_event_t;
155901c000fSMatthias Ringwald 
156901c000fSMatthias Ringwald typedef enum {
15734b6528fSMatthias Ringwald     EC_KEY_GENERATION_IDLE,
1587df18c15SMatthias Ringwald     EC_KEY_GENERATION_ACTIVE,
1597df18c15SMatthias Ringwald     EC_KEY_GENERATION_DONE,
1607df18c15SMatthias Ringwald } ec_key_generation_state_t;
1617df18c15SMatthias Ringwald 
1627df18c15SMatthias Ringwald typedef enum {
1633cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_NEEDED = 1 << 0,
1643cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1,
1653cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2,
166901c000fSMatthias Ringwald } sm_state_var_t;
167901c000fSMatthias Ringwald 
168c59d0c92SMatthias Ringwald typedef enum {
169c59d0c92SMatthias Ringwald     SM_SC_OOB_IDLE,
170d1a1f6a4SMatthias Ringwald     SM_SC_OOB_W4_RANDOM,
171c59d0c92SMatthias Ringwald     SM_SC_OOB_W2_CALC_CONFIRM,
172c59d0c92SMatthias Ringwald     SM_SC_OOB_W4_CONFIRM,
173c59d0c92SMatthias Ringwald } sm_sc_oob_state_t;
174c59d0c92SMatthias Ringwald 
1756420f61eSMatthias Ringwald typedef uint8_t sm_key24_t[3];
1766420f61eSMatthias Ringwald typedef uint8_t sm_key56_t[7];
1776420f61eSMatthias Ringwald typedef uint8_t sm_key256_t[32];
1786420f61eSMatthias Ringwald 
1793deb3ec6SMatthias Ringwald //
1803deb3ec6SMatthias Ringwald // GLOBAL DATA
1813deb3ec6SMatthias Ringwald //
1823deb3ec6SMatthias Ringwald 
1832d2d4d3cSMatthias Ringwald static bool sm_initialized;
1842d2d4d3cSMatthias Ringwald 
185841468bbSMatthias Ringwald static bool test_use_fixed_local_csrk;
186841468bbSMatthias Ringwald static bool test_use_fixed_local_irk;
1873deb3ec6SMatthias Ringwald 
188192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
189192365feSMatthias Ringwald static uint8_t test_pairing_failure;
190192365feSMatthias Ringwald #endif
191192365feSMatthias Ringwald 
1923deb3ec6SMatthias Ringwald // configuration
1933deb3ec6SMatthias Ringwald static uint8_t sm_accepted_stk_generation_methods;
1943deb3ec6SMatthias Ringwald static uint8_t sm_max_encryption_key_size;
1953deb3ec6SMatthias Ringwald static uint8_t sm_min_encryption_key_size;
1963deb3ec6SMatthias Ringwald static uint8_t sm_auth_req = 0;
1973deb3ec6SMatthias Ringwald static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1983deb3ec6SMatthias Ringwald static uint8_t sm_slave_request_security;
1994b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
2001979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
2013deb3ec6SMatthias Ringwald 
202c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
203c123d999SMatthias Ringwald static bool sm_sc_only_mode;
204c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
205c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
206c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
207c59d0c92SMatthias Ringwald #endif
208c59d0c92SMatthias Ringwald 
209899e6e02SMatthias Ringwald 
2101979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
211899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
212899e6e02SMatthias Ringwald static void *                sm_tlv_context;
213899e6e02SMatthias Ringwald 
2143deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2153deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2163deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2173deb3ec6SMatthias Ringwald 
2183deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2193deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2203deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2213deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2223deb3ec6SMatthias Ringwald 
2233deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2243deb3ec6SMatthias Ringwald // ..
2253deb3ec6SMatthias Ringwald 
2263deb3ec6SMatthias Ringwald // random address update
2273deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2283deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2293deb3ec6SMatthias Ringwald 
230d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
231514d35fcSMatthias Ringwald // CMAC Calculation: General
232d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
233d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
234d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
235d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2367a766ebfSMatthias Ringwald #endif
237514d35fcSMatthias Ringwald 
238514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2397a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
240d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
241d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
242d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
243d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2447a766ebfSMatthias Ringwald #endif
245514d35fcSMatthias Ringwald 
246514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
247514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
248aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
249514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
250514d35fcSMatthias Ringwald #endif
2513deb3ec6SMatthias Ringwald 
2523deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2533deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2543deb3ec6SMatthias Ringwald static int       sm_address_resolution_ah_calculation_active;
2553deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2563deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2573deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2583deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2598f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2603deb3ec6SMatthias Ringwald 
261d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2623deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2633deb3ec6SMatthias Ringwald 
264d1a1f6a4SMatthias Ringwald // crypto
265d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
266d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
267d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
268d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2697df1ef2fSMatthias Ringwald #endif
2707df1ef2fSMatthias Ringwald 
271d1a1f6a4SMatthias Ringwald // temp storage for random data
272d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
273d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
274d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
275d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2763deb3ec6SMatthias Ringwald 
277e03e489aSMatthias Ringwald // to receive hci events
278e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
279e03e489aSMatthias Ringwald 
28089a78d34SMatthias Ringwald /* to dispatch sm event */
28189a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28289a78d34SMatthias Ringwald 
283ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
284ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
285ece00d2dSMatthias Ringwald 
28609e4d397SMatthias Ringwald // LE Secure Connections
28709e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
28809e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
289fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
29009e4d397SMatthias Ringwald #endif
291df86eb96SMatthias Ringwald 
2923deb3ec6SMatthias Ringwald //
2933deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2943deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2953deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2963deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2973deb3ec6SMatthias Ringwald //
2983deb3ec6SMatthias Ringwald 
2993deb3ec6SMatthias Ringwald // data needed for security setup
3003deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3013deb3ec6SMatthias Ringwald 
302ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3033deb3ec6SMatthias Ringwald 
3043deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3053deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
306dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3073deb3ec6SMatthias Ringwald 
3083deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
309715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
310715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3119a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3133deb3ec6SMatthias Ringwald 
3143deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3153deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3163deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
317a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
31827c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3193deb3ec6SMatthias Ringwald 
3203deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3213deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3223deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3233deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3273deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3283deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3293deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3303deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3313deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3323deb3ec6SMatthias Ringwald 
33368437d83SMatthias Ringwald     uint8_t   sm_state_vars;
334e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
335fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
336446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
337446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
338d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
339e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
340e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
341446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
342446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3432bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
344a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3457df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
346e53be891SMatthias Ringwald #endif
34727c32905SMatthias Ringwald 
3483deb3ec6SMatthias Ringwald     // Phase 3
3493deb3ec6SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // key distribution, we generate
3513deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3523deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3543deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3553deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3563deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3583deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3593deb3ec6SMatthias Ringwald 
3603deb3ec6SMatthias Ringwald     // key distribution, received from peer
3613deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3623deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3643deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3653deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3663deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3683deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3693deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
370715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
371715a43d1SMatthias Ringwald     int       sm_le_device_index;
372715a43d1SMatthias Ringwald #endif
3733deb3ec6SMatthias Ringwald } sm_setup_context_t;
3743deb3ec6SMatthias Ringwald 
3753deb3ec6SMatthias Ringwald //
3763deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3773deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3783deb3ec6SMatthias Ringwald 
3793deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3807149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3813deb3ec6SMatthias Ringwald 
3823deb3ec6SMatthias Ringwald // @returns 1 if oob data is available
3833deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3843deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3854acf7b7bSMatthias 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);
3863deb3ec6SMatthias Ringwald 
3873deb3ec6SMatthias Ringwald static void sm_run(void);
388711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
389711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
3903deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3913deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
392d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
393d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
394d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
395d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
396d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
397d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
398d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4022a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4052a526f21SMatthias Ringwald #endif
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
410d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4116d80b495SMatthias 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));
41234b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4136ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4146ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4152a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
416d1a1f6a4SMatthias Ringwald #endif
4170ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4183deb3ec6SMatthias Ringwald 
4193deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4203deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4213deb3ec6SMatthias Ringwald }
4223deb3ec6SMatthias Ringwald 
4231fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4241fbd72c5SMatthias Ringwald //     return packet[0];
4251fbd72c5SMatthias Ringwald // }
4261fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4271fbd72c5SMatthias Ringwald     return packet[1];
4281fbd72c5SMatthias Ringwald }
4291fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4301fbd72c5SMatthias Ringwald     return packet[2];
4311fbd72c5SMatthias Ringwald }
4321fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4331fbd72c5SMatthias Ringwald     return packet[3];
4341fbd72c5SMatthias Ringwald }
4351fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4361fbd72c5SMatthias Ringwald     return packet[4];
4371fbd72c5SMatthias Ringwald }
4381fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4391fbd72c5SMatthias Ringwald     return packet[5];
4401fbd72c5SMatthias Ringwald }
4411fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4421fbd72c5SMatthias Ringwald     return packet[6];
4431fbd72c5SMatthias Ringwald }
4441fbd72c5SMatthias Ringwald 
4451fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4461fbd72c5SMatthias Ringwald     packet[0] = code;
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4491fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4521fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4531fbd72c5SMatthias Ringwald }
4541fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4551fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4561fbd72c5SMatthias Ringwald }
4571fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4581fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4591fbd72c5SMatthias Ringwald }
4601fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4611fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4621fbd72c5SMatthias Ringwald }
4631fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4641fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4651fbd72c5SMatthias Ringwald }
4661fbd72c5SMatthias Ringwald 
4673deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4681979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4693deb3ec6SMatthias Ringwald     int i;
4703764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47184c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4721979f09cSMatthias Ringwald             return false;
47384c0c5c7SMatthias Ringwald         }
4743deb3ec6SMatthias Ringwald     }
4751979f09cSMatthias Ringwald     return true;
4763deb3ec6SMatthias Ringwald }
4773deb3ec6SMatthias Ringwald 
4781979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4793764b551SMatthias Ringwald     return sm_is_null(random, 8);
4803764b551SMatthias Ringwald }
4813764b551SMatthias Ringwald 
4821979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4833764b551SMatthias Ringwald     return sm_is_null(key, 16);
4843764b551SMatthias Ringwald }
4853764b551SMatthias Ringwald 
48670b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
48770b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
48870b44dd4SMatthias Ringwald 	UNUSED(ts);
48970b44dd4SMatthias Ringwald 	sm_run();
49070b44dd4SMatthias Ringwald }
49170b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4922d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49384c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49470b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49570b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49670b44dd4SMatthias Ringwald }
49770b44dd4SMatthias Ringwald 
4983deb3ec6SMatthias Ringwald // Key utils
4993deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5003deb3ec6SMatthias Ringwald     int i;
5013deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5023deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5033deb3ec6SMatthias Ringwald     }
5043deb3ec6SMatthias Ringwald }
5053deb3ec6SMatthias Ringwald 
5063deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5073deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5083deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5093deb3ec6SMatthias Ringwald     int i;
5103deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5113deb3ec6SMatthias Ringwald         key[15-i] = 0;
5123deb3ec6SMatthias Ringwald     }
5133deb3ec6SMatthias Ringwald }
5143deb3ec6SMatthias Ringwald 
515899e6e02SMatthias Ringwald // ER / IR checks
51621045273SMatthias Ringwald static void sm_er_ir_set_default(void){
517899e6e02SMatthias Ringwald     int i;
518899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
519899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
520899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
521899e6e02SMatthias Ringwald     }
522899e6e02SMatthias Ringwald }
523899e6e02SMatthias Ringwald 
524899e6e02SMatthias Ringwald static int sm_er_is_default(void){
525899e6e02SMatthias Ringwald     int i;
526899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
527899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
528899e6e02SMatthias Ringwald     }
529899e6e02SMatthias Ringwald     return 1;
530899e6e02SMatthias Ringwald }
531899e6e02SMatthias Ringwald 
532899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
533899e6e02SMatthias Ringwald     int i;
534899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
535899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
536899e6e02SMatthias Ringwald     }
537899e6e02SMatthias Ringwald     return 1;
538899e6e02SMatthias Ringwald }
539899e6e02SMatthias Ringwald 
54073102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54173102768SMatthias Ringwald     UNUSED(channel);
54273102768SMatthias Ringwald 
54373102768SMatthias Ringwald     // log event
54473102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54573102768SMatthias Ringwald     // dispatch to all event handlers
54673102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
54773102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
54873102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
54973102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55073102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55173102768SMatthias Ringwald     }
55273102768SMatthias Ringwald }
55373102768SMatthias Ringwald 
55473102768SMatthias 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){
55573102768SMatthias Ringwald     event[0] = type;
55673102768SMatthias Ringwald     event[1] = event_size - 2;
55773102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
55873102768SMatthias Ringwald     event[4] = addr_type;
55973102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56073102768SMatthias Ringwald }
56173102768SMatthias Ringwald 
56273102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56373102768SMatthias Ringwald     uint8_t event[11];
56473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56673102768SMatthias Ringwald }
56773102768SMatthias Ringwald 
56873102768SMatthias 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){
56973102768SMatthias Ringwald     uint8_t event[15];
57073102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57173102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57373102768SMatthias Ringwald }
57473102768SMatthias Ringwald 
57573102768SMatthias 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){
57673102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57773102768SMatthias Ringwald     bd_addr_t identity_address;
57873102768SMatthias Ringwald     int identity_address_type;
57973102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58073102768SMatthias Ringwald 
58173102768SMatthias Ringwald     uint8_t event[20];
58273102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58373102768SMatthias Ringwald     event[11] = identity_address_type;
58473102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58573102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58773102768SMatthias Ringwald }
58873102768SMatthias Ringwald 
58973102768SMatthias 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){
59073102768SMatthias Ringwald     uint8_t event[12];
59173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59273102768SMatthias Ringwald     event[11] = status;
59373102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59473102768SMatthias Ringwald }
59573102768SMatthias Ringwald 
59673102768SMatthias Ringwald 
59773102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
59873102768SMatthias Ringwald 
5993ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6003ab61f77SMatthias Ringwald 
6017b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60273102768SMatthias Ringwald 
60373102768SMatthias Ringwald     int       identity_addr_type;
60473102768SMatthias Ringwald     bd_addr_t identity_addr;
6053c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6063c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6083c0e26deSMatthias Ringwald     } else {
6093c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6103c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6113c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6123c0e26deSMatthias Ringwald     }
61373102768SMatthias Ringwald 
61473102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61573102768SMatthias Ringwald }
61673102768SMatthias Ringwald 
61773102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
61873102768SMatthias Ringwald 
61960be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62060be5b21SMatthias Ringwald 
6217b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62273102768SMatthias Ringwald 
62373102768SMatthias Ringwald     int       identity_addr_type;
62473102768SMatthias Ringwald     bd_addr_t identity_addr;
6253c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6263c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6283c0e26deSMatthias Ringwald     } else {
6293c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6303c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6313c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6323c0e26deSMatthias Ringwald     }
63373102768SMatthias Ringwald 
63473102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63573102768SMatthias Ringwald }
63673102768SMatthias Ringwald 
637d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
638d3c12277SMatthias Ringwald 
639d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
640d3c12277SMatthias Ringwald 
641d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
642d3c12277SMatthias Ringwald 
643d3c12277SMatthias Ringwald     uint8_t event[11];
644d3c12277SMatthias 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);
645d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
646d3c12277SMatthias Ringwald }
647d3c12277SMatthias Ringwald 
6480ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
649f61072f5SMatthias Ringwald 
650d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
651d77906ffSMatthias Ringwald 
65269f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65369f82ad8SMatthias Ringwald 
6540ccf6c9cSMatthias Ringwald     uint8_t event[13];
6550ccf6c9cSMatthias 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);
6560ccf6c9cSMatthias Ringwald     event[11] = status;
6570ccf6c9cSMatthias Ringwald     event[12] = reason;
6580ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6590ccf6c9cSMatthias Ringwald }
6600ccf6c9cSMatthias Ringwald 
6613deb3ec6SMatthias Ringwald // SMP Timeout implementation
6623deb3ec6SMatthias Ringwald 
6633deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6643deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6653deb3ec6SMatthias Ringwald //
6663deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6673deb3ec6SMatthias Ringwald //
6683deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6693deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6703deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6713deb3ec6SMatthias Ringwald // established.
6723deb3ec6SMatthias Ringwald 
673ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6743deb3ec6SMatthias Ringwald     log_info("SM timeout");
675c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6763deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67768a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6780ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6793deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6803deb3ec6SMatthias Ringwald 
6813deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6823deb3ec6SMatthias Ringwald     sm_run();
6833deb3ec6SMatthias Ringwald }
6843deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
685528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
687528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
688528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
689528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6903deb3ec6SMatthias Ringwald }
6913deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
692528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6933deb3ec6SMatthias Ringwald }
6943deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6953deb3ec6SMatthias Ringwald     sm_timeout_stop();
6963deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald 
6993deb3ec6SMatthias Ringwald // end of sm timeout
7003deb3ec6SMatthias Ringwald 
7013deb3ec6SMatthias Ringwald // GAP Random Address updates
7023deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
703ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7043deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7053deb3ec6SMatthias Ringwald 
7063deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
707899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
708d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
709fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71070b44dd4SMatthias Ringwald     sm_trigger_run();
7113deb3ec6SMatthias Ringwald }
7123deb3ec6SMatthias Ringwald 
713ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7149ec2630cSMatthias Ringwald     UNUSED(timer);
7159ec2630cSMatthias Ringwald 
7163deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
717528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
718528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7193deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7203deb3ec6SMatthias Ringwald }
7213deb3ec6SMatthias Ringwald 
7223deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
723528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
724528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
725528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7263deb3ec6SMatthias Ringwald }
7273deb3ec6SMatthias Ringwald 
7283deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
729528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7303deb3ec6SMatthias Ringwald }
7313deb3ec6SMatthias Ringwald 
7323deb3ec6SMatthias Ringwald // ah(k,r) helper
7333deb3ec6SMatthias Ringwald // r = padding || r
7343deb3ec6SMatthias Ringwald // r - 24 bit value
7354a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7363deb3ec6SMatthias Ringwald     // r'= padding || r
7373deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7386535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7393deb3ec6SMatthias Ringwald }
7403deb3ec6SMatthias Ringwald 
7413deb3ec6SMatthias Ringwald // d1 helper
7423deb3ec6SMatthias Ringwald // d' = padding || r || d
7433deb3ec6SMatthias Ringwald // d,r - 16 bit values
7444a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7453deb3ec6SMatthias Ringwald     // d'= padding || r || d
7463deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
747f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
748f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7493deb3ec6SMatthias Ringwald }
7503deb3ec6SMatthias Ringwald 
7513deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7524a6806f3SMatthias 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){
7533deb3ec6SMatthias Ringwald 
7543deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7553deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7563deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7573deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7583deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7593deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald     sm_key_t p1;
7629c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7639c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7643deb3ec6SMatthias Ringwald     p1[14] = rat;
7653deb3ec6SMatthias Ringwald     p1[15] = iat;
7668314c363SMatthias Ringwald     log_info_key("p1", p1);
7678314c363SMatthias Ringwald     log_info_key("r", r);
7683deb3ec6SMatthias Ringwald 
7693deb3ec6SMatthias Ringwald     // t1 = r xor p1
7703deb3ec6SMatthias Ringwald     int i;
7713deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7723deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7733deb3ec6SMatthias Ringwald     }
7748314c363SMatthias Ringwald     log_info_key("t1", t1);
7753deb3ec6SMatthias Ringwald }
7763deb3ec6SMatthias Ringwald 
7773deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7784a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7793deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7803deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7813deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7823deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7833deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7843deb3ec6SMatthias Ringwald 
7853deb3ec6SMatthias Ringwald     sm_key_t p2;
7863deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7876535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7886535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7898314c363SMatthias Ringwald     log_info_key("p2", p2);
7903deb3ec6SMatthias Ringwald 
7913deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7923deb3ec6SMatthias Ringwald     int i;
7933deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7943deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7953deb3ec6SMatthias Ringwald     }
7968314c363SMatthias Ringwald     log_info_key("t3", t3);
7973deb3ec6SMatthias Ringwald }
7983deb3ec6SMatthias Ringwald 
7994a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8008314c363SMatthias Ringwald     log_info_key("r1", r1);
8018314c363SMatthias Ringwald     log_info_key("r2", r2);
8026535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8036535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8043deb3ec6SMatthias Ringwald }
8053deb3ec6SMatthias Ringwald 
806fbe050beSMatthias Ringwald 
8073deb3ec6SMatthias Ringwald // decide on stk generation based on
8083deb3ec6SMatthias Ringwald // - pairing request
8093deb3ec6SMatthias Ringwald // - io capabilities
8103deb3ec6SMatthias Ringwald // - OOB data availability
8113deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8123deb3ec6SMatthias Ringwald 
8138334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8148334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8158334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8168334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8178334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8188334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8198334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8208334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8218334d3d8SMatthias Ringwald     };
8228334d3d8SMatthias Ringwald 
8238334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8248334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8258334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8278334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8288334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8298334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8308334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8318334d3d8SMatthias Ringwald     };
8328334d3d8SMatthias Ringwald #endif
8338334d3d8SMatthias Ringwald 
8343deb3ec6SMatthias Ringwald     // default: just works
8353deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8363deb3ec6SMatthias Ringwald 
83727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83827c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83927c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8404ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84127c32905SMatthias Ringwald #else
84227c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84327c32905SMatthias Ringwald #endif
84498d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84527c32905SMatthias Ringwald 
84665a9a04eSMatthias Ringwald 
84765a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8481979f09cSMatthias Ringwald     bool use_oob;
84965a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85065a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85165a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8521979f09cSMatthias 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;
85365a9a04eSMatthias Ringwald     } else {
85465a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85565a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8561979f09cSMatthias 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;
85765a9a04eSMatthias Ringwald     }
85865a9a04eSMatthias Ringwald     if (use_oob){
85965a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86065a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86165a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86265a9a04eSMatthias Ringwald         return;
86365a9a04eSMatthias Ringwald     }
86465a9a04eSMatthias Ringwald 
86527c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86627c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86727c32905SMatthias Ringwald     // model shall be used.
8684ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8694ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87027c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87127c32905SMatthias Ringwald         return;
87227c32905SMatthias Ringwald     }
87327c32905SMatthias Ringwald 
8743deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8753deb3ec6SMatthias Ringwald     sm_reset_tk();
8763deb3ec6SMatthias Ringwald 
8773deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8788da2e96dSMatthias 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)){
8793deb3ec6SMatthias Ringwald         return;
8803deb3ec6SMatthias Ringwald     }
8813deb3ec6SMatthias Ringwald 
8823deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8833deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88427c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88527c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88627c32905SMatthias Ringwald 
88727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
888c6b7cbd9SMatthias Ringwald     // table not define by default
88927c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89027c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89127c32905SMatthias Ringwald     }
89227c32905SMatthias Ringwald #endif
89327c32905SMatthias 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)];
89427c32905SMatthias Ringwald 
8953deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8961ad129beSMatthias 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);
8973deb3ec6SMatthias Ringwald }
8983deb3ec6SMatthias Ringwald 
8993deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9003deb3ec6SMatthias Ringwald     int flags = 0;
9013deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9023deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9033deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9043deb3ec6SMatthias Ringwald     }
9053deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9073deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9083deb3ec6SMatthias Ringwald     }
9093deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     return flags;
9133deb3ec6SMatthias Ringwald }
9143deb3ec6SMatthias Ringwald 
9159a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9163deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9179a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9189a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
919715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9209790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
921715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9229790be5fSMatthias Ringwald #endif
9233deb3ec6SMatthias Ringwald }
9243deb3ec6SMatthias Ringwald 
9253deb3ec6SMatthias Ringwald // CSRK Key Lookup
9263deb3ec6SMatthias Ringwald 
9273deb3ec6SMatthias Ringwald 
9283deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9293deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9303deb3ec6SMatthias Ringwald }
9313deb3ec6SMatthias Ringwald 
932711e6c80SMatthias 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){
9336535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9343deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9353deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9363deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9373deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
938711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9393deb3ec6SMatthias Ringwald }
9403deb3ec6SMatthias Ringwald 
9413deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9423deb3ec6SMatthias Ringwald     // check if already in list
943665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9443deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
945665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
946665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
947665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9483deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9493deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9503deb3ec6SMatthias Ringwald         // already in list
9513deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9523deb3ec6SMatthias Ringwald     }
9533deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9543deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9553deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9566535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
957665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
95870b44dd4SMatthias Ringwald     sm_trigger_run();
9593deb3ec6SMatthias Ringwald     return 0;
9603deb3ec6SMatthias Ringwald }
9613deb3ec6SMatthias Ringwald 
962d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
963d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
964514d35fcSMatthias Ringwald 
965d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
966d1a1f6a4SMatthias Ringwald     UNUSED(arg);
967d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
968d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
96970b44dd4SMatthias Ringwald     sm_trigger_run();
9703deb3ec6SMatthias Ringwald }
971514d35fcSMatthias Ringwald 
9724dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9734ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9743deb3ec6SMatthias Ringwald }
9756d80b495SMatthias Ringwald #endif
9763deb3ec6SMatthias Ringwald 
9776d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
978514d35fcSMatthias Ringwald // generic cmac calculation
979d1a1f6a4SMatthias 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)){
980d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
981d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
982d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9833deb3ec6SMatthias Ringwald }
9847a766ebfSMatthias Ringwald #endif
9853deb3ec6SMatthias Ringwald 
986514d35fcSMatthias Ringwald // cmac for ATT Message signing
9877a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
988d1a1f6a4SMatthias Ringwald 
989d1a1f6a4SMatthias 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)){
990d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
991d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
992d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
993d1a1f6a4SMatthias Ringwald }
994d1a1f6a4SMatthias Ringwald 
9954dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
996d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
997d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
9984dfd504aSMatthias Ringwald         return 0;
9994dfd504aSMatthias Ringwald     }
10004dfd504aSMatthias Ringwald 
1001d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10024dfd504aSMatthias Ringwald 
1003d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10044dfd504aSMatthias Ringwald     if (offset < 3){
1005d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10064dfd504aSMatthias Ringwald     }
1007d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10084dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1009d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10104dfd504aSMatthias Ringwald     }
1011d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10124dfd504aSMatthias Ringwald }
10134dfd504aSMatthias Ringwald 
10144dfd504aSMatthias 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)){
1015514d35fcSMatthias Ringwald     // ATT Message Signing
1016d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1017d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1018d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1019514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1020d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1021d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1022d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10233deb3ec6SMatthias Ringwald }
10247a766ebfSMatthias Ringwald #endif
10253deb3ec6SMatthias Ringwald 
10263deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1027446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10283deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1029d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10303deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10313deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10333deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10345611a760SMatthias 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);
10353deb3ec6SMatthias Ringwald             } else {
1036c9b8fdd9SMatthias 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));
10373deb3ec6SMatthias Ringwald             }
10383deb3ec6SMatthias Ringwald             break;
10393deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
104042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1041c9b8fdd9SMatthias 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));
10423deb3ec6SMatthias Ringwald             } else {
10433deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10445611a760SMatthias 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);
10453deb3ec6SMatthias Ringwald             }
10463deb3ec6SMatthias Ringwald             break;
104747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10483deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10495611a760SMatthias 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);
10503deb3ec6SMatthias Ringwald             break;
105147fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1052446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1053c8c46d51SMatthias 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));
105427c32905SMatthias Ringwald             break;
10553deb3ec6SMatthias Ringwald         case JUST_WORKS:
10563deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10575611a760SMatthias 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);
10583deb3ec6SMatthias Ringwald             break;
10593deb3ec6SMatthias Ringwald         case OOB:
10603deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10613deb3ec6SMatthias Ringwald             break;
10627bbeb3adSMilanka Ringwald         default:
10637bbeb3adSMilanka Ringwald             btstack_assert(false);
10647bbeb3adSMilanka Ringwald             break;
10653deb3ec6SMatthias Ringwald     }
10663deb3ec6SMatthias Ringwald }
10673deb3ec6SMatthias Ringwald 
10683deb3ec6SMatthias Ringwald static int sm_key_distribution_all_received(sm_connection_t * sm_conn){
1069b2296177SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, bution_expected_set);
1070b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10713deb3ec6SMatthias Ringwald }
10723deb3ec6SMatthias Ringwald 
1073711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10747149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10753deb3ec6SMatthias Ringwald         sm_timeout_stop();
10767149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1077711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1078c085d9ffSMatthias Ringwald 
1079c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1080c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1081c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1082c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1083c085d9ffSMatthias Ringwald         }
1084c085d9ffSMatthias Ringwald #endif
10853deb3ec6SMatthias Ringwald     }
10863deb3ec6SMatthias Ringwald }
10873deb3ec6SMatthias Ringwald 
10887d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
10891dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
10900ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
10911dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
10921dca9d8aSMatthias Ringwald }
10931dca9d8aSMatthias Ringwald 
10943deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1095bb09604fSMatthias Ringwald 
1096bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
10973deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1098bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
10993deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1100bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1101bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1102bb09604fSMatthias Ringwald #endif
11037ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11047ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11057ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11067ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11077ece0eaaSMatthias Ringwald         }
11087ece0eaaSMatthias Ringwald #endif
11093deb3ec6SMatthias Ringwald     }
11103deb3ec6SMatthias Ringwald     return flags;
11113deb3ec6SMatthias Ringwald }
11123deb3ec6SMatthias Ringwald 
1113d7471931SMatthias Ringwald static void sm_reset_setup(void){
11143deb3ec6SMatthias Ringwald     // fill in sm setup
1115901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1116dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
11173deb3ec6SMatthias Ringwald     sm_reset_tk();
1118d7471931SMatthias Ringwald }
1119d7471931SMatthias Ringwald 
1120d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1121d7471931SMatthias Ringwald 
1122d7471931SMatthias Ringwald     // fill in sm setup
11233deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11246535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11253deb3ec6SMatthias Ringwald 
1126a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
1127a680ba6bSMatthias Ringwald     setup->sm_have_oob_data = 0;
11289305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1129a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11303deb3ec6SMatthias Ringwald     }
11313deb3ec6SMatthias Ringwald 
1132a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1133a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11344acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11354acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1136a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11379305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11384acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1139a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1140a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1141a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1142a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11434acf7b7bSMatthias Ringwald                     setup->sm_ra);
11444acf7b7bSMatthias Ringwald             } else {
11454acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11464acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11474acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11484acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11494acf7b7bSMatthias Ringwald                     setup->sm_rb);
11504acf7b7bSMatthias Ringwald             }
1151a680ba6bSMatthias Ringwald         } else {
1152a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1153a680ba6bSMatthias Ringwald         }
1154a680ba6bSMatthias Ringwald     }
1155a680ba6bSMatthias Ringwald #endif
1156a680ba6bSMatthias Ringwald 
11573deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
115842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11593deb3ec6SMatthias Ringwald         // slave
11603deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11613deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1162d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11636535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1164d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11653deb3ec6SMatthias Ringwald     } else {
11663deb3ec6SMatthias Ringwald         // master
11673deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11683deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1169d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11706535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1171d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11723deb3ec6SMatthias Ringwald 
11733deb3ec6SMatthias Ringwald         int key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11741ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11751ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11763deb3ec6SMatthias Ringwald     }
11773deb3ec6SMatthias Ringwald 
117857132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
11792c041b42SMatthias Ringwald     uint8_t max_encryptinon_key_size = sm_max_encryption_key_size;
11802c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11812c041b42SMatthias Ringwald     // enable SC for SC only mode
11822c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11832c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
11842c041b42SMatthias Ringwald         max_encryptinon_key_size = 16;
11852c041b42SMatthias Ringwald     }
11862c041b42SMatthias Ringwald #endif
118757132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
118857132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
118957132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
119057132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
119157132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
119257132f12SMatthias Ringwald 	}
119357132f12SMatthias Ringwald #endif
11941ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1195a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1196df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
11972c041b42SMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryptinon_key_size);
11983deb3ec6SMatthias Ringwald }
11993deb3ec6SMatthias Ringwald 
12003deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12013deb3ec6SMatthias Ringwald 
12023deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12039a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12049a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
120542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
120652f9cf63SMatthias Ringwald         // slave / responder
12073deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12089a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12099a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12103deb3ec6SMatthias Ringwald     } else {
12113deb3ec6SMatthias Ringwald         // master / initiator
12123deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12139a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12149a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12153deb3ec6SMatthias Ringwald     }
12163deb3ec6SMatthias Ringwald 
12173deb3ec6SMatthias Ringwald     // check key size
12182c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12192c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12202c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12212c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12222c041b42SMatthias Ringwald     }
12232c041b42SMatthias Ringwald #endif
12241ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12254ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12263deb3ec6SMatthias Ringwald 
1227eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12283deb3ec6SMatthias Ringwald     sm_setup_tk();
12293deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12303deb3ec6SMatthias Ringwald 
12313deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12323deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12333deb3ec6SMatthias Ringwald 
1234eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12352c041b42SMatthias Ringwald     // Check LE SC Only mode
12363cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12373cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12383cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12393cdbe9dbSMatthias Ringwald     }
12403cdbe9dbSMatthias Ringwald 
12419a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1242eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12439a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12449a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1245eddc894fSMatthias Ringwald     }
1246eddc894fSMatthias Ringwald #endif
1247eddc894fSMatthias Ringwald 
124852f9cf63SMatthias Ringwald     // identical to responder
12499a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
125052f9cf63SMatthias Ringwald 
12513deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1252c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12533deb3ec6SMatthias Ringwald 
12543deb3ec6SMatthias Ringwald     return 0;
12553deb3ec6SMatthias Ringwald }
12563deb3ec6SMatthias Ringwald 
12573deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12583deb3ec6SMatthias Ringwald 
12593deb3ec6SMatthias Ringwald     // cache and reset context
12603deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12613deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12623deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12633deb3ec6SMatthias Ringwald 
12643deb3ec6SMatthias Ringwald     // reset context
12653deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12663deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12673deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1268711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1271d2e90122SMatthias Ringwald     sm_key_t ltk;
12721979f09cSMatthias Ringwald     bool have_ltk;
12736c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12741979f09cSMatthias Ringwald     bool trigger_pairing;
127542134bc6SMatthias Ringwald #endif
12763deb3ec6SMatthias Ringwald     switch (mode){
12773deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12783deb3ec6SMatthias Ringwald             break;
12793deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12803deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1281711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12826c44b759SMatthias Ringwald 
12836c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12846c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12856c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12866c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12876c44b759SMatthias Ringwald 
12883deb3ec6SMatthias Ringwald             switch (event){
1289a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
12903deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
12913deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1292a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
12936c44b759SMatthias Ringwald 
12946c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
12956c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
12966c44b759SMatthias Ringwald 
12976c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
12986c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1299212d735eSMatthias Ringwald                         // IRK required before, continue
13006c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13016c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13026c39055aSMatthias Ringwald                             break;
13036c39055aSMatthias Ringwald                         }
1304212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1305212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1306212d735eSMatthias Ringwald                             break;
1307212d735eSMatthias Ringwald                         }
13087af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13097af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13106c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13117af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13127af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13136c44b759SMatthias Ringwald #endif
13147af5dcd5SMatthias Ringwald 
13157af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13161979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13177af5dcd5SMatthias Ringwald 
13187af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13197af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13207af5dcd5SMatthias Ringwald                             if (have_ltk){
13217af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13227af5dcd5SMatthias Ringwald                             } else {
13237af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13247af5dcd5SMatthias Ringwald                             }
13257af5dcd5SMatthias Ringwald                             sm_trigger_run();
13266c44b759SMatthias Ringwald                         }
13276c44b759SMatthias Ringwald #endif
13286c44b759SMatthias Ringwald                     } else {
13296c44b759SMatthias Ringwald 
133042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13316c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13326c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13336c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13341979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13353deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
133609ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
133732bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1338c245ca32SMatthias Ringwald 
1339d4af1595SMatthias Ringwald                         if (have_ltk){
13406a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1341b187cc61SMatthias Ringwald                             trigger_reencryption = true;
134232bc5d65SMatthias Ringwald #else
134332bc5d65SMatthias Ringwald                             if (trigger_pairing){
134432bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
134532bc5d65SMatthias Ringwald                             } else {
134632bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
134732bc5d65SMatthias Ringwald                             }
134832bc5d65SMatthias Ringwald #endif
134932bc5d65SMatthias Ringwald                         }
135032bc5d65SMatthias Ringwald 
135132bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13526c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13535567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1354d4af1595SMatthias Ringwald                             break;
1355d4af1595SMatthias Ringwald                         }
13566c44b759SMatthias Ringwald 
13576c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13586c44b759SMatthias Ringwald                         if (trigger_pairing){
13593deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1360d4af1595SMatthias Ringwald                             break;
13613deb3ec6SMatthias Ringwald                         }
136242134bc6SMatthias Ringwald #endif
1363298ab52bSMatthias Ringwald                     }
13643deb3ec6SMatthias Ringwald                     break;
13653deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13663deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13676c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13687af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13696c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13706c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13716c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13726c39055aSMatthias Ringwald                         }
13737af5dcd5SMatthias Ringwald                         // send security request if requested
13747af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13757af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13767af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13777af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13787af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13797af5dcd5SMatthias Ringwald                         }
13806c39055aSMatthias Ringwald                         break;
13817af5dcd5SMatthias Ringwald #endif
13826c39055aSMatthias Ringwald                     }
138342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
138409ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13853deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
138609ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13873deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
138842134bc6SMatthias Ringwald #endif
13893deb3ec6SMatthias Ringwald                     break;
13907bbeb3adSMilanka Ringwald 
13917bbeb3adSMilanka Ringwald                 default:
13927bbeb3adSMilanka Ringwald                     btstack_assert(false);
13937bbeb3adSMilanka Ringwald                     break;
13943deb3ec6SMatthias Ringwald             }
13953deb3ec6SMatthias Ringwald             break;
13963deb3ec6SMatthias Ringwald         default:
13973deb3ec6SMatthias Ringwald             break;
13983deb3ec6SMatthias Ringwald     }
13993deb3ec6SMatthias Ringwald 
14003deb3ec6SMatthias Ringwald     switch (event){
1401a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1402711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14033deb3ec6SMatthias Ringwald             break;
14043deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1405711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14063deb3ec6SMatthias Ringwald             break;
14077bbeb3adSMilanka Ringwald         default:
14087bbeb3adSMilanka Ringwald             btstack_assert(false);
14097bbeb3adSMilanka Ringwald             break;
14103deb3ec6SMatthias Ringwald     }
14113deb3ec6SMatthias Ringwald }
14123deb3ec6SMatthias Ringwald 
14133deb3ec6SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
14143deb3ec6SMatthias Ringwald 
14153deb3ec6SMatthias Ringwald     int le_db_index = -1;
14163deb3ec6SMatthias Ringwald 
141727ef8bc8SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
14181979f09cSMatthias Ringwald     bool bonding_enabed = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
141927ef8bc8SMatthias Ringwald                          & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
14204ea43905SMatthias Ringwald                          & SM_AUTHREQ_BONDING ) != 0u;
142127ef8bc8SMatthias Ringwald 
142227ef8bc8SMatthias Ringwald     if (bonding_enabed){
142327ef8bc8SMatthias Ringwald 
14243deb3ec6SMatthias Ringwald         // lookup device based on IRK
14253deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14263deb3ec6SMatthias Ringwald             int i;
1427092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14283deb3ec6SMatthias Ringwald                 sm_key_t irk;
14293deb3ec6SMatthias Ringwald                 bd_addr_t address;
1430c7e2c1a5SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14313deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, irk);
1432adf5eaa9SMatthias Ringwald                 // skip unused entries
1433c7e2c1a5SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1434c7e2c1a5SMatthias Ringwald                 // compare IRK
1435c7e2c1a5SMatthias Ringwald                 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1436c7e2c1a5SMatthias Ringwald 
14373deb3ec6SMatthias Ringwald                 log_info("sm: device found for IRK, updating");
14383deb3ec6SMatthias Ringwald                 le_db_index = i;
14393deb3ec6SMatthias Ringwald                 break;
14403deb3ec6SMatthias Ringwald             }
1441c7e2c1a5SMatthias Ringwald         } else {
1442c7e2c1a5SMatthias Ringwald             // assert IRK is set to zero
1443c7e2c1a5SMatthias Ringwald             memset(setup->sm_peer_irk, 0, 16);
14443deb3ec6SMatthias Ringwald         }
14453deb3ec6SMatthias Ringwald 
14463deb3ec6SMatthias Ringwald         // if not found, lookup via public address if possible
14473deb3ec6SMatthias Ringwald         log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1448c1ab6cc1SMatthias Ringwald         if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14493deb3ec6SMatthias Ringwald             int i;
1450092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14513deb3ec6SMatthias Ringwald                 bd_addr_t address;
1452adf5eaa9SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14533deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, NULL);
1454adf5eaa9SMatthias Ringwald                 // skip unused entries
1455adf5eaa9SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14563deb3ec6SMatthias Ringwald                 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14575df9dc78SMatthias Ringwald                 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14583deb3ec6SMatthias Ringwald                     log_info("sm: device found for public address, updating");
14593deb3ec6SMatthias Ringwald                     le_db_index = i;
14603deb3ec6SMatthias Ringwald                     break;
14613deb3ec6SMatthias Ringwald                 }
14623deb3ec6SMatthias Ringwald             }
14633deb3ec6SMatthias Ringwald         }
14643deb3ec6SMatthias Ringwald 
14653deb3ec6SMatthias Ringwald         // if not found, add to db
146602b02cffSMatthias Ringwald         bool new_to_le_device_db = false;
14673deb3ec6SMatthias Ringwald         if (le_db_index < 0) {
14683deb3ec6SMatthias Ringwald             le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
146902b02cffSMatthias Ringwald 			new_to_le_device_db = true;
14703deb3ec6SMatthias Ringwald         }
14713deb3ec6SMatthias Ringwald 
14723deb3ec6SMatthias Ringwald         if (le_db_index >= 0){
14733deb3ec6SMatthias Ringwald 
147402b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
147502b02cffSMatthias Ringwald         	if (!new_to_le_device_db){
147602b02cffSMatthias Ringwald 				hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
147702b02cffSMatthias Ringwald         	}
147802b02cffSMatthias Ringwald 			hci_load_le_device_db_entry_into_resolving_list(le_db_index);
147902b02cffSMatthias Ringwald #else
148002b02cffSMatthias Ringwald 			UNUSED(new_to_le_device_db);
148102b02cffSMatthias Ringwald #endif
148202b02cffSMatthias Ringwald 
148348163929SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index);
1484e1086030SMatthias Ringwald             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14857710ebd2SMatthias Ringwald             sm_conn->sm_le_db_index = le_db_index;
148648163929SMatthias Ringwald 
1487eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14883deb3ec6SMatthias Ringwald             // store local CSRK
1489715a43d1SMatthias Ringwald             setup->sm_le_device_index = le_db_index;
1490715a43d1SMatthias Ringwald             if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14913deb3ec6SMatthias Ringwald                 log_info("sm: store local CSRK");
14923deb3ec6SMatthias Ringwald                 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14933deb3ec6SMatthias Ringwald                 le_device_db_local_counter_set(le_db_index, 0);
14943deb3ec6SMatthias Ringwald             }
14953deb3ec6SMatthias Ringwald 
14963deb3ec6SMatthias Ringwald             // store remote CSRK
14973deb3ec6SMatthias Ringwald             if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14983deb3ec6SMatthias Ringwald                 log_info("sm: store remote CSRK");
14993deb3ec6SMatthias Ringwald                 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15003deb3ec6SMatthias Ringwald                 le_device_db_remote_counter_set(le_db_index, 0);
15013deb3ec6SMatthias Ringwald             }
1502eda85fbfSMatthias Ringwald #endif
150378f44163SMatthias Ringwald             // store encryption information for secure connections: LTK generated by ECDH
150478f44163SMatthias Ringwald             if (setup->sm_use_secure_connections){
1505e6343eb6SMatthias Ringwald                 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
150678f44163SMatthias Ringwald                 uint8_t zero_rand[8];
150778f44163SMatthias Ringwald                 memset(zero_rand, 0, 8);
150878f44163SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15093dc3a67dSMatthias Ringwald                     sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151078f44163SMatthias Ringwald             }
151178f44163SMatthias Ringwald 
1512e6343eb6SMatthias Ringwald             // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151378f44163SMatthias Ringwald             else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151478f44163SMatthias Ringwald                    && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1515e6343eb6SMatthias Ringwald                 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15163deb3ec6SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15173dc3a67dSMatthias Ringwald                     sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
151878f44163SMatthias Ringwald 
15193deb3ec6SMatthias Ringwald             }
15203deb3ec6SMatthias Ringwald         }
152127ef8bc8SMatthias Ringwald     } else {
152227ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
152327ef8bc8SMatthias Ringwald     }
15243deb3ec6SMatthias Ringwald }
15253deb3ec6SMatthias Ringwald 
1526688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1527f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1528688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1529688a08f9SMatthias Ringwald }
1530688a08f9SMatthias Ringwald 
1531688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1532688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1533688a08f9SMatthias Ringwald }
1534688a08f9SMatthias Ringwald 
15359af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1536688a08f9SMatthias Ringwald 
1537dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1538945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1539f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1540dc300847SMatthias Ringwald 
1541b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1542b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15431f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1544b90c4e75SMatthias Ringwald     } else {
1545b90c4e75SMatthias 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);
1546b35a3de2SMatthias Ringwald     }
1547b35a3de2SMatthias Ringwald }
1548b35a3de2SMatthias Ringwald 
1549688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
155042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1551688a08f9SMatthias Ringwald         // Responder
15524acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15534acf7b7bSMatthias Ringwald             // generate Nb
15544acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15556ca80073SMatthias 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);
15564acf7b7bSMatthias Ringwald         } else {
1557688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15584acf7b7bSMatthias Ringwald         }
1559688a08f9SMatthias Ringwald     } else {
1560688a08f9SMatthias Ringwald         // Initiator role
1561688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1562688a08f9SMatthias Ringwald             case JUST_WORKS:
1563dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1564688a08f9SMatthias Ringwald                 break;
1565688a08f9SMatthias Ringwald 
156647fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1567bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1568688a08f9SMatthias Ringwald                 break;
1569688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1570688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
157147fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15724ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1573b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1574688a08f9SMatthias Ringwald                 } else {
1575dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1576688a08f9SMatthias Ringwald                 }
1577688a08f9SMatthias Ringwald                 break;
1578688a08f9SMatthias Ringwald             case OOB:
157965a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1580688a08f9SMatthias Ringwald                 break;
15817bbeb3adSMilanka Ringwald             default:
15827bbeb3adSMilanka Ringwald                 btstack_assert(false);
15837bbeb3adSMilanka Ringwald                 break;
1584688a08f9SMatthias Ringwald         }
1585688a08f9SMatthias Ringwald     }
1586688a08f9SMatthias Ringwald }
1587688a08f9SMatthias Ringwald 
1588aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1589688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1590688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1591688a08f9SMatthias Ringwald 
1592c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1593c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1594a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1595c59d0c92SMatthias Ringwald         return;
1596c59d0c92SMatthias Ringwald     }
1597c59d0c92SMatthias Ringwald 
1598bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1599bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16006857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16012bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1602b4f65634SMatthias Ringwald #endif
1603bd57ffebSMatthias Ringwald 
1604bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1605aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16066535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1607bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1608aec94140SMatthias Ringwald             break;
1609688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1610688a08f9SMatthias Ringwald             // check
1611688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1612bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1613688a08f9SMatthias Ringwald                 break;
1614688a08f9SMatthias Ringwald             }
1615bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1616688a08f9SMatthias Ringwald             break;
1617901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1618901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1619901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1620901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1621901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1622019005a0SMatthias Ringwald             break;
1623019005a0SMatthias Ringwald         }
16240346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16256535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1626bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16270346c37cSMatthias Ringwald             break;
16280346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16296535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1630bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16310346c37cSMatthias Ringwald             break;
16320346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1633b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1634b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1635b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1636b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16376535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16386535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1639893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1640bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1641019005a0SMatthias Ringwald             break;
1642901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16436535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
164442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1645901c000fSMatthias Ringwald                 // responder
1646901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1647901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1648901c000fSMatthias Ringwald                 } else {
1649901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1650901c000fSMatthias Ringwald                 }
1651901c000fSMatthias Ringwald             } else {
1652901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1653901c000fSMatthias Ringwald             }
1654901c000fSMatthias Ringwald             break;
1655901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1656901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1657901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1658aec94140SMatthias Ringwald                 break;
1659aec94140SMatthias Ringwald             }
166042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1661901c000fSMatthias Ringwald                 // responder
1662901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1663901c000fSMatthias Ringwald             } else {
1664901c000fSMatthias Ringwald                 // initiator
1665901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1666bd57ffebSMatthias Ringwald             }
1667901c000fSMatthias Ringwald             break;
16686857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
166957132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16706535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
167157132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16722bacf595SMatthias Ringwald             break;
167357132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16742bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16752bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16762bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16778974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
167855160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16798974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16802bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16812bacf595SMatthias Ringwald             } else {
16822bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16832bacf595SMatthias Ringwald             }
16840ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16852bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16862bacf595SMatthias Ringwald             break;
1687bdb14b0eSMatthias Ringwald #endif
1688bd57ffebSMatthias Ringwald         default:
1689bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1690bd57ffebSMatthias Ringwald             break;
1691bd57ffebSMatthias Ringwald     }
169270b44dd4SMatthias Ringwald     sm_trigger_run();
1693aec94140SMatthias Ringwald }
1694aec94140SMatthias Ringwald 
1695688a08f9SMatthias 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){
1696dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1697aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
16986535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
16996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1700aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1701aec94140SMatthias Ringwald     log_info("f4 key");
1702aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1703aec94140SMatthias Ringwald     log_info("f4 message");
1704dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1705d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1706aec94140SMatthias Ringwald }
1707aec94140SMatthias Ringwald 
17080346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17090346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17100346c37cSMatthias Ringwald 
17110346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17128334d3d8SMatthias Ringwald 
17138334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17148334d3d8SMatthias Ringwald 
171540c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17160346c37cSMatthias Ringwald     // calculate salt for f5
17170346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17180346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17196535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1720d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17210346c37cSMatthias Ringwald }
17220346c37cSMatthias Ringwald 
17230346c37cSMatthias 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){
17240346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17250346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17260346c37cSMatthias Ringwald 
17270346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17280346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17296535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17306535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17316535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17326535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17336535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17346535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17350346c37cSMatthias Ringwald     log_info("f5 key");
17360346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17370346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17380346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1739d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17400346c37cSMatthias Ringwald }
17410346c37cSMatthias Ringwald 
17420346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17430346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17440346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17450346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17466535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17476535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
174842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17490346c37cSMatthias Ringwald         // responder
17500346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17510346c37cSMatthias Ringwald     } else {
17520346c37cSMatthias Ringwald         // initiator
17530346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17540346c37cSMatthias Ringwald     }
17550346c37cSMatthias Ringwald }
17560346c37cSMatthias Ringwald 
17570346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17580346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17590346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17600346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17610346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17620346c37cSMatthias Ringwald     // 1..52 setup before
17630346c37cSMatthias Ringwald     log_info("f5 key");
17640346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17650346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17660346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1767d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17680346c37cSMatthias Ringwald }
1769f92edc8eSMatthias Ringwald 
17700346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17710346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17720346c37cSMatthias Ringwald }
17730346c37cSMatthias Ringwald 
177431f061fbSMatthias 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){
17756535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17766535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17776535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17786535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
17796535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
17806535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
178131f061fbSMatthias Ringwald }
178231f061fbSMatthias Ringwald 
178331f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
178431f061fbSMatthias Ringwald     const uint16_t message_len = 65;
178531f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1786dc300847SMatthias Ringwald     log_info("f6 key");
1787dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1788dc300847SMatthias Ringwald     log_info("f6 message");
1789dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1790d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1791dc300847SMatthias Ringwald }
1792dc300847SMatthias Ringwald 
1793f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1794f92edc8eSMatthias Ringwald // - U is 256 bits
1795f92edc8eSMatthias Ringwald // - V is 256 bits
1796f92edc8eSMatthias Ringwald // - X is 128 bits
1797f92edc8eSMatthias Ringwald // - Y is 128 bits
1798bd57ffebSMatthias 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){
1799bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1800bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18026535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18036535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1804f92edc8eSMatthias Ringwald     log_info("g2 key");
1805f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1806f92edc8eSMatthias Ringwald     log_info("g2 message");
18072bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1808d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1809f92edc8eSMatthias Ringwald }
1810f92edc8eSMatthias Ringwald 
1811b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1812f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
181342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1814f92edc8eSMatthias Ringwald         // responder
1815fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1816f92edc8eSMatthias Ringwald     } else {
1817f92edc8eSMatthias Ringwald         // initiator
1818fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1819f92edc8eSMatthias Ringwald     }
1820f92edc8eSMatthias Ringwald }
1821f92edc8eSMatthias Ringwald 
1822945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18239af0f475SMatthias Ringwald     uint8_t z = 0;
182440c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18259af0f475SMatthias Ringwald         // some form of passkey
18269af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18274ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18289af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18299af0f475SMatthias Ringwald     }
1830fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18319af0f475SMatthias Ringwald }
1832688a08f9SMatthias Ringwald 
1833688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1834a680ba6bSMatthias Ringwald     // OOB
1835a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18364acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18374acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18384acf7b7bSMatthias Ringwald         } else {
18394acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18404acf7b7bSMatthias Ringwald         }
1841a680ba6bSMatthias Ringwald         return;
1842a680ba6bSMatthias Ringwald     }
1843a680ba6bSMatthias Ringwald 
1844688a08f9SMatthias Ringwald     uint8_t z = 0;
184540c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1846688a08f9SMatthias Ringwald         // some form of passkey
1847688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1848688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18494ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1850688a08f9SMatthias Ringwald     }
1851fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1852688a08f9SMatthias Ringwald }
1853688a08f9SMatthias Ringwald 
18540346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1855505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18563cf37b8cSMatthias Ringwald 
18573cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18583cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18593cf37b8cSMatthias Ringwald         return;
18603cf37b8cSMatthias Ringwald     } else {
18613cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18623cf37b8cSMatthias Ringwald     }
1863d1a1f6a4SMatthias Ringwald }
18643cf37b8cSMatthias Ringwald 
1865d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1866f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1867f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1868f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1869f3582630SMatthias Ringwald 
1870d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1871d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1872d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1873d1a1f6a4SMatthias Ringwald     // trigger next step
1874d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1875d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1876d1a1f6a4SMatthias Ringwald     }
187770b44dd4SMatthias Ringwald     sm_trigger_run();
1878dc300847SMatthias Ringwald }
1879dc300847SMatthias Ringwald 
1880dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1881dc300847SMatthias Ringwald     // calculate DHKCheck
1882dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1883dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1884dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18856535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18866535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1887dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1888dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1889dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1890dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1891dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1892dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1893dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1894dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
189542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1896dc300847SMatthias Ringwald         // responder
189731f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
189831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1899dc300847SMatthias Ringwald     } else {
1900dc300847SMatthias Ringwald         // initiator
190131f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
190231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1903dc300847SMatthias Ringwald     }
1904dc300847SMatthias Ringwald }
1905dc300847SMatthias Ringwald 
1906019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1907019005a0SMatthias Ringwald     // validate E = f6()
1908019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1909019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1910019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19116535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19126535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1913019005a0SMatthias Ringwald 
1914019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1915019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1916019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1917019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1918019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1919019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1920019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1921019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
192242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1923019005a0SMatthias Ringwald         // responder
192431f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1926019005a0SMatthias Ringwald     } else {
1927019005a0SMatthias Ringwald         // initiator
192831f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
192931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1930019005a0SMatthias Ringwald     }
1931019005a0SMatthias Ringwald }
19322bacf595SMatthias Ringwald 
193355c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19342bacf595SMatthias Ringwald 
19352bacf595SMatthias Ringwald //
19362bacf595SMatthias Ringwald // Link Key Conversion Function h6
19372bacf595SMatthias Ringwald //
193857132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19392bacf595SMatthias Ringwald // - W is 128 bits
19402bacf595SMatthias Ringwald // - keyID is 32 bits
19412bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19422bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19432bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19442bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19452bacf595SMatthias Ringwald     log_info("h6 key");
19462bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19472bacf595SMatthias Ringwald     log_info("h6 message");
19482bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1949d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19502bacf595SMatthias Ringwald }
195157132f12SMatthias Ringwald //
195257132f12SMatthias Ringwald // Link Key Conversion Function h7
195357132f12SMatthias Ringwald //
195457132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
195557132f12SMatthias Ringwald // - SALT is 128 bits
195657132f12SMatthias Ringwald // - W    is 128 bits
195757132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
195857132f12SMatthias Ringwald 	const uint16_t message_len = 16;
195957132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
196057132f12SMatthias Ringwald 	log_info("h7 key");
196157132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
196257132f12SMatthias Ringwald 	log_info("h7 message");
196357132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
196457132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
196557132f12SMatthias Ringwald }
19662bacf595SMatthias Ringwald 
1967b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1968b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1969b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1970b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
197157132f12SMatthias Ringwald 
1972*c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1973b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19742bacf595SMatthias Ringwald }
19752bacf595SMatthias Ringwald 
19762bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
19772bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
19782bacf595SMatthias Ringwald }
19792bacf595SMatthias Ringwald 
1980*c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
198157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
198257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
198357132f12SMatthias Ringwald }
19849af0f475SMatthias Ringwald #endif
19859af0f475SMatthias Ringwald 
198655c62cf5SMatthias Ringwald #endif
198755c62cf5SMatthias Ringwald 
1988613da3deSMatthias Ringwald // key management legacy connections:
1989613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
1990613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
1991613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
1992613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
1993613da3deSMatthias Ringwald 
1994613da3deSMatthias Ringwald // key management secure connections:
1995613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
1996613da3deSMatthias Ringwald 
199742134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
19985829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
19995829ebe2SMatthias Ringwald     int encryption_key_size;
20005829ebe2SMatthias Ringwald     int authenticated;
20015829ebe2SMatthias Ringwald     int authorized;
20023dc3a67dSMatthias Ringwald     int secure_connection;
20035829ebe2SMatthias Ringwald 
20045829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20055829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20063dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20073dc3a67dSMatthias 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);
20085829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20095829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20105829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20113dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20125829ebe2SMatthias Ringwald }
201342134bc6SMatthias Ringwald #endif
2014bd57ffebSMatthias Ringwald 
201542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
201659066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20176535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
201859066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
201959066796SMatthias Ringwald     // re-establish used key encryption size
202059066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20214ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
202259066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20234ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20243dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20253dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
202659066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
202759066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
202859066796SMatthias Ringwald }
202942134bc6SMatthias Ringwald #endif
203059066796SMatthias Ringwald 
20313deb3ec6SMatthias Ringwald // distributed key generation
2032d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20333deb3ec6SMatthias Ringwald     switch (dkg_state){
20343deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20353deb3ec6SMatthias Ringwald             // already busy?
20363deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2037d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20383deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2039d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2040d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2041d1a1f6a4SMatthias 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);
2042d7f1c72eSMatthias Ringwald                 return true;
20433deb3ec6SMatthias Ringwald             }
20443deb3ec6SMatthias Ringwald             break;
20453deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20463deb3ec6SMatthias Ringwald             // already busy?
20473deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2048d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20493deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2050d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2051d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2052d1a1f6a4SMatthias 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);
2053d7f1c72eSMatthias Ringwald                 return true;
20543deb3ec6SMatthias Ringwald             }
20553deb3ec6SMatthias Ringwald             break;
20563deb3ec6SMatthias Ringwald         default:
20573deb3ec6SMatthias Ringwald             break;
20583deb3ec6SMatthias Ringwald     }
2059d7f1c72eSMatthias Ringwald     return false;
2060d7f1c72eSMatthias Ringwald }
20613deb3ec6SMatthias Ringwald 
20623deb3ec6SMatthias Ringwald // random address updates
2063d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
20643deb3ec6SMatthias Ringwald     switch (rau_state){
2065fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2066fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
20675b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2068d7f1c72eSMatthias Ringwald             return true;
20693deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
20703deb3ec6SMatthias Ringwald             // already busy?
20713deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2072d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2073d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2074d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2075d7f1c72eSMatthias Ringwald                 return true;
20763deb3ec6SMatthias Ringwald             }
20773deb3ec6SMatthias Ringwald             break;
20783deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
20793deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
20803deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
20813deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2082d7f1c72eSMatthias Ringwald             return true;
20833deb3ec6SMatthias Ringwald         default:
20843deb3ec6SMatthias Ringwald             break;
20853deb3ec6SMatthias Ringwald     }
2086d7f1c72eSMatthias Ringwald     return false;
2087d7f1c72eSMatthias Ringwald }
20883deb3ec6SMatthias Ringwald 
20893deb3ec6SMatthias Ringwald // CSRK Lookup
2090d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2091d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2092d7f1c72eSMatthias Ringwald 
20933deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
20943deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
20953deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2096665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2097665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
20983deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
20993deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21003deb3ec6SMatthias Ringwald                 // and start lookup
21013deb3ec6SMatthias 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);
21023deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21033deb3ec6SMatthias Ringwald                 break;
21043deb3ec6SMatthias Ringwald             }
21053deb3ec6SMatthias Ringwald         }
21063deb3ec6SMatthias Ringwald     }
21073deb3ec6SMatthias Ringwald 
21083deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21093deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2110665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21113deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2112665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21133deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21143deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21153deb3ec6SMatthias Ringwald         }
21163deb3ec6SMatthias Ringwald     }
21173deb3ec6SMatthias Ringwald 
21183deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21193deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2120092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2121092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2122adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21233deb3ec6SMatthias Ringwald             bd_addr_t addr;
21243deb3ec6SMatthias Ringwald             sm_key_t irk;
21253deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21263deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21273deb3ec6SMatthias Ringwald 
2128adf5eaa9SMatthias Ringwald             // skip unused entries
2129adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2130adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2131adf5eaa9SMatthias Ringwald                 continue;
2132adf5eaa9SMatthias Ringwald             }
2133adf5eaa9SMatthias Ringwald 
21345df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21353deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2136a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21373deb3ec6SMatthias Ringwald                 break;
21383deb3ec6SMatthias Ringwald             }
21393deb3ec6SMatthias Ringwald 
2140a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2141a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21423deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21433deb3ec6SMatthias Ringwald                 continue;
21443deb3ec6SMatthias Ringwald             }
21453deb3ec6SMatthias Ringwald 
21463deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21473deb3ec6SMatthias Ringwald 
21483deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21498314c363SMatthias Ringwald             log_info_key("IRK", irk);
21503deb3ec6SMatthias Ringwald 
21516535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2152d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21533deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2154d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2155d1a1f6a4SMatthias 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);
2156d7f1c72eSMatthias Ringwald             return true;
21573deb3ec6SMatthias Ringwald         }
21583deb3ec6SMatthias Ringwald 
2159092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
21603deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
21613deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
21623deb3ec6SMatthias Ringwald         }
21633deb3ec6SMatthias Ringwald     }
2164d7f1c72eSMatthias Ringwald     return false;
2165d7f1c72eSMatthias Ringwald }
21663deb3ec6SMatthias Ringwald 
2167d7f1c72eSMatthias Ringwald // SC OOB
2168d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2169c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2170c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2171c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2172c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2173c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2174c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2175d7f1c72eSMatthias Ringwald             return true;
2176c59d0c92SMatthias Ringwald         default:
2177c59d0c92SMatthias Ringwald             break;
2178c59d0c92SMatthias Ringwald     }
2179c59d0c92SMatthias Ringwald #endif
2180d7f1c72eSMatthias Ringwald     return false;
2181d7f1c72eSMatthias Ringwald }
2182275aafe8SMatthias Ringwald 
2183687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2184687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2185687a03c8SMatthias Ringwald }
2186687a03c8SMatthias Ringwald 
218741d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2188d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2189d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
219041d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2191e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
219241d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
219341d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
219441d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2195f4935286SMatthias Ringwald 
2196f4935286SMatthias Ringwald             // general
2197f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2198f4935286SMatthias Ringwald                 uint8_t buffer[2];
2199f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2200f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2201f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2202687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2203f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2204f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2205f4935286SMatthias Ringwald                 break;
2206f4935286SMatthias Ringwald             }
2207f4935286SMatthias Ringwald 
220841d32297SMatthias Ringwald             // responder side
220941d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
221041d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
221141d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2212d7f1c72eSMatthias Ringwald                 return true;
22134b8b5afeSMatthias Ringwald 
22144b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22154b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22164b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22174b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2218e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22194b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22204b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2221d7f1c72eSMatthias Ringwald                         return true;
22224b8b5afeSMatthias Ringwald                     default:
22234b8b5afeSMatthias Ringwald                         break;
22244b8b5afeSMatthias Ringwald                 }
22254b8b5afeSMatthias Ringwald                 break;
22264b8b5afeSMatthias Ringwald #endif
222741d32297SMatthias Ringwald             default:
222841d32297SMatthias Ringwald                 break;
222941d32297SMatthias Ringwald         }
223041d32297SMatthias Ringwald     }
2231d7f1c72eSMatthias Ringwald     return false;
2232d7f1c72eSMatthias Ringwald }
22333deb3ec6SMatthias Ringwald 
2234d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22353deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2236d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22373deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22387149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2239665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22403deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22413deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22421979f09cSMatthias Ringwald         bool done = true;
22433deb3ec6SMatthias Ringwald         int err;
224442134bc6SMatthias Ringwald         UNUSED(err);
224534b6528fSMatthias Ringwald 
224634b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
224734b6528fSMatthias Ringwald         // assert ec key is ready
2248505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2249178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2250178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
225134b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
225234b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
225334b6528fSMatthias Ringwald             }
225434b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
225534b6528fSMatthias Ringwald                 continue;
225634b6528fSMatthias Ringwald             }
225734b6528fSMatthias Ringwald         }
225834b6528fSMatthias Ringwald #endif
225934b6528fSMatthias Ringwald 
22603deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
226142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
22623deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
22633deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
226442134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2265549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
226606cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
226787014f74SMatthias Ringwald #endif
226887014f74SMatthias Ringwald #endif
226934c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
22705567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
227134c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2272549ad5d2SMatthias Ringwald #endif
227387014f74SMatthias Ringwald 				// just lock context
227487014f74SMatthias Ringwald 				break;
22753deb3ec6SMatthias Ringwald             default:
22761979f09cSMatthias Ringwald                 done = false;
22773deb3ec6SMatthias Ringwald                 break;
22783deb3ec6SMatthias Ringwald         }
22793deb3ec6SMatthias Ringwald         if (done){
22807149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
22817149bde5SMatthias 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);
22823deb3ec6SMatthias Ringwald         }
22833deb3ec6SMatthias Ringwald     }
2284d7f1c72eSMatthias Ringwald }
2285d7f1c72eSMatthias Ringwald 
2286403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2287403280b9SMatthias Ringwald     int i;
2288403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2289403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2290403280b9SMatthias Ringwald     uint8_t action = 0;
2291403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2292403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2293403280b9SMatthias Ringwald             bool clear_flag = true;
2294403280b9SMatthias Ringwald             switch (i){
2295403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2296403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2297403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2298403280b9SMatthias Ringwald                 default:
2299403280b9SMatthias Ringwald                     break;
2300403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2301403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2302403280b9SMatthias Ringwald                     num_actions--;
2303403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2304403280b9SMatthias Ringwald                     break;
2305403280b9SMatthias Ringwald             }
2306403280b9SMatthias Ringwald             if (clear_flag){
2307403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2308403280b9SMatthias Ringwald             }
2309403280b9SMatthias Ringwald             action = i;
2310403280b9SMatthias Ringwald             break;
2311403280b9SMatthias Ringwald         }
2312403280b9SMatthias Ringwald     }
2313403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2314403280b9SMatthias Ringwald 
2315403280b9SMatthias Ringwald     // send keypress notification
2316403280b9SMatthias Ringwald     uint8_t buffer[2];
2317403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2318403280b9SMatthias Ringwald     buffer[1] = action;
2319687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2320403280b9SMatthias Ringwald 
2321403280b9SMatthias Ringwald     // try
2322403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2323403280b9SMatthias Ringwald }
2324403280b9SMatthias Ringwald 
2325403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2326403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2327403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2328403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2329403280b9SMatthias Ringwald         uint8_t buffer[17];
2330403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2331403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2332687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2333403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2334403280b9SMatthias Ringwald         return;
2335403280b9SMatthias Ringwald     }
2336403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2337403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2338403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2339403280b9SMatthias Ringwald         uint8_t buffer[11];
2340403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2341403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2342403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2343687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2344403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2345403280b9SMatthias Ringwald         return;
2346403280b9SMatthias Ringwald     }
2347403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2348403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2349403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2350403280b9SMatthias Ringwald         uint8_t buffer[17];
2351403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2352403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2353687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2354403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2355403280b9SMatthias Ringwald         return;
2356403280b9SMatthias Ringwald     }
2357403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2358403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2359403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2360403280b9SMatthias Ringwald         bd_addr_t local_address;
2361403280b9SMatthias Ringwald         uint8_t buffer[8];
2362403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2363403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2364403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2365403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2366403280b9SMatthias Ringwald                 // public or static random
2367403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2368403280b9SMatthias Ringwald                 break;
2369403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2370403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2371403280b9SMatthias Ringwald                 // fallback to public
2372403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2373403280b9SMatthias Ringwald                 buffer[1] = 0;
2374403280b9SMatthias Ringwald                 break;
2375403280b9SMatthias Ringwald             default:
2376403280b9SMatthias Ringwald                 btstack_assert(false);
2377403280b9SMatthias Ringwald                 break;
2378403280b9SMatthias Ringwald         }
2379403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
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_SIGNING_IDENTIFICATION){
2385403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2386403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2387403280b9SMatthias Ringwald 
2388403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2389403280b9SMatthias Ringwald         // hack to reproduce test runs
2390403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2391403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2392403280b9SMatthias Ringwald                     }
2393403280b9SMatthias Ringwald 
2394403280b9SMatthias Ringwald                     // store local CSRK
2395403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2396403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2397403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2398403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2399403280b9SMatthias Ringwald                     }
2400403280b9SMatthias Ringwald #endif
2401403280b9SMatthias Ringwald 
2402403280b9SMatthias Ringwald         uint8_t buffer[17];
2403403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2404403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2405687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2406403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2407403280b9SMatthias Ringwald         return;
2408403280b9SMatthias Ringwald     }
2409403280b9SMatthias Ringwald     btstack_assert(false);
2410403280b9SMatthias Ringwald }
2411403280b9SMatthias Ringwald 
2412bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2413bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2414bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2415bbd73538SMatthias Ringwald     // - use secure connections
2416bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2417bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2418bbd73538SMatthias 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;
2419bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2420bbd73538SMatthias Ringwald     // - need identity address / public addr
2421bbd73538SMatthias 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);
2422bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2423bbd73538SMatthias 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)
2424bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2425bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2426bbd73538SMatthias 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.
2427bbd73538SMatthias Ringwald     uint8_t link_key[16];
2428bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2429bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2430bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2431bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2432bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2433bbd73538SMatthias Ringwald         return false;
2434bbd73538SMatthias Ringwald     }
2435bbd73538SMatthias Ringwald     // get started (all of the above are true)
2436bbd73538SMatthias Ringwald     return true;
2437bbd73538SMatthias Ringwald #else
2438bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2439bbd73538SMatthias Ringwald 	return false;
2440bbd73538SMatthias Ringwald #endif
2441bbd73538SMatthias Ringwald }
2442bbd73538SMatthias Ringwald 
24436f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24446f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24456f7422f1SMatthias 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;
24466f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24476f7422f1SMatthias Ringwald     } else {
24486f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24496f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24506f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24516f7422f1SMatthias Ringwald     }
24526f7422f1SMatthias Ringwald }
24536f7422f1SMatthias Ringwald 
2454af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2455af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2456af7ef9d1SMatthias 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;
2457af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2458af7ef9d1SMatthias Ringwald     } else {
2459af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2460af7ef9d1SMatthias Ringwald     }
2461af7ef9d1SMatthias Ringwald }
2462af7ef9d1SMatthias Ringwald 
2463d7f1c72eSMatthias Ringwald static void sm_run(void){
2464d7f1c72eSMatthias Ringwald 
2465d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2466d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2467d7f1c72eSMatthias Ringwald 
2468d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2469d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2470d7f1c72eSMatthias Ringwald 
2471d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2472d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2473d7f1c72eSMatthias Ringwald 
2474d7f1c72eSMatthias Ringwald     bool done;
2475d7f1c72eSMatthias Ringwald 
2476d7f1c72eSMatthias Ringwald     //
2477d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2478d7f1c72eSMatthias Ringwald     //
2479d7f1c72eSMatthias Ringwald 
2480d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2481d7f1c72eSMatthias Ringwald     if (done) return;
2482d7f1c72eSMatthias Ringwald 
2483d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2484d7f1c72eSMatthias Ringwald     if (done) return;
2485d7f1c72eSMatthias Ringwald 
2486d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2487d7f1c72eSMatthias Ringwald     if (done) return;
2488d7f1c72eSMatthias Ringwald 
2489d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2490d7f1c72eSMatthias Ringwald     if (done) return;
2491d7f1c72eSMatthias Ringwald 
2492d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2493d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2494d7f1c72eSMatthias Ringwald 
2495d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2496d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2497d7f1c72eSMatthias Ringwald     if (done) return;
2498d7f1c72eSMatthias Ringwald 
2499d7f1c72eSMatthias Ringwald     //
2500d7f1c72eSMatthias Ringwald     // active connection handling
2501d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2502d7f1c72eSMatthias Ringwald 
2503d7f1c72eSMatthias Ringwald     while (true) {
2504d7f1c72eSMatthias Ringwald 
2505d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2506d7f1c72eSMatthias Ringwald 
2507d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25083deb3ec6SMatthias Ringwald 
25093deb3ec6SMatthias Ringwald         //
25103deb3ec6SMatthias Ringwald         // active connection handling
25113deb3ec6SMatthias Ringwald         //
25123deb3ec6SMatthias Ringwald 
25133cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25143cf37b8cSMatthias Ringwald         if (!connection) {
25153cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25163cf37b8cSMatthias Ringwald             return;
25173cf37b8cSMatthias Ringwald         }
25183cf37b8cSMatthias Ringwald 
25193deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25207149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25217149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25227149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2523b170b20fSMatthias Ringwald             return;
2524b170b20fSMatthias Ringwald         }
25253deb3ec6SMatthias Ringwald 
25263d7fe1e9SMatthias Ringwald         // send keypress notifications
2527dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2528403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2529d7471931SMatthias Ringwald             return;
25303d7fe1e9SMatthias Ringwald         }
25313d7fe1e9SMatthias Ringwald 
25323deb3ec6SMatthias Ringwald         int key_distribution_flags;
253342134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2534b6afa23eSMatthias Ringwald 		int err;
2535b6afa23eSMatthias Ringwald 		UNUSED(err);
25369b75de03SMatthias Ringwald         bool have_ltk;
25379b75de03SMatthias Ringwald         uint8_t ltk[16];
25383deb3ec6SMatthias Ringwald 
25393deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2540dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2541dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2542dd4a08fbSMatthias Ringwald         }
25433deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25443deb3ec6SMatthias Ringwald 
2545f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2546aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2547aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2548aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2549aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2550aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2551aec94140SMatthias Ringwald                 break;
2552688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2553688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2554688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2555688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2556688a08f9SMatthias Ringwald                 break;
2557dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2558dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2559dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2560dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2561dc300847SMatthias Ringwald                 break;
2562019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2563b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2564019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
25650346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
25660346c37cSMatthias Ringwald                 break;
25670346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2568b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25690346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
25700346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
25710346c37cSMatthias Ringwald                 break;
25720346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2573b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25740346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
25750346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
25760346c37cSMatthias Ringwald                 break;
25770346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2578b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25790346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
25800346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2581019005a0SMatthias Ringwald                 break;
2582bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2583b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2584bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2585b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2586bd57ffebSMatthias Ringwald                 break;
25876857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
258857132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
25892bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
259057132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
2591*c82679c3SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
25922bacf595SMatthias Ringwald                 break;
259357132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
25942bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
259557132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
25962bacf595SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
25972bacf595SMatthias Ringwald                 break;
259857132f12SMatthias Ringwald 			case SM_SC_W2_CALCULATE_ILK_USING_H7:
259957132f12SMatthias Ringwald 				if (!sm_cmac_ready()) break;
260057132f12SMatthias Ringwald 				connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
2601*c82679c3SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
260257132f12SMatthias Ringwald 				break;
2603aec94140SMatthias Ringwald #endif
2604a756d52bSMatthias Ringwald #endif
260541d32297SMatthias Ringwald 
260642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26073deb3ec6SMatthias Ringwald             // initiator side
2608f32b7a88SMatthias Ringwald 
26095567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2610f32b7a88SMatthias Ringwald 				sm_reset_setup();
2611f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2612daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2613f32b7a88SMatthias Ringwald 
26143deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26159c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26165567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26173deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2618c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2619c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26203deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26213deb3ec6SMatthias Ringwald                 return;
26223deb3ec6SMatthias Ringwald             }
26233deb3ec6SMatthias Ringwald 
2624b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2625b26f445fSMatthias Ringwald 				sm_reset_setup();
2626b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2627b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2628d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2629b26f445fSMatthias Ringwald 
26301ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26313deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2632687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26333deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26343deb3ec6SMatthias Ringwald                 break;
263542134bc6SMatthias Ringwald #endif
26363deb3ec6SMatthias Ringwald 
263727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
263841d32297SMatthias Ringwald 
2639c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26401979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26411979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
264227c32905SMatthias Ringwald                 uint8_t buffer[65];
264327c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
264427c32905SMatthias Ringwald                 //
2645fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2646fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2647e53be891SMatthias Ringwald 
2648349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2649349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2650349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2651349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2652349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2653349d0adbSMatthias Ringwald                 }
2654349d0adbSMatthias Ringwald #endif
2655349d0adbSMatthias Ringwald 
265645a61d50SMatthias Ringwald                 // stk generation method
265745a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
265845a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
265945a61d50SMatthias Ringwald                     case JUST_WORKS:
266047fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
266142134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
266207036a04SMatthias Ringwald                             // responder
26631979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2664b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
266527c32905SMatthias Ringwald                         } else {
266607036a04SMatthias Ringwald                             // initiator
2667c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
266827c32905SMatthias Ringwald                         }
266945a61d50SMatthias Ringwald                         break;
267045a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
267145a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
267247fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
267307036a04SMatthias Ringwald                         // use random TK for display
26746535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
26756535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
267645a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
267707036a04SMatthias Ringwald 
267842134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
267945a61d50SMatthias Ringwald                             // responder
2680c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
268145a61d50SMatthias Ringwald                         } else {
268245a61d50SMatthias Ringwald                             // initiator
2683c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
268445a61d50SMatthias Ringwald                         }
26851979f09cSMatthias Ringwald                         trigger_user_response = true;
268645a61d50SMatthias Ringwald                         break;
268745a61d50SMatthias Ringwald                     case OOB:
268865a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
268965a9a04eSMatthias Ringwald                             // responder
269065a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
269165a9a04eSMatthias Ringwald                         } else {
269265a9a04eSMatthias Ringwald                             // initiator
269365a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
269465a9a04eSMatthias Ringwald                         }
269545a61d50SMatthias Ringwald                         break;
26967bbeb3adSMilanka Ringwald                     default:
26977bbeb3adSMilanka Ringwald                         btstack_assert(false);
26987bbeb3adSMilanka Ringwald                         break;
269945a61d50SMatthias Ringwald                 }
270045a61d50SMatthias Ringwald 
2701687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
270227c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2703644c6a1dSMatthias Ringwald 
2704b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2705644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2706644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2707644c6a1dSMatthias Ringwald                 }
2708b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2709b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2710b90c4e75SMatthias Ringwald                 }
271127c32905SMatthias Ringwald                 break;
271227c32905SMatthias Ringwald             }
2713c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2714e53be891SMatthias Ringwald                 uint8_t buffer[17];
2715e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27169af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
271742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2718c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2719e53be891SMatthias Ringwald                 } else {
2720c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2721e53be891SMatthias Ringwald                 }
2722687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2723e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2724e53be891SMatthias Ringwald                 break;
2725e53be891SMatthias Ringwald             }
2726c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2727e53be891SMatthias Ringwald                 uint8_t buffer[17];
2728e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2729e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27309d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27314ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
273240c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
273342134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
273445a61d50SMatthias Ringwald                         // responder
2735c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
273645a61d50SMatthias Ringwald                     } else {
273745a61d50SMatthias Ringwald                         // initiator
2738c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
273945a61d50SMatthias Ringwald                     }
274045a61d50SMatthias Ringwald                 } else {
274140c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
274242134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2743e53be891SMatthias Ringwald                         // responder
274447fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
274540c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2746901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27472886623dSMatthias Ringwald                         } else {
274840c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27492886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2750446a8c36SMatthias Ringwald                         }
2751e53be891SMatthias Ringwald                     } else {
2752136d331aSMatthias Ringwald                         // initiator
2753c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2754e53be891SMatthias Ringwald                     }
275545a61d50SMatthias Ringwald                 }
2756687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2757e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2758e53be891SMatthias Ringwald                 break;
2759e53be891SMatthias Ringwald             }
2760c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2761e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2762e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2763e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2764dc300847SMatthias Ringwald 
276542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2766c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2767e53be891SMatthias Ringwald                 } else {
2768c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2769e53be891SMatthias Ringwald                 }
2770e083ca23SMatthias Ringwald 
2771687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2772e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2773e53be891SMatthias Ringwald                 break;
2774e53be891SMatthias Ringwald             }
2775e53be891SMatthias Ringwald 
2776e53be891SMatthias Ringwald #endif
277742134bc6SMatthias Ringwald 
277842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2779dd12a62bSMatthias Ringwald 
278087014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
278187014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
278287014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2783687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2784c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
278587014f74SMatthias Ringwald 				break;
278687014f74SMatthias Ringwald 			}
278787014f74SMatthias Ringwald 
278838196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
278938196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
279038196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
279138196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
279238196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
279338196718SMatthias Ringwald 						// start using context by loading security info
279438196718SMatthias Ringwald 						sm_reset_setup();
279538196718SMatthias Ringwald 						sm_load_security_info(connection);
279638196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
279738196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
279838196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
279942646f38SMatthias Ringwald                             sm_reencryption_started(connection);
280038196718SMatthias Ringwald                             sm_trigger_run();
280138196718SMatthias Ringwald 							break;
280238196718SMatthias Ringwald 						}
280338196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
280438196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
280538196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
280638196718SMatthias Ringwald 						return;
280738196718SMatthias Ringwald 					default:
280838196718SMatthias Ringwald 						// just wait until IRK lookup is completed
280938196718SMatthias Ringwald 						break;
281038196718SMatthias Ringwald 				}
281138196718SMatthias Ringwald 				break;
281238196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
281338196718SMatthias Ringwald 
2814b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2815b6afa23eSMatthias Ringwald                 sm_reset_setup();
28169b75de03SMatthias Ringwald 
28179b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28189b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28199b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28209b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28219b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28229b75de03SMatthias Ringwald                         if (have_ltk){
28239b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
282419a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28259b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28269b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28279b75de03SMatthias Ringwald                         }
28289b75de03SMatthias Ringwald                         break;
28299b75de03SMatthias Ringwald                     default:
28309b75de03SMatthias Ringwald                         break;
28319b75de03SMatthias Ringwald                 }
28329b75de03SMatthias Ringwald 
2833b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2834d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
283539543d07SMatthias Ringwald 
2836b6afa23eSMatthias Ringwald 				// recover pairing request
2837b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2838b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2839b6afa23eSMatthias Ringwald 
2840b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2841b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2842b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2843b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2844b6afa23eSMatthias Ringwald                     }
2845b6afa23eSMatthias Ringwald #endif
28469305033eSMatthias Ringwald 				if (err != 0){
2847f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2848b6afa23eSMatthias Ringwald 					sm_trigger_run();
2849b6afa23eSMatthias Ringwald 					break;
2850b6afa23eSMatthias Ringwald 				}
2851b6afa23eSMatthias Ringwald 
2852b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2853b6afa23eSMatthias Ringwald 
2854b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2855b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2856b6afa23eSMatthias 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);
2857b6afa23eSMatthias Ringwald 					break;
2858b6afa23eSMatthias Ringwald 				}
2859b6afa23eSMatthias Ringwald 
2860b6afa23eSMatthias Ringwald 				/* fall through */
2861b6afa23eSMatthias Ringwald 
28623deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28631ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2864f55bd529SMatthias Ringwald 
2865f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28663deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28671ad129beSMatthias Ringwald 
2868f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2869f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2870f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2871f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2872f55bd529SMatthias Ringwald                 }
2873f55bd529SMatthias Ringwald #endif
2874f55bd529SMatthias Ringwald                 // setup in response
2875f55bd529SMatthias 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);
2876f55bd529SMatthias 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);
2877f55bd529SMatthias Ringwald 
2878f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
28799a90d41aSMatthias 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));
2880f55bd529SMatthias Ringwald 
288127c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2882c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
28830b8af2a5SMatthias Ringwald                 } else {
28840b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
288527c32905SMatthias Ringwald                 }
28860b8af2a5SMatthias Ringwald 
2887687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
28883deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2889446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2890c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
28913deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2892446a8c36SMatthias Ringwald                 }
28933deb3ec6SMatthias Ringwald                 return;
289442134bc6SMatthias Ringwald #endif
28953deb3ec6SMatthias Ringwald 
28963deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
28973deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
28983deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
28999c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
290042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29013deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29023deb3ec6SMatthias Ringwald                 } else {
29033deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29043deb3ec6SMatthias Ringwald                 }
2905687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29063deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29073deb3ec6SMatthias Ringwald                 break;
29083deb3ec6SMatthias Ringwald             }
29093deb3ec6SMatthias Ringwald 
2910d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29113deb3ec6SMatthias Ringwald                 // already busy?
29123deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2913d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2914d1a1f6a4SMatthias 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);
2915d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2916d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2917f3582630SMatthias 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);
29183deb3ec6SMatthias Ringwald                 break;
29193deb3ec6SMatthias Ringwald 
29203deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29213deb3ec6SMatthias Ringwald                 // already busy?
29223deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29233deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2924d1a1f6a4SMatthias 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);
2925d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2926d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2927f3582630SMatthias 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);
29283deb3ec6SMatthias Ringwald                 break;
2929d1a1f6a4SMatthias Ringwald 
29303deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29313deb3ec6SMatthias Ringwald                 // already busy?
29323deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29333deb3ec6SMatthias Ringwald                 // calculate STK
293442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2935d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29363deb3ec6SMatthias Ringwald                 } else {
2937d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29383deb3ec6SMatthias Ringwald                 }
2939d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2940d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2941f3582630SMatthias 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);
29423deb3ec6SMatthias Ringwald                 break;
2943d1a1f6a4SMatthias Ringwald 
29443deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29453deb3ec6SMatthias Ringwald                 // already busy?
29463deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29473deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29489ad0dd7cSMatthias Ringwald 
29499ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29509ad0dd7cSMatthias Ringwald                 // r' = padding || r
29519ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29529ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29536535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29549ad0dd7cSMatthias Ringwald 
29553deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2956d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2957d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2958f3582630SMatthias 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);
2959d1a1f6a4SMatthias Ringwald                 break;
2960d1a1f6a4SMatthias Ringwald 
29613deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29623deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29633deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29649c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
296542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29663deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29673deb3ec6SMatthias Ringwald                 } else {
29683deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
29693deb3ec6SMatthias Ringwald                 }
2970687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29713deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29723deb3ec6SMatthias Ringwald                 return;
29733deb3ec6SMatthias Ringwald             }
297442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
29753deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
29763deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
29779c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
29783deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
29793deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
29803deb3ec6SMatthias Ringwald                 return;
29813deb3ec6SMatthias Ringwald             }
2982d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
29833deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
29849c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
29855567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
29863deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
29873deb3ec6SMatthias Ringwald                 return;
29883deb3ec6SMatthias Ringwald             }
2989dd12a62bSMatthias Ringwald 
2990dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
29913deb3ec6SMatthias Ringwald                 // already busy?
29923deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29933deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
2994c61cfe5aSMatthias Ringwald 
2995dd12a62bSMatthias Ringwald 				sm_reset_setup();
2996dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
2997dd12a62bSMatthias Ringwald 
299842646f38SMatthias Ringwald 				sm_reencryption_started(connection);
299942646f38SMatthias Ringwald 
3000c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3001c61cfe5aSMatthias Ringwald                 // r' = padding || r
3002c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3003c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30046535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3005c61cfe5aSMatthias Ringwald 
30063deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3007d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3008d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3009f3582630SMatthias 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);
30103deb3ec6SMatthias Ringwald                 return;
301142134bc6SMatthias Ringwald #endif
301242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
301342134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
301442134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
301542134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
301642134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
301742134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
301842134bc6SMatthias Ringwald                 return;
301942134bc6SMatthias Ringwald             }
302042134bc6SMatthias Ringwald #endif
30213deb3ec6SMatthias Ringwald 
30223deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3023403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3024403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30253deb3ec6SMatthias Ringwald                     return;
30263deb3ec6SMatthias Ringwald                 }
30273deb3ec6SMatthias Ringwald 
30283deb3ec6SMatthias Ringwald                 // keys are sent
302942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30303deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
30313deb3ec6SMatthias Ringwald                     if (sm_key_distribution_all_received(connection)){
30323deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3033f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3034f5020412SMatthias Ringwald                         // start CTKD right away
3035f5020412SMatthias Ringwald                         continue;
30363deb3ec6SMatthias Ringwald                     } else {
30373deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30383deb3ec6SMatthias Ringwald                     }
30393deb3ec6SMatthias Ringwald                 } else {
30401dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30413deb3ec6SMatthias Ringwald                 }
30423deb3ec6SMatthias Ringwald                 break;
30433deb3ec6SMatthias Ringwald 
30443deb3ec6SMatthias Ringwald             default:
30453deb3ec6SMatthias Ringwald                 break;
30463deb3ec6SMatthias Ringwald         }
30473deb3ec6SMatthias Ringwald 
30483deb3ec6SMatthias Ringwald         // check again if active connection was released
30497149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
30503deb3ec6SMatthias Ringwald     }
30513deb3ec6SMatthias Ringwald }
30523deb3ec6SMatthias Ringwald 
3053d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3054d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3055f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
305604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
305704678764SMatthias Ringwald 
3058f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3059f3582630SMatthias Ringwald     if (connection == NULL) return;
3060f3582630SMatthias Ringwald 
3061d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
306204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3063f3582630SMatthias 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);
3064d1a1f6a4SMatthias Ringwald }
30653deb3ec6SMatthias Ringwald 
3066d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3067f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
306804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
306904678764SMatthias Ringwald 
3070f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3071f3582630SMatthias Ringwald     if (connection == NULL) return;
3072f3582630SMatthias Ringwald 
30738314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
30743deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
307570b44dd4SMatthias Ringwald     sm_trigger_run();
3076d1a1f6a4SMatthias Ringwald }
3077d1a1f6a4SMatthias Ringwald 
3078d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3079d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3080f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
308104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
308204678764SMatthias Ringwald 
3083f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3084f3582630SMatthias Ringwald     if (connection == NULL) return;
3085f3582630SMatthias Ringwald 
3086d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
308704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3088f3582630SMatthias 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);
3089d1a1f6a4SMatthias Ringwald }
3090d1a1f6a4SMatthias Ringwald 
3091d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3092f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
309304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
309404678764SMatthias Ringwald 
3095f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3096f3582630SMatthias Ringwald     if (connection == NULL) return;
3097f3582630SMatthias Ringwald 
3098d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3099d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3100f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
310170b44dd4SMatthias Ringwald         sm_trigger_run();
31023deb3ec6SMatthias Ringwald         return;
31033deb3ec6SMatthias Ringwald     }
310442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31053deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
310670b44dd4SMatthias Ringwald         sm_trigger_run();
31073deb3ec6SMatthias Ringwald     } else {
3108d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3109d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3110f3582630SMatthias 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);
31113deb3ec6SMatthias Ringwald     }
31123deb3ec6SMatthias Ringwald }
3113d1a1f6a4SMatthias Ringwald 
3114d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
311504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3116f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
311704678764SMatthias Ringwald 
3118f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3119f3582630SMatthias Ringwald     if (connection == NULL) return;
3120f3582630SMatthias Ringwald 
31213deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
31228314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
312342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31243deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
31253deb3ec6SMatthias Ringwald     } else {
31263deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
31273deb3ec6SMatthias Ringwald     }
312870b44dd4SMatthias Ringwald     sm_trigger_run();
3129d1a1f6a4SMatthias Ringwald }
3130d1a1f6a4SMatthias Ringwald 
3131d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3132d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3133f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
313404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
313504678764SMatthias Ringwald 
3136f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3137f3582630SMatthias Ringwald     if (connection == NULL) return;
3138f3582630SMatthias Ringwald 
3139d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31403deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31413deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
31423deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
31433deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31443deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31453deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3146d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
314704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3148f3582630SMatthias 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);
31493deb3ec6SMatthias Ringwald }
3150d1a1f6a4SMatthias Ringwald 
31512a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3152d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3153d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
315404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3155f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
315604678764SMatthias Ringwald 
3157f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3158f3582630SMatthias Ringwald     if (connection == NULL) return;
3159f3582630SMatthias Ringwald 
3160d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31613deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31623deb3ec6SMatthias Ringwald 
31633deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
31643deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
31653deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31663deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31673deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3168d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
316904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3170f3582630SMatthias 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);
31713deb3ec6SMatthias Ringwald }
31722a526f21SMatthias Ringwald #endif
3173d1a1f6a4SMatthias Ringwald 
3174d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3175d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3176f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
317704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
317804678764SMatthias Ringwald 
3179f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3180f3582630SMatthias Ringwald     if (connection == NULL) return;
3181f3582630SMatthias Ringwald 
31828314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
31833deb3ec6SMatthias Ringwald     // calc CSRK next
3184d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
318504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3186f3582630SMatthias 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);
3187d1a1f6a4SMatthias Ringwald }
3188d1a1f6a4SMatthias Ringwald 
3189d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3190f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
319104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
319204678764SMatthias Ringwald 
3193f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3194f3582630SMatthias Ringwald     if (connection == NULL) return;
3195f3582630SMatthias Ringwald 
3196d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
31978314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
31983deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
31993deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
32003deb3ec6SMatthias Ringwald     } else {
32013deb3ec6SMatthias Ringwald         // no keys to send, just continue
320242134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3203c5a72e35SMatthias Ringwald             if (sm_key_distribution_all_received(connection)){
3204c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3205c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3206c5a72e35SMatthias Ringwald             } else {
32073deb3ec6SMatthias Ringwald                 // slave -> receive master keys
32083deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3209c5a72e35SMatthias Ringwald             }
32103deb3ec6SMatthias Ringwald         } else {
3211af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
32123deb3ec6SMatthias Ringwald         }
32132bacf595SMatthias Ringwald     }
321470b44dd4SMatthias Ringwald     sm_trigger_run();
3215d1a1f6a4SMatthias Ringwald }
3216d1a1f6a4SMatthias Ringwald 
321742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3218d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3219f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322104678764SMatthias Ringwald 
3222f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3223f3582630SMatthias Ringwald     if (connection == NULL) return;
3224f3582630SMatthias Ringwald 
32253deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32268314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3227d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
322870b44dd4SMatthias Ringwald     sm_trigger_run();
3229d1a1f6a4SMatthias Ringwald }
3230d1a1f6a4SMatthias Ringwald #endif
3231d1a1f6a4SMatthias Ringwald 
3232d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3233d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3234d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323504678764SMatthias Ringwald 
3236d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3237d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3238d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3239d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3240d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3241a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
324270b44dd4SMatthias Ringwald         sm_trigger_run();
32433deb3ec6SMatthias Ringwald         return;
32443deb3ec6SMatthias Ringwald     }
3245d1a1f6a4SMatthias Ringwald     // no match, try next
3246d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
324770b44dd4SMatthias Ringwald     sm_trigger_run();
32483deb3ec6SMatthias Ringwald }
32493deb3ec6SMatthias Ringwald 
3250d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3251d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3252d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325304678764SMatthias Ringwald 
3254d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3255d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
325670b44dd4SMatthias Ringwald     sm_trigger_run();
32577df18c15SMatthias Ringwald }
3258d1a1f6a4SMatthias Ringwald 
3259d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3260d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3261d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326204678764SMatthias Ringwald 
3263d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3264d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
326570b44dd4SMatthias Ringwald     sm_trigger_run();
32667df18c15SMatthias Ringwald }
3267d1a1f6a4SMatthias Ringwald 
3268d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3269d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3270d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327104678764SMatthias Ringwald 
32726535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3273d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
327470b44dd4SMatthias Ringwald     sm_trigger_run();
327551fa0b28SMatthias Ringwald }
32767df18c15SMatthias Ringwald 
3277d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3278d1a1f6a4SMatthias Ringwald     UNUSED(arg);
32793deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
32803deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
32813deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
32823deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
32833deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
32844ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
32854ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
32863deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
32873deb3ec6SMatthias Ringwald             break;
32883deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
32893deb3ec6SMatthias Ringwald         default:
32903deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
32914ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
32923deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
32933deb3ec6SMatthias Ringwald             break;
32943deb3ec6SMatthias Ringwald     }
329570b44dd4SMatthias Ringwald     sm_trigger_run();
32963deb3ec6SMatthias Ringwald }
32973deb3ec6SMatthias Ringwald 
3298c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
32996ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3300f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3301f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3302f3582630SMatthias Ringwald     if (connection == NULL) return;
3303c59d0c92SMatthias Ringwald 
330465a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
330570b44dd4SMatthias Ringwald     sm_trigger_run();
330665a9a04eSMatthias Ringwald }
3307d1a1f6a4SMatthias Ringwald 
33086ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
33096ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
33106ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
33116ca80073SMatthias Ringwald     if (connection == NULL) return;
33126ca80073SMatthias Ringwald 
3313b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
331470b44dd4SMatthias Ringwald     sm_trigger_run();
3315d1a1f6a4SMatthias Ringwald }
3316f1c1783eSMatthias Ringwald #endif
3317f1c1783eSMatthias Ringwald 
3318d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3319f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3320f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3321f3582630SMatthias Ringwald     if (connection == NULL) return;
3322f3582630SMatthias Ringwald 
3323d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
332470b44dd4SMatthias Ringwald     sm_trigger_run();
3325d1a1f6a4SMatthias Ringwald }
3326d1a1f6a4SMatthias Ringwald 
3327d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3328f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3329f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3330f3582630SMatthias Ringwald     if (connection == NULL) return;
3331f3582630SMatthias Ringwald 
3332caf15bf3SMatthias Ringwald     sm_reset_tk();
3333caf15bf3SMatthias Ringwald     uint32_t tk;
33345ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
33353deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3336d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
33373deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
33384ea43905SMatthias Ringwald         if (tk >= 999999u){
33394ea43905SMatthias Ringwald             tk = tk - 999999u;
33403deb3ec6SMatthias Ringwald         }
3341caf15bf3SMatthias Ringwald     } else {
3342caf15bf3SMatthias Ringwald         // override with pre-defined passkey
33434b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3344caf15bf3SMatthias Ringwald     }
3345f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
334642134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33473deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
33483deb3ec6SMatthias Ringwald     } else {
3349b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3350b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3351b41539d5SMatthias Ringwald         } else {
33523deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
33533deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
33543deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
33553deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3356f3582630SMatthias 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);
33573deb3ec6SMatthias Ringwald             }
33583deb3ec6SMatthias Ringwald         }
3359b41539d5SMatthias Ringwald     }
336070b44dd4SMatthias Ringwald     sm_trigger_run();
33613deb3ec6SMatthias Ringwald }
3362d1a1f6a4SMatthias Ringwald 
3363d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3364f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3365f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3366f3582630SMatthias Ringwald     if (connection == NULL) return;
3367f3582630SMatthias Ringwald 
3368d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3369d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3370d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3371d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
337270b44dd4SMatthias Ringwald     sm_trigger_run();
3373d1a1f6a4SMatthias Ringwald }
3374d1a1f6a4SMatthias Ringwald 
3375d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3376f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3377f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3378f3582630SMatthias Ringwald     if (connection == NULL) return;
3379f3582630SMatthias Ringwald 
3380d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
33813deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
33824ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
33833deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
33844ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
33858b3ffec5SMatthias 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);
33863deb3ec6SMatthias Ringwald }
3387899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3388899e6e02SMatthias Ringwald     // warn about default ER/IR
33891979f09cSMatthias Ringwald     bool warning = false;
3390899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
33911979f09cSMatthias Ringwald         warning = true;
3392899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3393899e6e02SMatthias Ringwald     }
3394899e6e02SMatthias Ringwald     if (sm_er_is_default()){
33951979f09cSMatthias Ringwald         warning = true;
3396899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3397899e6e02SMatthias Ringwald     }
339821045273SMatthias Ringwald     if (warning) {
3399899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3400899e6e02SMatthias Ringwald     }
340121045273SMatthias Ringwald }
3402899e6e02SMatthias Ringwald 
3403899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
34041979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34059305033eSMatthias Ringwald     if (arg != NULL){
3406899e6e02SMatthias Ringwald         // key generated, store in tlv
34074ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3408899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3409e0d13a19SMilanka Ringwald         UNUSED(status);
3410899e6e02SMatthias Ringwald     }
3411899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
34128d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3413841468bbSMatthias Ringwald 
3414841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3415841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3416841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3417841468bbSMatthias Ringwald     }
3418841468bbSMatthias Ringwald 
341970b44dd4SMatthias Ringwald     sm_trigger_run();
3420899e6e02SMatthias Ringwald }
3421899e6e02SMatthias Ringwald 
3422899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
34231979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34249305033eSMatthias Ringwald     if (arg != 0){
3425899e6e02SMatthias Ringwald         // key generated, store in tlv
34264ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3427899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3428e0d13a19SMilanka Ringwald         UNUSED(status);
3429899e6e02SMatthias Ringwald     }
3430899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3431899e6e02SMatthias Ringwald 
3432899e6e02SMatthias Ringwald     // try load ir
34334ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3434899e6e02SMatthias Ringwald     if (key_size == 16){
3435899e6e02SMatthias Ringwald         // ok, let's continue
3436899e6e02SMatthias Ringwald         log_info("IR from TLV");
3437899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3438899e6e02SMatthias Ringwald     } else {
3439899e6e02SMatthias Ringwald         // invalid, generate new random one
34401979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3441899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3442899e6e02SMatthias Ringwald     }
3443899e6e02SMatthias Ringwald }
34443deb3ec6SMatthias Ringwald 
3445f664b5e8SMatthias 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){
3446f664b5e8SMatthias Ringwald 
3447f664b5e8SMatthias Ringwald     // connection info
3448f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3449f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3450f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3451f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3452f664b5e8SMatthias Ringwald 
3453f664b5e8SMatthias Ringwald     // security properties
3454f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3455f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3456f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3457f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3458f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3459f664b5e8SMatthias Ringwald 
3460f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3461f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3462f664b5e8SMatthias Ringwald 
3463f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3464f664b5e8SMatthias Ringwald }
3465f664b5e8SMatthias Ringwald 
3466d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
34673deb3ec6SMatthias Ringwald 
3468cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3469cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
34709ec2630cSMatthias Ringwald 
34713deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3472711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3473fbe050beSMatthias Ringwald     uint8_t           status;
3474f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3475f664b5e8SMatthias Ringwald 
34763deb3ec6SMatthias Ringwald     switch (packet_type) {
34773deb3ec6SMatthias Ringwald 
34783deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
34790e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
34803deb3ec6SMatthias Ringwald 
34813deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
34823deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3483be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
34843deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3485899e6e02SMatthias Ringwald 
3486899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3487899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
34889305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
34894ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3490899e6e02SMatthias Ringwald                             if (key_size == 16){
3491899e6e02SMatthias Ringwald                                 // ok, let's continue
3492899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3493899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3494899e6e02SMatthias Ringwald                             } else {
3495899e6e02SMatthias Ringwald                                 // invalid, generate random one
34961979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3497899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3498899e6e02SMatthias Ringwald                             }
3499899e6e02SMatthias Ringwald                         } else {
3500899e6e02SMatthias Ringwald                             sm_validate_er_ir();
35018d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3502841468bbSMatthias Ringwald 
3503841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3504841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3505841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3506841468bbSMatthias Ringwald                             }
3507899e6e02SMatthias Ringwald                         }
35081bf086daSMatthias Ringwald 
35091bf086daSMatthias Ringwald                         // restart random address updates after power cycle
35101bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
35113deb3ec6SMatthias Ringwald 					}
35123deb3ec6SMatthias Ringwald 					break;
35132d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
35142d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
35152d095694SMatthias Ringwald 			        // ignore if connection failed
35162d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
35173deb3ec6SMatthias Ringwald 
35182d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
35192d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
35202d095694SMatthias Ringwald 			        if (!sm_conn) break;
35212d095694SMatthias Ringwald 
35222d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
35232d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
35242d095694SMatthias Ringwald                                        con_handle,
35252d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3526f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
35272d095694SMatthias Ringwald                                        addr);
35282d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
35292d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
35302d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
35312d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
35322d095694SMatthias Ringwald 			        break;
35332d095694SMatthias Ringwald #endif
35343deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
35353deb3ec6SMatthias Ringwald                     switch (packet[2]) {
35363deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3537f664b5e8SMatthias Ringwald                             // ignore if connection failed
3538f664b5e8SMatthias Ringwald                             if (packet[3]) return;
35393deb3ec6SMatthias Ringwald 
3540711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3541711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35423deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35433deb3ec6SMatthias Ringwald 
3544f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3545f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3546f664b5e8SMatthias Ringwald                                                con_handle,
3547f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3548f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3549f664b5e8SMatthias Ringwald                                                addr);
3550687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3551f664b5e8SMatthias Ringwald 
3552f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3553f664b5e8SMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet)){
3554ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3555ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3556f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3557ba9fc867SMatthias Ringwald                             } else {
3558ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3559ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
35603deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
35613deb3ec6SMatthias Ringwald                             }
35623deb3ec6SMatthias Ringwald                             break;
35633deb3ec6SMatthias Ringwald 
35643deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3565711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3566711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35673deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35683deb3ec6SMatthias Ringwald 
35693deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
35703deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
35713deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
35723deb3ec6SMatthias Ringwald                                 break;
35733deb3ec6SMatthias Ringwald                             }
3574c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3575778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3576778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3577e53be891SMatthias Ringwald                                 break;
3578e53be891SMatthias Ringwald                             }
35793deb3ec6SMatthias Ringwald 
35803deb3ec6SMatthias Ringwald                             // store rand and ediv
35819c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3582f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3583549ad5d2SMatthias Ringwald 
3584549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3585549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
35864ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
35876c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
358806cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3589549ad5d2SMatthias Ringwald                                     break;
3590549ad5d2SMatthias Ringwald                                 }
35916c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
35926c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
35936c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
35946c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
35956c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
35966c39055aSMatthias Ringwald                                         break;
35976c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
35986c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
35996c39055aSMatthias Ringwald                                         break;
36006c39055aSMatthias Ringwald                                     default:
36016c39055aSMatthias Ringwald                                         // wait for irk look doen
36026c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
36036c39055aSMatthias Ringwald                                         break;
36046c39055aSMatthias Ringwald                                 }
36056c39055aSMatthias Ringwald                                 break;
36066c39055aSMatthias Ringwald                             }
3607549ad5d2SMatthias Ringwald 
3608549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
360906cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3610549ad5d2SMatthias Ringwald #else
3611549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3612549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3613549ad5d2SMatthias Ringwald #endif
36143deb3ec6SMatthias Ringwald                             break;
3615804d3e67SMatthias Ringwald 
36163deb3ec6SMatthias Ringwald                         default:
36173deb3ec6SMatthias Ringwald                             break;
36183deb3ec6SMatthias Ringwald                     }
36193deb3ec6SMatthias Ringwald                     break;
36203deb3ec6SMatthias Ringwald 
36213deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
36223b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3623711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36243deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36253deb3ec6SMatthias Ringwald 
36263b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
36273deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
36283deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
36293deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
363003a9359aSMatthias Ringwald 
3631fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3632fbe050beSMatthias Ringwald 
36335567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
363403a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3635fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3636fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
36378d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
36388d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36398d4eef95SMatthias Ringwald                                 } else {
364003a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36418d4eef95SMatthias Ringwald                                 }
3642fbe050beSMatthias Ringwald                             } else {
3643e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3644cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
36453b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3646cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
36473b7fd749SMatthias Ringwald                             }
3648fbe050beSMatthias Ringwald 
3649fbe050beSMatthias Ringwald                             // emit re-encryption complete
365073102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3651fbe050beSMatthias Ringwald 
3652c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3653c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3654c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
36550ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
365603a9359aSMatthias Ringwald                             }
365703a9359aSMatthias Ringwald 
36583deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
36593deb3ec6SMatthias Ringwald                             break;
3660fbe050beSMatthias Ringwald 
36613deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3662fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3663dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
366442134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
36653deb3ec6SMatthias Ringwald                                 // slave
3666bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3667bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3668bbf8db22SMatthias Ringwald                                 } else {
3669f3582630SMatthias 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);
3670bbf8db22SMatthias Ringwald                                 }
36713deb3ec6SMatthias Ringwald                             } else {
36723deb3ec6SMatthias Ringwald                                 // master
36733deb3ec6SMatthias Ringwald                                 if (sm_key_distribution_all_received(sm_conn)){
36743deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
36753deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3676f3582630SMatthias 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);
36773deb3ec6SMatthias Ringwald                                 } else {
36783deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
36793deb3ec6SMatthias Ringwald                                 }
36803deb3ec6SMatthias Ringwald                             }
36813deb3ec6SMatthias Ringwald                             break;
36823deb3ec6SMatthias Ringwald                         default:
36833deb3ec6SMatthias Ringwald                             break;
36843deb3ec6SMatthias Ringwald                     }
36853deb3ec6SMatthias Ringwald                     break;
36863deb3ec6SMatthias Ringwald 
36873deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3688711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3689711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36903deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36913deb3ec6SMatthias Ringwald 
36923deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
36933deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
36943deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
36953deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
36965567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
36975567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
36985567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36995567aa60SMatthias Ringwald                             } else {
37003deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37015567aa60SMatthias Ringwald                             }
37023deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
37033deb3ec6SMatthias Ringwald                             break;
37043deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
370542134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
37063deb3ec6SMatthias Ringwald                                 // slave
3707f3582630SMatthias 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);
37083deb3ec6SMatthias Ringwald                             } else {
37093deb3ec6SMatthias Ringwald                                 // master
37103deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
37113deb3ec6SMatthias Ringwald                             }
37123deb3ec6SMatthias Ringwald                             break;
37133deb3ec6SMatthias Ringwald                         default:
37143deb3ec6SMatthias Ringwald                             break;
37153deb3ec6SMatthias Ringwald                     }
37163deb3ec6SMatthias Ringwald                     break;
37173deb3ec6SMatthias Ringwald 
37183deb3ec6SMatthias Ringwald 
37193deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3720711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3721711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3722711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37233deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37243deb3ec6SMatthias Ringwald 
372503f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
37267f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37277f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
37287f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
37297f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
37307f3f442dSMatthias Ringwald                             break;
37317f3f442dSMatthias Ringwald                         default:
373268a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37330ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
37347f3f442dSMatthias Ringwald                             break;
373503f736b1SMatthias Ringwald                     }
3736accbde80SMatthias Ringwald 
37373deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
37383deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
37393deb3ec6SMatthias Ringwald                     break;
37403deb3ec6SMatthias Ringwald 
37413deb3ec6SMatthias Ringwald 				case HCI_EVENT_COMMAND_COMPLETE:
374233373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
37439091c5f5SMatthias Ringwald                         // set local addr for le device db
374433373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
37450c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
374633373e40SMatthias Ringwald                     }
374765b44ffdSMatthias Ringwald                     break;
374865b44ffdSMatthias Ringwald                 default:
374965b44ffdSMatthias Ringwald                     break;
37503deb3ec6SMatthias Ringwald 			}
375165b44ffdSMatthias Ringwald             break;
375265b44ffdSMatthias Ringwald         default:
375365b44ffdSMatthias Ringwald             break;
37543deb3ec6SMatthias Ringwald 	}
37553deb3ec6SMatthias Ringwald 
37563deb3ec6SMatthias Ringwald     sm_run();
37573deb3ec6SMatthias Ringwald }
37583deb3ec6SMatthias Ringwald 
37593deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
37603deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
37613deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
37623deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
37633deb3ec6SMatthias Ringwald }
37643deb3ec6SMatthias Ringwald 
3765945888f5SMatthias Ringwald 
376631c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3767945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3768945888f5SMatthias Ringwald     switch (method){
3769945888f5SMatthias Ringwald         case JUST_WORKS:
377047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3771945888f5SMatthias Ringwald             return 1;
3772945888f5SMatthias Ringwald         default:
3773945888f5SMatthias Ringwald             return 0;
3774945888f5SMatthias Ringwald     }
3775945888f5SMatthias Ringwald }
377607036a04SMatthias Ringwald // responder
3777945888f5SMatthias Ringwald 
3778688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3779688a08f9SMatthias Ringwald     switch (method){
3780688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3781688a08f9SMatthias Ringwald             return 1;
3782688a08f9SMatthias Ringwald         default:
3783688a08f9SMatthias Ringwald             return 0;
3784688a08f9SMatthias Ringwald     }
3785688a08f9SMatthias Ringwald }
378640c5d850SMatthias Ringwald 
378740c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
378840c5d850SMatthias Ringwald     switch (method){
378940c5d850SMatthias Ringwald         case PK_RESP_INPUT:
379040c5d850SMatthias Ringwald         case PK_INIT_INPUT:
379147fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
379240c5d850SMatthias Ringwald             return 1;
379340c5d850SMatthias Ringwald         default:
379440c5d850SMatthias Ringwald             return 0;
379540c5d850SMatthias Ringwald     }
379640c5d850SMatthias Ringwald }
379740c5d850SMatthias Ringwald 
379831c09488SMatthias Ringwald #endif
3799688a08f9SMatthias Ringwald 
38003deb3ec6SMatthias Ringwald /**
38013deb3ec6SMatthias Ringwald  * @return ok
38023deb3ec6SMatthias Ringwald  */
38033deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
38043deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
38053deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
38063deb3ec6SMatthias Ringwald         case JUST_WORKS:
38074ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
38083deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
38093deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
381047fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
38114ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
38123deb3ec6SMatthias Ringwald         case OOB:
38134ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
381447fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
38154ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
38163deb3ec6SMatthias Ringwald         default:
38173deb3ec6SMatthias Ringwald             return 0;
38183deb3ec6SMatthias Ringwald     }
38193deb3ec6SMatthias Ringwald }
38203deb3ec6SMatthias Ringwald 
38218334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
38228334d3d8SMatthias Ringwald 
38234c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
38244c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
38254c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
38264c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
38274c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
38284c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
38294c1d1092SMatthias Ringwald             17, // 0x04 pairing random
38304c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
38314c1d1092SMatthias Ringwald             17, // 0x06 encryption information
38327a2e6387SMatthias Ringwald             11, // 0x07 master identification
38334c1d1092SMatthias Ringwald             17, // 0x08 identification information
38344c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
38354c1d1092SMatthias Ringwald             17, // 0x0a signing information
38364c1d1092SMatthias Ringwald             2,  // 0x0b security request
38374c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
38384c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
38394c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
38404c1d1092SMatthias Ringwald     };
38413deb3ec6SMatthias Ringwald 
3842c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3843b170b20fSMatthias Ringwald         sm_run();
3844b170b20fSMatthias Ringwald     }
3845b170b20fSMatthias Ringwald 
38463deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
38474ea43905SMatthias Ringwald     if (size == 0u) return;
38484c1d1092SMatthias Ringwald 
38494c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
38504c1d1092SMatthias Ringwald 
38514c1d1092SMatthias Ringwald     // validate pdu size
38524c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
38537a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
38543deb3ec6SMatthias Ringwald 
3855711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
38563deb3ec6SMatthias Ringwald     if (!sm_conn) return;
38573deb3ec6SMatthias Ringwald 
38584c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
385968a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
38600ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3861accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
38623deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
38633deb3ec6SMatthias Ringwald         return;
38643deb3ec6SMatthias Ringwald     }
38653deb3ec6SMatthias Ringwald 
38664c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
38673deb3ec6SMatthias Ringwald 
38683deb3ec6SMatthias Ringwald     int err;
386942134bc6SMatthias Ringwald     UNUSED(err);
38703deb3ec6SMatthias Ringwald 
38714c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
38723d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
38733d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
38743d7fe1e9SMatthias Ringwald         buffer[1] = 3;
38753d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
38763d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
38773d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
38783d7fe1e9SMatthias Ringwald         return;
38793d7fe1e9SMatthias Ringwald     }
38803d7fe1e9SMatthias Ringwald 
3881a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
3882212d735eSMatthias Ringwald     int have_ltk;
3883212d735eSMatthias Ringwald     uint8_t ltk[16];
3884a6ca6916SDavid Lechner #endif
3885212d735eSMatthias Ringwald 
38863deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
38873deb3ec6SMatthias Ringwald 
3888c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
38893deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
38903deb3ec6SMatthias Ringwald             return;
38913deb3ec6SMatthias Ringwald 
389242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
389342134bc6SMatthias Ringwald 
38943deb3ec6SMatthias Ringwald         // Initiator
38953deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
38964c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
38973deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
38983deb3ec6SMatthias Ringwald                 break;
38993deb3ec6SMatthias Ringwald             }
390034c39fbdSMatthias Ringwald 
39012c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
39022c041b42SMatthias Ringwald             if (sm_sc_only_mode){
39032c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
39042c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
3905f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
39062c041b42SMatthias Ringwald                     break;
39072c041b42SMatthias Ringwald                 }
39082c041b42SMatthias Ringwald             }
39092c041b42SMatthias Ringwald #endif
39102c041b42SMatthias Ringwald 
391134c39fbdSMatthias Ringwald             // IRK complete?
391234c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
391334c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
3914dc8ca372SMatthias Ringwald                     // start pairing
39153deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
39163deb3ec6SMatthias Ringwald                     break;
3917e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
3918e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3919e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
39208549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
39218549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
39228549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
39235567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
3924e061bbd4SMatthias Ringwald                     } else {
3925dc8ca372SMatthias Ringwald                         // start pairing
3926e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3927e061bbd4SMatthias Ringwald                     }
3928e061bbd4SMatthias Ringwald                     break;
392934c39fbdSMatthias Ringwald                 default:
39303deb3ec6SMatthias Ringwald                     // otherwise, store security request
39313deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
39323deb3ec6SMatthias Ringwald                     break;
3933dc8ca372SMatthias Ringwald             }
3934dc8ca372SMatthias Ringwald             break;
39353deb3ec6SMatthias Ringwald 
39363deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3937aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
3938aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3939aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3940aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3941aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
3942aacfafc3SMatthias Ringwald                 break;
3943aacfafc3SMatthias Ringwald             }
3944aacfafc3SMatthias Ringwald 
3945aacfafc3SMatthias Ringwald             // all other pdus are incorrect
39464c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
39473deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39483deb3ec6SMatthias Ringwald                 break;
39493deb3ec6SMatthias Ringwald             }
39500af429c6SMatthias Ringwald 
39513deb3ec6SMatthias Ringwald             // store pairing request
39526535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
39536535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
39543deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
39550af429c6SMatthias Ringwald 
39560af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
39570af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
39580af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
39590af429c6SMatthias Ringwald                 err = test_pairing_failure;
39600af429c6SMatthias Ringwald             }
39610af429c6SMatthias Ringwald #endif
39620af429c6SMatthias Ringwald 
39639305033eSMatthias Ringwald             if (err != 0){
3964f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
39653deb3ec6SMatthias Ringwald                 break;
39663deb3ec6SMatthias Ringwald             }
3967b41539d5SMatthias Ringwald 
3968b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
3969b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3970f3582630SMatthias 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);
3971b41539d5SMatthias Ringwald                 break;
3972b41539d5SMatthias Ringwald             }
3973b41539d5SMatthias Ringwald 
3974136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3975136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
39768cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
39778cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
3978136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3979136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
3980136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3981c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3982136d331aSMatthias Ringwald                     }
39838cba5ca3SMatthias Ringwald                 } else {
3984c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
39858cba5ca3SMatthias Ringwald                 }
3986136d331aSMatthias Ringwald                 break;
3987136d331aSMatthias Ringwald             }
3988136d331aSMatthias Ringwald #endif
39893deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
39903deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
39913deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
39923deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3993f3582630SMatthias 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);
39943deb3ec6SMatthias Ringwald             }
39953deb3ec6SMatthias Ringwald             break;
39963deb3ec6SMatthias Ringwald 
39973deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
39984c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
39993deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40003deb3ec6SMatthias Ringwald                 break;
40013deb3ec6SMatthias Ringwald             }
40023deb3ec6SMatthias Ringwald 
40033deb3ec6SMatthias Ringwald             // store s_confirm
40049c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4005192365feSMatthias Ringwald 
4006aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4007aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4008aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4009aa9b34e5SMatthias Ringwald                 break;
4010aa9b34e5SMatthias Ringwald             }
4011aa9b34e5SMatthias Ringwald 
4012192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4013192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4014192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4015192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4016192365feSMatthias Ringwald             }
4017192365feSMatthias Ringwald #endif
40183deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
40193deb3ec6SMatthias Ringwald             break;
40203deb3ec6SMatthias Ringwald 
40213deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
40224c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
40233deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40243deb3ec6SMatthias Ringwald                 break;;
40253deb3ec6SMatthias Ringwald             }
40263deb3ec6SMatthias Ringwald 
40273deb3ec6SMatthias Ringwald             // received random value
40289c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
40293deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
40303deb3ec6SMatthias Ringwald             break;
403142134bc6SMatthias Ringwald #endif
40323deb3ec6SMatthias Ringwald 
403342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
40343deb3ec6SMatthias Ringwald         // Responder
40353deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
40363deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
40373deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
40384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
40393deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40403deb3ec6SMatthias Ringwald                 break;;
40413deb3ec6SMatthias Ringwald             }
40423deb3ec6SMatthias Ringwald 
40433deb3ec6SMatthias Ringwald             // store pairing request
4044212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4045212d735eSMatthias Ringwald 
4046212d735eSMatthias Ringwald             // check if IRK completed
4047212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4048212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4049212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
40503deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
40513deb3ec6SMatthias Ringwald                     break;
4052212d735eSMatthias Ringwald                 default:
4053212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4054212d735eSMatthias Ringwald                     break;
4055212d735eSMatthias Ringwald             }
4056212d735eSMatthias Ringwald             break;
405742134bc6SMatthias Ringwald #endif
40583deb3ec6SMatthias Ringwald 
405927c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4060c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
40614c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
406227c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
406327c32905SMatthias Ringwald                 break;
406427c32905SMatthias Ringwald             }
4065bccf5e67SMatthias Ringwald 
4066e53be891SMatthias Ringwald             // store public key for DH Key calculation
4067fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4068fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4069bccf5e67SMatthias Ringwald 
407002658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
407102658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
407202658749SMatthias Ringwald                 log_info("Remote PK matches ours");
407302658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
407402658749SMatthias Ringwald                 break;
407502658749SMatthias Ringwald             }
407602658749SMatthias Ringwald 
4077d1a1f6a4SMatthias Ringwald             // validate public key
4078d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
40799305033eSMatthias Ringwald             if (err != 0){
408002658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4081349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4082bccf5e67SMatthias Ringwald                 break;
4083bccf5e67SMatthias Ringwald             }
4084891bb64aSMatthias Ringwald 
4085d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4086f3582630SMatthias 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);
40873cf37b8cSMatthias Ringwald 
408865a9a04eSMatthias Ringwald 
408965a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
409042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4091136d331aSMatthias Ringwald                 // responder
4092c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4093136d331aSMatthias Ringwald             } else {
4094136d331aSMatthias Ringwald                 // initiator
4095a1e31e9cSMatthias Ringwald                 // stk generation method
4096a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4097a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4098a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
409947fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4100c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4101a1e31e9cSMatthias Ringwald                         break;
4102a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
410307036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
410407036a04SMatthias Ringwald                         break;
410507036a04SMatthias Ringwald                     case PK_INIT_INPUT:
410647fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
410707036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
410807036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
410907036a04SMatthias Ringwald                             break;
411007036a04SMatthias Ringwald                         }
4111b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4112a1e31e9cSMatthias Ringwald                         break;
4113a1e31e9cSMatthias Ringwald                     case OOB:
4114d1a1f6a4SMatthias Ringwald                         // generate Nx
41154acf7b7bSMatthias Ringwald                         log_info("Generate Na");
41166ca80073SMatthias 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);
4117a1e31e9cSMatthias Ringwald                         break;
41187bbeb3adSMilanka Ringwald                     default:
41197bbeb3adSMilanka Ringwald                         btstack_assert(false);
41207bbeb3adSMilanka Ringwald                         break;
4121a1e31e9cSMatthias Ringwald                 }
4122136d331aSMatthias Ringwald             }
412327c32905SMatthias Ringwald             break;
4124e53be891SMatthias Ringwald 
4125c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
41264c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
412745a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
412845a61d50SMatthias Ringwald                 break;
412945a61d50SMatthias Ringwald             }
413045a61d50SMatthias Ringwald             // received confirm value
413145a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
413245a61d50SMatthias Ringwald 
4133192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4134192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4135192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4136192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4137192365feSMatthias Ringwald             }
4138192365feSMatthias Ringwald #endif
413942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
414045a61d50SMatthias Ringwald                 // responder
414107036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
414207036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
414307036a04SMatthias Ringwald                         // still waiting for passkey
414407036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
414507036a04SMatthias Ringwald                         break;
414607036a04SMatthias Ringwald                     }
414707036a04SMatthias Ringwald                 }
4148b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
414945a61d50SMatthias Ringwald             } else {
415045a61d50SMatthias Ringwald                 // initiator
4151945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
41526ca80073SMatthias 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);
4153f1c1783eSMatthias Ringwald                 } else {
4154c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
415545a61d50SMatthias Ringwald                 }
4156f1c1783eSMatthias Ringwald             }
415745a61d50SMatthias Ringwald             break;
415845a61d50SMatthias Ringwald 
4159c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
41604c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4161e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4162136d331aSMatthias Ringwald                 break;
4163e53be891SMatthias Ringwald             }
4164e53be891SMatthias Ringwald 
4165e53be891SMatthias Ringwald             // received random value
4166e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4167e53be891SMatthias Ringwald 
41685a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4169ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4170d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4171d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4172d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
417365a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4174d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4175688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4176ae451ec5SMatthias Ringwald                  break;
41775a293e6eSMatthias Ringwald             }
41786f52a196SMatthias Ringwald 
41794acf7b7bSMatthias Ringwald             // OOB
41804acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
41814acf7b7bSMatthias Ringwald 
41824acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
41834acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
41844acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
41854ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
41864acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
41874acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
41884acf7b7bSMatthias Ringwald                     } else {
41896535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
41904acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
41914acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
41924acf7b7bSMatthias Ringwald                     }
41934acf7b7bSMatthias Ringwald                 }  else {
41944ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
41954acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
41964acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
41974acf7b7bSMatthias Ringwald                     } else {
41986535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
41994acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
42004acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
42014acf7b7bSMatthias Ringwald                     }
42024acf7b7bSMatthias Ringwald                 }
42034acf7b7bSMatthias Ringwald 
4204a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
42054acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4206a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4207a680ba6bSMatthias Ringwald                      break;
4208a680ba6bSMatthias Ringwald                 }
42094acf7b7bSMatthias Ringwald             }
4210a680ba6bSMatthias Ringwald 
4211a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4212688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4213e53be891SMatthias Ringwald             break;
4214e53be891SMatthias Ringwald 
4215901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4216901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
42173cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4218901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4219901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4220901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4221901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4222901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4223901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4224901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4225c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4226901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4227d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
42284c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4229e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4230e53be891SMatthias Ringwald                 break;
4231e53be891SMatthias Ringwald             }
4232e53be891SMatthias Ringwald             // store DHKey Check
4233901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4234e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4235446a8c36SMatthias Ringwald 
4236901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4237901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4238019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4239bd57ffebSMatthias Ringwald             }
4240bd57ffebSMatthias Ringwald             break;
424127c32905SMatthias Ringwald #endif
424227c32905SMatthias Ringwald 
424342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42443deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
42454c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42463deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
424727c32905SMatthias Ringwald                 break;
42483deb3ec6SMatthias Ringwald             }
42493deb3ec6SMatthias Ringwald 
42503deb3ec6SMatthias Ringwald             // received confirm value
42519c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
42523deb3ec6SMatthias Ringwald 
4253192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4254192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4255192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4256192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4257192365feSMatthias Ringwald             }
4258192365feSMatthias Ringwald #endif
42593deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
42603deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
42615611a760SMatthias 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);
42623deb3ec6SMatthias Ringwald             }
42633deb3ec6SMatthias Ringwald 
42643deb3ec6SMatthias Ringwald             // handle user cancel pairing?
42653deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4266f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
42673deb3ec6SMatthias Ringwald                 break;
42683deb3ec6SMatthias Ringwald             }
42693deb3ec6SMatthias Ringwald 
42703deb3ec6SMatthias Ringwald             // wait for user action?
42713deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
42723deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42733deb3ec6SMatthias Ringwald                 break;
42743deb3ec6SMatthias Ringwald             }
42753deb3ec6SMatthias Ringwald 
42763deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4277f3582630SMatthias 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);
42783deb3ec6SMatthias Ringwald             break;
42793deb3ec6SMatthias Ringwald 
42803deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
42814c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42823deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42833deb3ec6SMatthias Ringwald                 break;;
42843deb3ec6SMatthias Ringwald             }
42853deb3ec6SMatthias Ringwald 
42863deb3ec6SMatthias Ringwald             // received random value
42879c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42883deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42893deb3ec6SMatthias Ringwald             break;
429042134bc6SMatthias Ringwald #endif
42913deb3ec6SMatthias Ringwald 
42923deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
42934c1d1092SMatthias Ringwald             switch(sm_pdu_code){
42943deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
42953deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
42969c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
42973deb3ec6SMatthias Ringwald                     break;
42983deb3ec6SMatthias Ringwald 
42993deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
43003deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4301f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
43029c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
43033deb3ec6SMatthias Ringwald                     break;
43043deb3ec6SMatthias Ringwald 
43053deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
43063deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
43079c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
43083deb3ec6SMatthias Ringwald                     break;
43093deb3ec6SMatthias Ringwald 
43103deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
43113deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
43123deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4313724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
43143deb3ec6SMatthias Ringwald                     break;
43153deb3ec6SMatthias Ringwald 
43163deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
43173deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
43189c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
43193deb3ec6SMatthias Ringwald                     break;
43203deb3ec6SMatthias Ringwald                 default:
43213deb3ec6SMatthias Ringwald                     // Unexpected PDU
43223deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
43233deb3ec6SMatthias Ringwald                     break;
43243deb3ec6SMatthias Ringwald             }
43253deb3ec6SMatthias Ringwald             // done with key distribution?
43263deb3ec6SMatthias Ringwald             if (sm_key_distribution_all_received(sm_conn)){
43273deb3ec6SMatthias Ringwald 
43283deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
43293deb3ec6SMatthias Ringwald 
433042134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43316f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
43323deb3ec6SMatthias Ringwald                 } else {
4333625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4334625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4335bbf8db22SMatthias Ringwald                     } else {
4336f3582630SMatthias 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);
4337625f00b2SMatthias Ringwald                     }
43383deb3ec6SMatthias Ringwald                 }
43393deb3ec6SMatthias Ringwald             }
43403deb3ec6SMatthias Ringwald             break;
43413deb3ec6SMatthias Ringwald         default:
43423deb3ec6SMatthias Ringwald             // Unexpected PDU
43433deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
43442d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
43453deb3ec6SMatthias Ringwald             break;
43463deb3ec6SMatthias Ringwald     }
43473deb3ec6SMatthias Ringwald 
434870b44dd4SMatthias Ringwald     // try to send next pdu
434970b44dd4SMatthias Ringwald     sm_trigger_run();
43503deb3ec6SMatthias Ringwald }
43513deb3ec6SMatthias Ringwald 
43523deb3ec6SMatthias Ringwald // Security Manager Client API
4353a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
43543deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
43553deb3ec6SMatthias Ringwald }
43563deb3ec6SMatthias Ringwald 
43574acf7b7bSMatthias 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)){
4358a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4359a680ba6bSMatthias Ringwald }
4360a680ba6bSMatthias Ringwald 
436189a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
436289a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
436389a78d34SMatthias Ringwald }
436489a78d34SMatthias Ringwald 
43653deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
43663deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
43673deb3ec6SMatthias Ringwald }
43683deb3ec6SMatthias Ringwald 
43693deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
43703deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
43713deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
43723deb3ec6SMatthias Ringwald }
43733deb3ec6SMatthias Ringwald 
43743deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
437598d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
437698d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
437798d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
437898d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
437998d95509SMatthias Ringwald     }
438098d95509SMatthias Ringwald #endif
43813deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
43823deb3ec6SMatthias Ringwald }
43833deb3ec6SMatthias Ringwald 
43843deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
43853deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
43863deb3ec6SMatthias Ringwald }
43873deb3ec6SMatthias Ringwald 
438842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43893deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
43903deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
43913deb3ec6SMatthias Ringwald }
439242134bc6SMatthias Ringwald #endif
43933deb3ec6SMatthias Ringwald 
43943deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
43956535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
43963deb3ec6SMatthias Ringwald }
43973deb3ec6SMatthias Ringwald 
43983deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
43996535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
44003deb3ec6SMatthias Ringwald }
44013deb3ec6SMatthias Ringwald 
44023deb3ec6SMatthias Ringwald // Testing support only
44033deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
44046535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4405103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4406841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
44073deb3ec6SMatthias Ringwald }
44083deb3ec6SMatthias Ringwald 
44093deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4410841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
44113deb3ec6SMatthias Ringwald }
44123deb3ec6SMatthias Ringwald 
4413d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4414d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4415d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4416d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
441734b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
441870b44dd4SMatthias Ringwald     sm_trigger_run();
4419d1a1f6a4SMatthias Ringwald }
4420674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
442134b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4422674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4423674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4424674e5b4aSMatthias Ringwald }
4425d1a1f6a4SMatthias Ringwald #endif
4426d1a1f6a4SMatthias Ringwald 
4427192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4428192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4429192365feSMatthias Ringwald     test_pairing_failure = reason;
4430192365feSMatthias Ringwald }
4431192365feSMatthias Ringwald #endif
4432192365feSMatthias Ringwald 
44333deb3ec6SMatthias Ringwald void sm_init(void){
44342d2d4d3cSMatthias Ringwald 
44352d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
44362d2d4d3cSMatthias Ringwald 
4437899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4438899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4439899e6e02SMatthias Ringwald 
44403deb3ec6SMatthias Ringwald     // defaults
44413deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
44423deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4443b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4444b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4445b4343428SMatthias Ringwald 
44463deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
44473deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
44483deb3ec6SMatthias Ringwald 
44495ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
44501979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4451caf15bf3SMatthias Ringwald 
4452d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4453d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
44547a766ebfSMatthias Ringwald #endif
44558d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4456fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
44573deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
44583deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
44593deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
44603deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
44613deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
44623deb3ec6SMatthias Ringwald 
44633deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
44647149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
44653deb3ec6SMatthias Ringwald 
4466841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
44673deb3ec6SMatthias Ringwald 
446884c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
446984c0c5c7SMatthias Ringwald 
4470e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4471e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4472e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4473e03e489aSMatthias Ringwald 
4474d1a1f6a4SMatthias Ringwald     //
4475d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4476d1a1f6a4SMatthias Ringwald 
447751bd74d1SMatthias Ringwald     // init le_device_db
447851bd74d1SMatthias Ringwald     le_device_db_init();
447951bd74d1SMatthias Ringwald 
4480b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4481e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
448227c32905SMatthias Ringwald 
448309e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4484674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4485a3aba2f9SMatthias Ringwald #endif
44862d2d4d3cSMatthias Ringwald 
44872d2d4d3cSMatthias Ringwald     sm_initialized = true;
44883deb3ec6SMatthias Ringwald }
44893deb3ec6SMatthias Ringwald 
449015537ea4SMatthias Ringwald void sm_deinit(void){
449115537ea4SMatthias Ringwald     sm_initialized = false;
449215537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
449315537ea4SMatthias Ringwald }
449415537ea4SMatthias Ringwald 
44954b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
44964b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4497caf15bf3SMatthias Ringwald }
4498caf15bf3SMatthias Ringwald 
44996c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
45001979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
45016c39055aSMatthias Ringwald }
45026c39055aSMatthias Ringwald 
4503711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4504711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
45053deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
45063deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
45073deb3ec6SMatthias Ringwald }
45083deb3ec6SMatthias Ringwald 
45096bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4510711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4511711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45123deb3ec6SMatthias Ringwald     if (!sm_conn) return;
45136bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
45146bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
45153deb3ec6SMatthias Ringwald }
45163deb3ec6SMatthias Ringwald 
45173deb3ec6SMatthias Ringwald // request pairing
4518711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4519711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45203deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45213deb3ec6SMatthias Ringwald 
45227af5dcd5SMatthias Ringwald     bool have_ltk;
45237af5dcd5SMatthias Ringwald     uint8_t ltk[16];
45243deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
452542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
452624c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
452724c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
452824c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
45297af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45307af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45317af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
45327af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
45337af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
45347af5dcd5SMatthias Ringwald                         if (have_ltk){
45357af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
453624c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45377af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
45387af5dcd5SMatthias Ringwald                             break;
45397af5dcd5SMatthias Ringwald                         }
45407af5dcd5SMatthias Ringwald                         /* fall through */
45417af5dcd5SMatthias Ringwald 
45427af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45437af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45447af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45457af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
45467af5dcd5SMatthias Ringwald                         break;
45477af5dcd5SMatthias Ringwald                     default:
45487af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
45497af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45507af5dcd5SMatthias Ringwald                         break;
45517af5dcd5SMatthias Ringwald                 }
455224c20dc4SMatthias Ringwald                 break;
455324c20dc4SMatthias Ringwald             default:
455424c20dc4SMatthias Ringwald                 break;
455524c20dc4SMatthias Ringwald         }
45563deb3ec6SMatthias Ringwald     } else {
45573deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4558175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4559175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
45603deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45613deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45623dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4563f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4564f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4565f53ec649SMatthias Ringwald                         if (have_ltk){
4566c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
45675567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4568c245ca32SMatthias Ringwald                             break;
4569f53ec649SMatthias Ringwald                         }
4570cf373d3aSMatthias Ringwald                         /* fall through */
4571c245ca32SMatthias Ringwald 
457234c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45733deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
45743deb3ec6SMatthias Ringwald                         break;
45753deb3ec6SMatthias Ringwald                     default:
4576d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
457709ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45783deb3ec6SMatthias Ringwald                         break;
45793deb3ec6SMatthias Ringwald                 }
4580175b7faaSMatthias Ringwald                 break;
4581cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4582cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4583cb6d7eb0SMatthias Ringwald                 break;
4584175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
458509ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4586175b7faaSMatthias Ringwald                 break;
4587175b7faaSMatthias Ringwald             default:
4588175b7faaSMatthias Ringwald                 break;
45893deb3ec6SMatthias Ringwald         }
45903deb3ec6SMatthias Ringwald     }
459170b44dd4SMatthias Ringwald     sm_trigger_run();
45923deb3ec6SMatthias Ringwald }
45933deb3ec6SMatthias Ringwald 
45943deb3ec6SMatthias Ringwald // called by client app on authorization request
4595711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4596711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45973deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45983deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4599589f5a99SMatthias 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);
46003deb3ec6SMatthias Ringwald }
46013deb3ec6SMatthias Ringwald 
4602711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4603711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46043deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46053deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4606589f5a99SMatthias 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);
46073deb3ec6SMatthias Ringwald }
46083deb3ec6SMatthias Ringwald 
46093deb3ec6SMatthias Ringwald // GAP Bonding API
46103deb3ec6SMatthias Ringwald 
4611711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4612711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46133deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46143deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
46150af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
46160af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
46170af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46180af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
46190af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
46200af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
46210af429c6SMatthias Ringwald #endif
46220af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4623de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4624de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4625de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
462647fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
46270af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4628de2fd182SMatthias Ringwald                     break;
462947fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4630de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4631de2fd182SMatthias Ringwald                     break;
4632de2fd182SMatthias Ringwald                 case JUST_WORKS:
4633de2fd182SMatthias Ringwald                 case OOB:
4634de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4635de2fd182SMatthias Ringwald                     break;
46367bbeb3adSMilanka Ringwald                 default:
46377bbeb3adSMilanka Ringwald                     btstack_assert(false);
46387bbeb3adSMilanka Ringwald                     break;
4639de2fd182SMatthias Ringwald             }
46400af429c6SMatthias Ringwald             break;
46410af429c6SMatthias Ringwald         default:
46420af429c6SMatthias Ringwald             break;
46433deb3ec6SMatthias Ringwald     }
464470b44dd4SMatthias Ringwald     sm_trigger_run();
46453deb3ec6SMatthias Ringwald }
46463deb3ec6SMatthias Ringwald 
4647711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4648711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46493deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46503deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
46513deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4652136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4653c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4654bbf8db22SMatthias Ringwald         } else {
4655f3582630SMatthias 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);
4656136d331aSMatthias Ringwald         }
46573deb3ec6SMatthias Ringwald     }
46580346c37cSMatthias Ringwald 
46590346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4660c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4661dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4662446a8c36SMatthias Ringwald     }
46630346c37cSMatthias Ringwald #endif
46640346c37cSMatthias Ringwald 
466570b44dd4SMatthias Ringwald     sm_trigger_run();
46663deb3ec6SMatthias Ringwald }
46673deb3ec6SMatthias Ringwald 
4668c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4669c8c46d51SMatthias Ringwald     // for now, it's the same
4670c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4671c8c46d51SMatthias Ringwald }
4672c8c46d51SMatthias Ringwald 
4673711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4674711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46753deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46763deb3ec6SMatthias Ringwald     sm_reset_tk();
4677f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
46783deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
46793deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4680f3582630SMatthias 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);
46813deb3ec6SMatthias Ringwald     }
46821c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46836535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
46846535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
468507036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
468607036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
468707036a04SMatthias Ringwald     }
46881c516d8fSMatthias Ringwald #endif
468970b44dd4SMatthias Ringwald     sm_trigger_run();
46903deb3ec6SMatthias Ringwald }
46913deb3ec6SMatthias Ringwald 
46923d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
46933d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46943d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46953d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4696dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
46974ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4698dd4a08fbSMatthias Ringwald     switch (action){
4699dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4700dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
47014ea43905SMatthias Ringwald             flags |= (1u << action);
4702dd4a08fbSMatthias Ringwald             break;
4703dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4704dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
47054ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4706dd4a08fbSMatthias Ringwald             break;
4707dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
47084ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4709dd4a08fbSMatthias Ringwald                 // erase actions queued
4710dd4a08fbSMatthias Ringwald                 num_actions--;
47114ea43905SMatthias Ringwald                 if (num_actions == 0u){
4712dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47134ea43905SMatthias Ringwald                     flags &= 0x19u;
4714dd4a08fbSMatthias Ringwald                 }
4715dd4a08fbSMatthias Ringwald                 break;
4716dd4a08fbSMatthias Ringwald             }
4717dd4a08fbSMatthias Ringwald             num_actions++;
47184ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4719dd4a08fbSMatthias Ringwald             break;
4720dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
47214ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4722dd4a08fbSMatthias Ringwald                 // enter actions queued
4723dd4a08fbSMatthias Ringwald                 num_actions--;
47244ea43905SMatthias Ringwald                 if (num_actions == 0u){
4725dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47264ea43905SMatthias Ringwald                     flags &= 0x19u;
4727dd4a08fbSMatthias Ringwald                 }
4728dd4a08fbSMatthias Ringwald                 break;
4729dd4a08fbSMatthias Ringwald             }
4730dd4a08fbSMatthias Ringwald             num_actions++;
47314ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4732dd4a08fbSMatthias Ringwald             break;
4733dd4a08fbSMatthias Ringwald         default:
4734dd4a08fbSMatthias Ringwald             break;
4735dd4a08fbSMatthias Ringwald     }
4736dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
473770b44dd4SMatthias Ringwald     sm_trigger_run();
47383d7fe1e9SMatthias Ringwald }
47393d7fe1e9SMatthias Ringwald 
4740c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4741d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
4742d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4743d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
474470b44dd4SMatthias Ringwald     sm_trigger_run();
4745d1a1f6a4SMatthias Ringwald }
4746c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
47478334d3d8SMatthias Ringwald 
47488334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
47498334d3d8SMatthias Ringwald 
4750c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4751c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
4752d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4753d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4754c59d0c92SMatthias Ringwald     return 0;
4755c59d0c92SMatthias Ringwald }
4756c59d0c92SMatthias Ringwald #endif
4757c59d0c92SMatthias Ringwald 
47583deb3ec6SMatthias Ringwald /**
4759ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
4760ba394633SMatthias Ringwald  * @param con_handle
4761ba394633SMatthias Ringwald  * @return irk_lookup_state_t
4762ba394633SMatthias Ringwald  */
4763ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4764ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4765ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
4766ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
4767ba394633SMatthias Ringwald }
4768ba394633SMatthias Ringwald 
4769ba394633SMatthias Ringwald /**
47703deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
47713deb3ec6SMatthias Ringwald  * @param handle
47723deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
47733deb3ec6SMatthias Ringwald  */
4774711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
4775711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47763deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
47773deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
47783deb3ec6SMatthias Ringwald }
47793deb3ec6SMatthias Ringwald 
47808f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
478147ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
478247ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
478347ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
478447ba4de1SMatthias Ringwald             return 0;
478547ba4de1SMatthias Ringwald         default:
47868f57b085SMatthias Ringwald             return 1;
47878f57b085SMatthias Ringwald     }
478847ba4de1SMatthias Ringwald }
4789d70217a2SMatthias Ringwald 
479033373e40SMatthias Ringwald static uint8_t own_address_type(void){
4791b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
4792b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4793b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
4794b95a5a35SMatthias Ringwald         default:
4795b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
4796b95a5a35SMatthias Ringwald     }
479733373e40SMatthias Ringwald }
47988f57b085SMatthias Ringwald 
47993deb3ec6SMatthias Ringwald // GAP LE API
48003deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
48013deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48023deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
4803b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
48048f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48053deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48063deb3ec6SMatthias Ringwald     gap_random_address_trigger();
48073deb3ec6SMatthias Ringwald }
48083deb3ec6SMatthias Ringwald 
48093deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
48103deb3ec6SMatthias Ringwald     return gap_random_adress_type;
48113deb3ec6SMatthias Ringwald }
48123deb3ec6SMatthias Ringwald 
48133deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
48143deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
48158f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48163deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48173deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48183deb3ec6SMatthias Ringwald }
48193deb3ec6SMatthias Ringwald 
4820667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
48218f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
48226535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
48237e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
482470b44dd4SMatthias Ringwald     sm_trigger_run();
48257e252622SMatthias Ringwald }
48267e252622SMatthias Ringwald 
4827d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48283deb3ec6SMatthias Ringwald /*
48293deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
48303deb3ec6SMatthias Ringwald  * @param adv_int_min
48313deb3ec6SMatthias Ringwald  * @param adv_int_max
48323deb3ec6SMatthias Ringwald  * @param adv_type
48333deb3ec6SMatthias Ringwald  * @param direct_address_type
48343deb3ec6SMatthias Ringwald  * @param direct_address
48353deb3ec6SMatthias Ringwald  * @param channel_map
48363deb3ec6SMatthias Ringwald  * @param filter_policy
48373deb3ec6SMatthias Ringwald  *
48383deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
48393deb3ec6SMatthias Ringwald  */
48403deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
48413deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4842b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
48433deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
48443deb3ec6SMatthias Ringwald }
4845d70217a2SMatthias Ringwald #endif
4846dcd6c9b5SMatthias Ringwald 
4847dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4848dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4849dcd6c9b5SMatthias Ringwald      // wrong connection
4850dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
4851dcd6c9b5SMatthias Ringwald     // already encrypted
4852dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
4853dcd6c9b5SMatthias Ringwald     // irk status?
4854dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
4855dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
4856dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
4857dcd6c9b5SMatthias Ringwald             return 0;
4858dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
4859dcd6c9b5SMatthias Ringwald             break;
4860dcd6c9b5SMatthias Ringwald         default:
4861dcd6c9b5SMatthias Ringwald             // IR Lookup pending
4862dcd6c9b5SMatthias Ringwald             return 1;
4863dcd6c9b5SMatthias Ringwald     }
4864f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
4865f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
4866b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
4867b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
4868b15d5ceaSMatthias Ringwald     } else {
4869dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4870dcd6c9b5SMatthias Ringwald     }
4871b15d5ceaSMatthias Ringwald }
48723cdbe9dbSMatthias Ringwald 
48733cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
48743cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
48753cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
48763cdbe9dbSMatthias Ringwald #else
48773cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
48783cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
48793cdbe9dbSMatthias Ringwald #endif
48803cdbe9dbSMatthias Ringwald }
4881052bbdc5SMatthias Ringwald 
4882052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
4883052bbdc5SMatthias Ringwald     return sm_persistent_irk;
4884052bbdc5SMatthias Ringwald }
48854f384501SMatthias Ringwald 
48864f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
48874f384501SMatthias Ringwald     uint16_t i;
48884f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
48894f384501SMatthias Ringwald         bd_addr_t entry_address;
48904f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
48914f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
48924f384501SMatthias Ringwald         // skip unused entries
48934f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
48944f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
48954f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
48964f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
48974f384501SMatthias Ringwald #endif
48984f384501SMatthias Ringwald             le_device_db_remove(i);
48994f384501SMatthias Ringwald             break;
49004f384501SMatthias Ringwald         }
49014f384501SMatthias Ringwald     }
49024f384501SMatthias Ringwald }
4903