xref: /btstack/src/ble/sm.c (revision 61d1a45e7d0c1f3965fbf939af71fa1d59fd6895)
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
373e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
374e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
375e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
376e0a03c85SMatthias Ringwald #endif
3773deb3ec6SMatthias Ringwald } sm_setup_context_t;
3783deb3ec6SMatthias Ringwald 
3793deb3ec6SMatthias Ringwald //
3803deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3813deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3823deb3ec6SMatthias Ringwald 
3833deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3847149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3853deb3ec6SMatthias Ringwald 
3863deb3ec6SMatthias Ringwald // @returns 1 if oob data is available
3873deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3883deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3894acf7b7bSMatthias 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);
3903deb3ec6SMatthias Ringwald 
3913deb3ec6SMatthias Ringwald static void sm_run(void);
392711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
393711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39477e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39577e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
39677e2e5edSMatthias Ringwald #endif
3973deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3983deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4092a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4122a526f21SMatthias Ringwald #endif
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
415d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
416d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
417d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4186d80b495SMatthias Ringwald static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash));
41934b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4206ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4216ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4222a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
423d1a1f6a4SMatthias Ringwald #endif
4240ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4253deb3ec6SMatthias Ringwald 
4263deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4273deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4283deb3ec6SMatthias Ringwald }
4293deb3ec6SMatthias Ringwald 
4301fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4311fbd72c5SMatthias Ringwald //     return packet[0];
4321fbd72c5SMatthias Ringwald // }
4331fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4341fbd72c5SMatthias Ringwald     return packet[1];
4351fbd72c5SMatthias Ringwald }
4361fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4371fbd72c5SMatthias Ringwald     return packet[2];
4381fbd72c5SMatthias Ringwald }
4391fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4401fbd72c5SMatthias Ringwald     return packet[3];
4411fbd72c5SMatthias Ringwald }
4421fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4431fbd72c5SMatthias Ringwald     return packet[4];
4441fbd72c5SMatthias Ringwald }
4451fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4461fbd72c5SMatthias Ringwald     return packet[5];
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4491fbd72c5SMatthias Ringwald     return packet[6];
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald 
4521fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4531fbd72c5SMatthias Ringwald     packet[0] = code;
4541fbd72c5SMatthias Ringwald }
4551fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4561fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4571fbd72c5SMatthias Ringwald }
4581fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4591fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4601fbd72c5SMatthias Ringwald }
4611fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4621fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4631fbd72c5SMatthias Ringwald }
4641fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4651fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4661fbd72c5SMatthias Ringwald }
4671fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4681fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4691fbd72c5SMatthias Ringwald }
4701fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4711fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4721fbd72c5SMatthias Ringwald }
4731fbd72c5SMatthias Ringwald 
4743deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4751979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4763deb3ec6SMatthias Ringwald     int i;
4773764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47884c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4791979f09cSMatthias Ringwald             return false;
48084c0c5c7SMatthias Ringwald         }
4813deb3ec6SMatthias Ringwald     }
4821979f09cSMatthias Ringwald     return true;
4833deb3ec6SMatthias Ringwald }
4843deb3ec6SMatthias Ringwald 
4851979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4863764b551SMatthias Ringwald     return sm_is_null(random, 8);
4873764b551SMatthias Ringwald }
4883764b551SMatthias Ringwald 
4891979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4903764b551SMatthias Ringwald     return sm_is_null(key, 16);
4913764b551SMatthias Ringwald }
4923764b551SMatthias Ringwald 
49370b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49470b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49570b44dd4SMatthias Ringwald 	UNUSED(ts);
49670b44dd4SMatthias Ringwald 	sm_run();
49770b44dd4SMatthias Ringwald }
49870b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4992d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
50084c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50170b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50270b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50370b44dd4SMatthias Ringwald }
50470b44dd4SMatthias Ringwald 
5053deb3ec6SMatthias Ringwald // Key utils
5063deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5073deb3ec6SMatthias Ringwald     int i;
5083deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5093deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5103deb3ec6SMatthias Ringwald     }
5113deb3ec6SMatthias Ringwald }
5123deb3ec6SMatthias Ringwald 
5133deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5143deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5153deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5163deb3ec6SMatthias Ringwald     int i;
5173deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5183deb3ec6SMatthias Ringwald         key[15-i] = 0;
5193deb3ec6SMatthias Ringwald     }
5203deb3ec6SMatthias Ringwald }
5213deb3ec6SMatthias Ringwald 
522899e6e02SMatthias Ringwald // ER / IR checks
52321045273SMatthias Ringwald static void sm_er_ir_set_default(void){
524899e6e02SMatthias Ringwald     int i;
525899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
526899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
527899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
528899e6e02SMatthias Ringwald     }
529899e6e02SMatthias Ringwald }
530899e6e02SMatthias Ringwald 
531899e6e02SMatthias Ringwald static int sm_er_is_default(void){
532899e6e02SMatthias Ringwald     int i;
533899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
534899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
535899e6e02SMatthias Ringwald     }
536899e6e02SMatthias Ringwald     return 1;
537899e6e02SMatthias Ringwald }
538899e6e02SMatthias Ringwald 
539899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
540899e6e02SMatthias Ringwald     int i;
541899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
542899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
543899e6e02SMatthias Ringwald     }
544899e6e02SMatthias Ringwald     return 1;
545899e6e02SMatthias Ringwald }
546899e6e02SMatthias Ringwald 
54773102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54873102768SMatthias Ringwald     UNUSED(channel);
54973102768SMatthias Ringwald 
55073102768SMatthias Ringwald     // log event
55173102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55273102768SMatthias Ringwald     // dispatch to all event handlers
55373102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55473102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55573102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55673102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55773102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55873102768SMatthias Ringwald     }
55973102768SMatthias Ringwald }
56073102768SMatthias Ringwald 
56173102768SMatthias Ringwald static void sm_setup_event_base(uint8_t * event, int event_size, uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56273102768SMatthias Ringwald     event[0] = type;
56373102768SMatthias Ringwald     event[1] = event_size - 2;
56473102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56573102768SMatthias Ringwald     event[4] = addr_type;
56673102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56773102768SMatthias Ringwald }
56873102768SMatthias Ringwald 
56973102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
57073102768SMatthias Ringwald     uint8_t event[11];
57173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57373102768SMatthias Ringwald }
57473102768SMatthias Ringwald 
57573102768SMatthias Ringwald static void sm_notify_client_passkey(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint32_t passkey){
57673102768SMatthias Ringwald     uint8_t event[15];
57773102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57873102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57973102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58073102768SMatthias Ringwald }
58173102768SMatthias Ringwald 
58273102768SMatthias Ringwald static void sm_notify_client_index(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint16_t index){
58373102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58473102768SMatthias Ringwald     bd_addr_t identity_address;
58573102768SMatthias Ringwald     int identity_address_type;
58673102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58773102768SMatthias Ringwald 
58873102768SMatthias Ringwald     uint8_t event[20];
58973102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59073102768SMatthias Ringwald     event[11] = identity_address_type;
59173102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
59273102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
59373102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59473102768SMatthias Ringwald }
59573102768SMatthias Ringwald 
59673102768SMatthias Ringwald static void sm_notify_client_status(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint8_t status){
59773102768SMatthias Ringwald     uint8_t event[12];
59873102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59973102768SMatthias Ringwald     event[11] = status;
60073102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
60173102768SMatthias Ringwald }
60273102768SMatthias Ringwald 
60373102768SMatthias Ringwald 
60473102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60573102768SMatthias Ringwald 
6063ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6073ab61f77SMatthias Ringwald 
6087b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60973102768SMatthias Ringwald 
61073102768SMatthias Ringwald     int       identity_addr_type;
61173102768SMatthias Ringwald     bd_addr_t identity_addr;
6123c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6133c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61473102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6153c0e26deSMatthias Ringwald     } else {
6163c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6173c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6183c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6193c0e26deSMatthias Ringwald     }
62073102768SMatthias Ringwald 
62173102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
62273102768SMatthias Ringwald }
62373102768SMatthias Ringwald 
62473102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62573102768SMatthias Ringwald 
62660be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62760be5b21SMatthias Ringwald 
6287b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62973102768SMatthias Ringwald 
63073102768SMatthias Ringwald     int       identity_addr_type;
63173102768SMatthias Ringwald     bd_addr_t identity_addr;
6323c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6333c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63473102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6353c0e26deSMatthias Ringwald     } else {
6363c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6373c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6383c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6393c0e26deSMatthias Ringwald     }
64073102768SMatthias Ringwald 
64173102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
64273102768SMatthias Ringwald }
64373102768SMatthias Ringwald 
644d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
645d3c12277SMatthias Ringwald 
646d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
647d3c12277SMatthias Ringwald 
648d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
649d3c12277SMatthias Ringwald 
650d3c12277SMatthias Ringwald     uint8_t event[11];
651d3c12277SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_STARTED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
652d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
653d3c12277SMatthias Ringwald }
654d3c12277SMatthias Ringwald 
6550ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
656f61072f5SMatthias Ringwald 
657d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
658d77906ffSMatthias Ringwald 
65969f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
66069f82ad8SMatthias Ringwald 
6610ccf6c9cSMatthias Ringwald     uint8_t event[13];
6620ccf6c9cSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_COMPLETE, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
6630ccf6c9cSMatthias Ringwald     event[11] = status;
6640ccf6c9cSMatthias Ringwald     event[12] = reason;
6650ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6660ccf6c9cSMatthias Ringwald }
6670ccf6c9cSMatthias Ringwald 
6683deb3ec6SMatthias Ringwald // SMP Timeout implementation
6693deb3ec6SMatthias Ringwald 
6703deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6713deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6723deb3ec6SMatthias Ringwald //
6733deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6743deb3ec6SMatthias Ringwald //
6753deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6763deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6773deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6783deb3ec6SMatthias Ringwald // established.
6793deb3ec6SMatthias Ringwald 
680ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6813deb3ec6SMatthias Ringwald     log_info("SM timeout");
682c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6833deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68468a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6850ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6863deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6873deb3ec6SMatthias Ringwald 
6883deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6893deb3ec6SMatthias Ringwald     sm_run();
6903deb3ec6SMatthias Ringwald }
6913deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
692528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
69391a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
694528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
695528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
696528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
699528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
7003deb3ec6SMatthias Ringwald }
7013deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
7023deb3ec6SMatthias Ringwald     sm_timeout_stop();
7033deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7043deb3ec6SMatthias Ringwald }
7053deb3ec6SMatthias Ringwald 
7063deb3ec6SMatthias Ringwald // end of sm timeout
7073deb3ec6SMatthias Ringwald 
7083deb3ec6SMatthias Ringwald // GAP Random Address updates
7093deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
710ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7113deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7123deb3ec6SMatthias Ringwald 
7133deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
714899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
715d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
716fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71770b44dd4SMatthias Ringwald     sm_trigger_run();
7183deb3ec6SMatthias Ringwald }
7193deb3ec6SMatthias Ringwald 
720ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7219ec2630cSMatthias Ringwald     UNUSED(timer);
7229ec2630cSMatthias Ringwald 
7233deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
724528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
725528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7263deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7273deb3ec6SMatthias Ringwald }
7283deb3ec6SMatthias Ringwald 
7293deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
730528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
731528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
732528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7333deb3ec6SMatthias Ringwald }
7343deb3ec6SMatthias Ringwald 
7353deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
736528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7373deb3ec6SMatthias Ringwald }
7383deb3ec6SMatthias Ringwald 
7393deb3ec6SMatthias Ringwald // ah(k,r) helper
7403deb3ec6SMatthias Ringwald // r = padding || r
7413deb3ec6SMatthias Ringwald // r - 24 bit value
7424a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7433deb3ec6SMatthias Ringwald     // r'= padding || r
7443deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7456535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7463deb3ec6SMatthias Ringwald }
7473deb3ec6SMatthias Ringwald 
7483deb3ec6SMatthias Ringwald // d1 helper
7493deb3ec6SMatthias Ringwald // d' = padding || r || d
7503deb3ec6SMatthias Ringwald // d,r - 16 bit values
7514a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7523deb3ec6SMatthias Ringwald     // d'= padding || r || d
7533deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
754f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
755f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7563deb3ec6SMatthias Ringwald }
7573deb3ec6SMatthias Ringwald 
7583deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7594a6806f3SMatthias Ringwald static void sm_c1_t1(sm_key_t r, uint8_t preq[7], uint8_t pres[7], uint8_t iat, uint8_t rat, uint8_t * t1){
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7623deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7633deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7643deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7653deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7663deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7673deb3ec6SMatthias Ringwald 
7683deb3ec6SMatthias Ringwald     sm_key_t p1;
7699c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7709c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7713deb3ec6SMatthias Ringwald     p1[14] = rat;
7723deb3ec6SMatthias Ringwald     p1[15] = iat;
7738314c363SMatthias Ringwald     log_info_key("p1", p1);
7748314c363SMatthias Ringwald     log_info_key("r", r);
7753deb3ec6SMatthias Ringwald 
7763deb3ec6SMatthias Ringwald     // t1 = r xor p1
7773deb3ec6SMatthias Ringwald     int i;
7783deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7793deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7803deb3ec6SMatthias Ringwald     }
7818314c363SMatthias Ringwald     log_info_key("t1", t1);
7823deb3ec6SMatthias Ringwald }
7833deb3ec6SMatthias Ringwald 
7843deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7854a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7863deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7873deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7883deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7893deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7903deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7913deb3ec6SMatthias Ringwald 
7923deb3ec6SMatthias Ringwald     sm_key_t p2;
7933deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7946535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7956535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7968314c363SMatthias Ringwald     log_info_key("p2", p2);
7973deb3ec6SMatthias Ringwald 
7983deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7993deb3ec6SMatthias Ringwald     int i;
8003deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
8013deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
8023deb3ec6SMatthias Ringwald     }
8038314c363SMatthias Ringwald     log_info_key("t3", t3);
8043deb3ec6SMatthias Ringwald }
8053deb3ec6SMatthias Ringwald 
8064a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8078314c363SMatthias Ringwald     log_info_key("r1", r1);
8088314c363SMatthias Ringwald     log_info_key("r2", r2);
8096535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8106535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8113deb3ec6SMatthias Ringwald }
8123deb3ec6SMatthias Ringwald 
813fbe050beSMatthias Ringwald 
8143deb3ec6SMatthias Ringwald // decide on stk generation based on
8153deb3ec6SMatthias Ringwald // - pairing request
8163deb3ec6SMatthias Ringwald // - io capabilities
8173deb3ec6SMatthias Ringwald // - OOB data availability
8183deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8193deb3ec6SMatthias Ringwald 
8208334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8218334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8228334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8238334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8248334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8258334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8278334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8288334d3d8SMatthias Ringwald     };
8298334d3d8SMatthias Ringwald 
8308334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8318334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8328334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8338334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8348334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8358334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8368334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8378334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8388334d3d8SMatthias Ringwald     };
8398334d3d8SMatthias Ringwald #endif
8408334d3d8SMatthias Ringwald 
8413deb3ec6SMatthias Ringwald     // default: just works
8423deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8433deb3ec6SMatthias Ringwald 
84427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84527c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84627c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8474ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84827c32905SMatthias Ringwald #else
84927c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
85027c32905SMatthias Ringwald #endif
85198d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
85227c32905SMatthias Ringwald 
85365a9a04eSMatthias Ringwald 
85465a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8551979f09cSMatthias Ringwald     bool use_oob;
85665a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85765a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85865a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8591979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
86065a9a04eSMatthias Ringwald     } else {
86165a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
86265a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8631979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
86465a9a04eSMatthias Ringwald     }
86565a9a04eSMatthias Ringwald     if (use_oob){
86665a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86765a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86865a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86965a9a04eSMatthias Ringwald         return;
87065a9a04eSMatthias Ringwald     }
87165a9a04eSMatthias Ringwald 
87227c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
87327c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87427c32905SMatthias Ringwald     // model shall be used.
8754ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8764ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87727c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87827c32905SMatthias Ringwald         return;
87927c32905SMatthias Ringwald     }
88027c32905SMatthias Ringwald 
8813deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8823deb3ec6SMatthias Ringwald     sm_reset_tk();
8833deb3ec6SMatthias Ringwald 
8843deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8858da2e96dSMatthias Ringwald     if ((sm_pairing_packet_get_io_capability(setup->sm_m_preq) > IO_CAPABILITY_KEYBOARD_DISPLAY) || (sm_pairing_packet_get_io_capability(setup->sm_s_pres) > IO_CAPABILITY_KEYBOARD_DISPLAY)){
8863deb3ec6SMatthias Ringwald         return;
8873deb3ec6SMatthias Ringwald     }
8883deb3ec6SMatthias Ringwald 
8893deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8903deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
89127c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
89227c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
89327c32905SMatthias Ringwald 
89427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
895c6b7cbd9SMatthias Ringwald     // table not define by default
89627c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89727c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89827c32905SMatthias Ringwald     }
89927c32905SMatthias Ringwald #endif
90027c32905SMatthias Ringwald     setup->sm_stk_generation_method = generation_method[sm_pairing_packet_get_io_capability(setup->sm_s_pres)][sm_pairing_packet_get_io_capability(setup->sm_m_preq)];
90127c32905SMatthias Ringwald 
9023deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
9031ad129beSMatthias Ringwald         sm_pairing_packet_get_io_capability(setup->sm_m_preq), sm_pairing_packet_get_io_capability(setup->sm_s_pres), setup->sm_stk_generation_method);
9043deb3ec6SMatthias Ringwald }
9053deb3ec6SMatthias Ringwald 
9063deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9073deb3ec6SMatthias Ringwald     int flags = 0;
9083deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9143deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9153deb3ec6SMatthias Ringwald     }
9163deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9173deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9183deb3ec6SMatthias Ringwald     }
9193deb3ec6SMatthias Ringwald     return flags;
9203deb3ec6SMatthias Ringwald }
9213deb3ec6SMatthias Ringwald 
9229a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9233deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9249a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9259a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
926715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9279790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
928715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9299790be5fSMatthias Ringwald #endif
9303deb3ec6SMatthias Ringwald }
9313deb3ec6SMatthias Ringwald 
9323deb3ec6SMatthias Ringwald // CSRK Key Lookup
9333deb3ec6SMatthias Ringwald 
9343deb3ec6SMatthias Ringwald 
9353deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9363deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9373deb3ec6SMatthias Ringwald }
9383deb3ec6SMatthias Ringwald 
939711e6c80SMatthias Ringwald static void sm_address_resolution_start_lookup(uint8_t addr_type, hci_con_handle_t con_handle, bd_addr_t addr, address_resolution_mode_t mode, void * context){
9406535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9413deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9423deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9433deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9443deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
945711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9463deb3ec6SMatthias Ringwald }
9473deb3ec6SMatthias Ringwald 
9483deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9493deb3ec6SMatthias Ringwald     // check if already in list
950665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9513deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
952665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
953665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
954665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9553deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9563deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9573deb3ec6SMatthias Ringwald         // already in list
9583deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9593deb3ec6SMatthias Ringwald     }
9603deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9613deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9623deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9636535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
964665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96570b44dd4SMatthias Ringwald     sm_trigger_run();
9663deb3ec6SMatthias Ringwald     return 0;
9673deb3ec6SMatthias Ringwald }
9683deb3ec6SMatthias Ringwald 
969d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
970d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
971514d35fcSMatthias Ringwald 
972d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
973d1a1f6a4SMatthias Ringwald     UNUSED(arg);
974d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
975d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97670b44dd4SMatthias Ringwald     sm_trigger_run();
9773deb3ec6SMatthias Ringwald }
978514d35fcSMatthias Ringwald 
9794dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9804ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9813deb3ec6SMatthias Ringwald }
9826d80b495SMatthias Ringwald #endif
9833deb3ec6SMatthias Ringwald 
9846d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
985514d35fcSMatthias Ringwald // generic cmac calculation
986d1a1f6a4SMatthias Ringwald static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash)){
987d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
988d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
989d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9903deb3ec6SMatthias Ringwald }
9917a766ebfSMatthias Ringwald #endif
9923deb3ec6SMatthias Ringwald 
993514d35fcSMatthias Ringwald // cmac for ATT Message signing
9947a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
995d1a1f6a4SMatthias Ringwald 
996d1a1f6a4SMatthias Ringwald static void sm_cmac_generator_start(const sm_key_t key, uint16_t message_len, uint8_t (*get_byte_callback)(uint16_t offset), void (*done_callback)(uint8_t * hash)){
997d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
998d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
999d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
1000d1a1f6a4SMatthias Ringwald }
1001d1a1f6a4SMatthias Ringwald 
10024dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
1003d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1004d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10054dfd504aSMatthias Ringwald         return 0;
10064dfd504aSMatthias Ringwald     }
10074dfd504aSMatthias Ringwald 
1008d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10094dfd504aSMatthias Ringwald 
1010d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10114dfd504aSMatthias Ringwald     if (offset < 3){
1012d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10134dfd504aSMatthias Ringwald     }
1014d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10154dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1016d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10174dfd504aSMatthias Ringwald     }
1018d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10194dfd504aSMatthias Ringwald }
10204dfd504aSMatthias Ringwald 
10214dfd504aSMatthias Ringwald void sm_cmac_signed_write_start(const sm_key_t k, uint8_t opcode, hci_con_handle_t con_handle, uint16_t message_len, const uint8_t * message, uint32_t sign_counter, void (*done_handler)(uint8_t * hash)){
1022514d35fcSMatthias Ringwald     // ATT Message Signing
1023d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1024d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1025d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1026514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1027d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1028d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1029d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10303deb3ec6SMatthias Ringwald }
10317a766ebfSMatthias Ringwald #endif
10323deb3ec6SMatthias Ringwald 
10333deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1034446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10353deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1036d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10373deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10383deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10403deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10415611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10423deb3ec6SMatthias Ringwald             } else {
1043c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10443deb3ec6SMatthias Ringwald             }
10453deb3ec6SMatthias Ringwald             break;
10463deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
104742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1048c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10493deb3ec6SMatthias Ringwald             } else {
10503deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10515611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10523deb3ec6SMatthias Ringwald             }
10533deb3ec6SMatthias Ringwald             break;
105447fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10553deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10565611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10573deb3ec6SMatthias Ringwald             break;
105847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1059446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1060c8c46d51SMatthias Ringwald             sm_notify_client_passkey(SM_EVENT_NUMERIC_COMPARISON_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
106127c32905SMatthias Ringwald             break;
10623deb3ec6SMatthias Ringwald         case JUST_WORKS:
10633deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10645611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_JUST_WORKS_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10653deb3ec6SMatthias Ringwald             break;
10663deb3ec6SMatthias Ringwald         case OOB:
10673deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10683deb3ec6SMatthias Ringwald             break;
10697bbeb3adSMilanka Ringwald         default:
10707bbeb3adSMilanka Ringwald             btstack_assert(false);
10717bbeb3adSMilanka Ringwald             break;
10723deb3ec6SMatthias Ringwald     }
10733deb3ec6SMatthias Ringwald }
10743deb3ec6SMatthias Ringwald 
1075*61d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
1076b2296177SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, bution_expected_set);
1077b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10783deb3ec6SMatthias Ringwald }
10793deb3ec6SMatthias Ringwald 
1080711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10817149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10823deb3ec6SMatthias Ringwald         sm_timeout_stop();
10837149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1084711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1085c085d9ffSMatthias Ringwald 
1086c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1087c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1088c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1089c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1090c085d9ffSMatthias Ringwald         }
1091c085d9ffSMatthias Ringwald #endif
10923deb3ec6SMatthias Ringwald     }
10933deb3ec6SMatthias Ringwald }
10943deb3ec6SMatthias Ringwald 
10957d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
10961dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
10970ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
10981dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
10991dca9d8aSMatthias Ringwald }
11001dca9d8aSMatthias Ringwald 
11013deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1102bb09604fSMatthias Ringwald 
1103bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11043deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1105bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1107bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1108bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1109bb09604fSMatthias Ringwald #endif
11107ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11117ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11127ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11137ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11147ece0eaaSMatthias Ringwald         }
11157ece0eaaSMatthias Ringwald #endif
11163deb3ec6SMatthias Ringwald     }
11173deb3ec6SMatthias Ringwald     return flags;
11183deb3ec6SMatthias Ringwald }
11193deb3ec6SMatthias Ringwald 
1120d7471931SMatthias Ringwald static void sm_reset_setup(void){
11213deb3ec6SMatthias Ringwald     // fill in sm setup
1122901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1123dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1124d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11253deb3ec6SMatthias Ringwald     sm_reset_tk();
1126d7471931SMatthias Ringwald }
1127d7471931SMatthias Ringwald 
1128d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1129d7471931SMatthias Ringwald     // fill in sm setup
11303deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11316535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11323deb3ec6SMatthias Ringwald 
1133a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11349305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1135a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11363deb3ec6SMatthias Ringwald     }
11373deb3ec6SMatthias Ringwald 
1138a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1139a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11404acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11414acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1142a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11439305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11444acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1145a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1146a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1147a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1148a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11494acf7b7bSMatthias Ringwald                     setup->sm_ra);
11504acf7b7bSMatthias Ringwald             } else {
11514acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11524acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11534acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11544acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11554acf7b7bSMatthias Ringwald                     setup->sm_rb);
11564acf7b7bSMatthias Ringwald             }
1157a680ba6bSMatthias Ringwald         } else {
1158a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1159a680ba6bSMatthias Ringwald         }
1160a680ba6bSMatthias Ringwald     }
1161a680ba6bSMatthias Ringwald #endif
1162a680ba6bSMatthias Ringwald 
11633deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
116442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11653deb3ec6SMatthias Ringwald         // slave
11663deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11673deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1168d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11696535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1170d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11713deb3ec6SMatthias Ringwald     } else {
11723deb3ec6SMatthias Ringwald         // master
11733deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11743deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1175d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11766535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1177d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11783deb3ec6SMatthias Ringwald 
1179d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11801ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11811ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11823deb3ec6SMatthias Ringwald     }
11833deb3ec6SMatthias Ringwald 
118457132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1185d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11862c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11872c041b42SMatthias Ringwald     // enable SC for SC only mode
11882c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11892c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1190d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
11912c041b42SMatthias Ringwald     }
11922c041b42SMatthias Ringwald #endif
119357132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
119457132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
119557132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
119657132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
119757132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
119857132f12SMatthias Ringwald 	}
119957132f12SMatthias Ringwald #endif
12001ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1201a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1202df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1203d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12043deb3ec6SMatthias Ringwald }
12053deb3ec6SMatthias Ringwald 
12063deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12073deb3ec6SMatthias Ringwald 
12083deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12099a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12109a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
121142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121252f9cf63SMatthias Ringwald         // slave / responder
12133deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12149a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12159a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12163deb3ec6SMatthias Ringwald     } else {
12173deb3ec6SMatthias Ringwald         // master / initiator
12183deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12199a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12209a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12213deb3ec6SMatthias Ringwald     }
12223deb3ec6SMatthias Ringwald 
12233deb3ec6SMatthias Ringwald     // check key size
12242c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12252c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12262c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12272c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12282c041b42SMatthias Ringwald     }
12292c041b42SMatthias Ringwald #endif
12301ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12314ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12323deb3ec6SMatthias Ringwald 
1233eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12343deb3ec6SMatthias Ringwald     sm_setup_tk();
12353deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12363deb3ec6SMatthias Ringwald 
12373deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12383deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12393deb3ec6SMatthias Ringwald 
1240eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12412c041b42SMatthias Ringwald     // Check LE SC Only mode
12423cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12433cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12443cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12453cdbe9dbSMatthias Ringwald     }
12463cdbe9dbSMatthias Ringwald 
12479a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1248eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12499a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12509a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1251eddc894fSMatthias Ringwald     }
1252eddc894fSMatthias Ringwald #endif
1253eddc894fSMatthias Ringwald 
125452f9cf63SMatthias Ringwald     // identical to responder
12559a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
125652f9cf63SMatthias Ringwald 
12573deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1258c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12593deb3ec6SMatthias Ringwald 
12603deb3ec6SMatthias Ringwald     return 0;
12613deb3ec6SMatthias Ringwald }
12623deb3ec6SMatthias Ringwald 
12633deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12643deb3ec6SMatthias Ringwald 
12653deb3ec6SMatthias Ringwald     // cache and reset context
12663deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12673deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12683deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     // reset context
12713deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12723deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12733deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1274711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12753deb3ec6SMatthias Ringwald 
12763deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1277d2e90122SMatthias Ringwald     sm_key_t ltk;
12781979f09cSMatthias Ringwald     bool have_ltk;
12796c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12801979f09cSMatthias Ringwald     bool trigger_pairing;
128142134bc6SMatthias Ringwald #endif
12823deb3ec6SMatthias Ringwald     switch (mode){
12833deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12843deb3ec6SMatthias Ringwald             break;
12853deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12863deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1287711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12886c44b759SMatthias Ringwald 
12896c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12906c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12916c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12926c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12936c44b759SMatthias Ringwald 
12943deb3ec6SMatthias Ringwald             switch (event){
1295a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
12963deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
12973deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1298a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
12996c44b759SMatthias Ringwald 
13006c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13016c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13026c44b759SMatthias Ringwald 
13036c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13046c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1305212d735eSMatthias Ringwald                         // IRK required before, continue
13066c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13076c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13086c39055aSMatthias Ringwald                             break;
13096c39055aSMatthias Ringwald                         }
1310212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1311212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1312212d735eSMatthias Ringwald                             break;
1313212d735eSMatthias Ringwald                         }
13147af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13157af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13166c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13177af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13187af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13196c44b759SMatthias Ringwald #endif
13207af5dcd5SMatthias Ringwald 
13217af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13221979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13237af5dcd5SMatthias Ringwald 
13247af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13257af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13267af5dcd5SMatthias Ringwald                             if (have_ltk){
13277af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13287af5dcd5SMatthias Ringwald                             } else {
13297af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13307af5dcd5SMatthias Ringwald                             }
13317af5dcd5SMatthias Ringwald                             sm_trigger_run();
13326c44b759SMatthias Ringwald                         }
13336c44b759SMatthias Ringwald #endif
13346c44b759SMatthias Ringwald                     } else {
13356c44b759SMatthias Ringwald 
133642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13376c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13386c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13396c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13401979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13413deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134209ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134332bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1344c245ca32SMatthias Ringwald 
1345d4af1595SMatthias Ringwald                         if (have_ltk){
13466a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1347b187cc61SMatthias Ringwald                             trigger_reencryption = true;
134832bc5d65SMatthias Ringwald #else
134932bc5d65SMatthias Ringwald                             if (trigger_pairing){
135032bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135132bc5d65SMatthias Ringwald                             } else {
135232bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135332bc5d65SMatthias Ringwald                             }
135432bc5d65SMatthias Ringwald #endif
135532bc5d65SMatthias Ringwald                         }
135632bc5d65SMatthias Ringwald 
135732bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13586c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13595567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1360d4af1595SMatthias Ringwald                             break;
1361d4af1595SMatthias Ringwald                         }
13626c44b759SMatthias Ringwald 
13636c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13646c44b759SMatthias Ringwald                         if (trigger_pairing){
13653deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1366d4af1595SMatthias Ringwald                             break;
13673deb3ec6SMatthias Ringwald                         }
136842134bc6SMatthias Ringwald #endif
1369298ab52bSMatthias Ringwald                     }
13703deb3ec6SMatthias Ringwald                     break;
13713deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13723deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13736c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13747af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13756c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13766c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13776c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13786c39055aSMatthias Ringwald                         }
13797af5dcd5SMatthias Ringwald                         // send security request if requested
13807af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13817af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13827af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13837af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13847af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13857af5dcd5SMatthias Ringwald                         }
13866c39055aSMatthias Ringwald                         break;
13877af5dcd5SMatthias Ringwald #endif
13886c39055aSMatthias Ringwald                     }
138942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139009ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13913deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139209ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13933deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139442134bc6SMatthias Ringwald #endif
13953deb3ec6SMatthias Ringwald                     break;
13967bbeb3adSMilanka Ringwald 
13977bbeb3adSMilanka Ringwald                 default:
13987bbeb3adSMilanka Ringwald                     btstack_assert(false);
13997bbeb3adSMilanka Ringwald                     break;
14003deb3ec6SMatthias Ringwald             }
14013deb3ec6SMatthias Ringwald             break;
14023deb3ec6SMatthias Ringwald         default:
14033deb3ec6SMatthias Ringwald             break;
14043deb3ec6SMatthias Ringwald     }
14053deb3ec6SMatthias Ringwald 
14063deb3ec6SMatthias Ringwald     switch (event){
1407a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1408711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14093deb3ec6SMatthias Ringwald             break;
14103deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1411711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14123deb3ec6SMatthias Ringwald             break;
14137bbeb3adSMilanka Ringwald         default:
14147bbeb3adSMilanka Ringwald             btstack_assert(false);
14157bbeb3adSMilanka Ringwald             break;
14163deb3ec6SMatthias Ringwald     }
14173deb3ec6SMatthias Ringwald }
14183deb3ec6SMatthias Ringwald 
141955f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14203deb3ec6SMatthias Ringwald     int le_db_index = -1;
14213deb3ec6SMatthias Ringwald 
14223deb3ec6SMatthias Ringwald     // lookup device based on IRK
14233deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14243deb3ec6SMatthias Ringwald         int i;
1425092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14263deb3ec6SMatthias Ringwald             sm_key_t irk;
14273deb3ec6SMatthias Ringwald             bd_addr_t address;
1428c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14293deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1430adf5eaa9SMatthias Ringwald             // skip unused entries
1431c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1432c7e2c1a5SMatthias Ringwald             // compare IRK
1433c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1434c7e2c1a5SMatthias Ringwald 
14353deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14363deb3ec6SMatthias Ringwald             le_db_index = i;
14373deb3ec6SMatthias Ringwald             break;
14383deb3ec6SMatthias Ringwald         }
1439c7e2c1a5SMatthias Ringwald     } else {
1440c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1441c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14423deb3ec6SMatthias Ringwald     }
14433deb3ec6SMatthias Ringwald 
14443deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14453deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1446c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14473deb3ec6SMatthias Ringwald         int i;
1448092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14493deb3ec6SMatthias Ringwald             bd_addr_t address;
1450adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14513deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1452adf5eaa9SMatthias Ringwald             // skip unused entries
1453adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14543deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14555df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14563deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14573deb3ec6SMatthias Ringwald                 le_db_index = i;
14583deb3ec6SMatthias Ringwald                 break;
14593deb3ec6SMatthias Ringwald             }
14603deb3ec6SMatthias Ringwald         }
14613deb3ec6SMatthias Ringwald     }
14623deb3ec6SMatthias Ringwald 
14633deb3ec6SMatthias Ringwald     // if not found, add to db
146402b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14653deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14663deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
146702b02cffSMatthias Ringwald         new_to_le_device_db = true;
14683deb3ec6SMatthias Ringwald     }
14693deb3ec6SMatthias Ringwald 
14703deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14713deb3ec6SMatthias Ringwald 
147202b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
147302b02cffSMatthias Ringwald         if (!new_to_le_device_db){
147402b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
147502b02cffSMatthias Ringwald         }
147602b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
147702b02cffSMatthias Ringwald #else
147802b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
147902b02cffSMatthias Ringwald #endif
148002b02cffSMatthias Ringwald 
148148163929SMatthias 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);
1482e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14837710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
148448163929SMatthias Ringwald 
1485eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14863deb3ec6SMatthias Ringwald         // store local CSRK
1487715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1488715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14893deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
14903deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14913deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
14923deb3ec6SMatthias Ringwald         }
14933deb3ec6SMatthias Ringwald 
14943deb3ec6SMatthias Ringwald         // store remote CSRK
14953deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14963deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
14973deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
14983deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
14993deb3ec6SMatthias Ringwald         }
1500eda85fbfSMatthias Ringwald #endif
150178f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
150278f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1503e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
150478f44163SMatthias Ringwald             uint8_t zero_rand[8];
150578f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
150678f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15073dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
150878f44163SMatthias Ringwald         }
150978f44163SMatthias Ringwald 
1510e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151178f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151278f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1513e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15143deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15153dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
151678f44163SMatthias Ringwald 
15173deb3ec6SMatthias Ringwald         }
15183deb3ec6SMatthias Ringwald     }
151955f09f49SMatthias Ringwald }
152055f09f49SMatthias Ringwald 
152155f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
152255f09f49SMatthias Ringwald 
152355f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
152455f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
152555f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
152655f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
152755f09f49SMatthias Ringwald 
152855f09f49SMatthias Ringwald     if (bonding_enabled){
152955f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
153027ef8bc8SMatthias Ringwald     } else {
153127ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153227ef8bc8SMatthias Ringwald     }
15333deb3ec6SMatthias Ringwald }
15343deb3ec6SMatthias Ringwald 
1535688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1536f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1537688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1538688a08f9SMatthias Ringwald }
1539688a08f9SMatthias Ringwald 
1540688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1541688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1542688a08f9SMatthias Ringwald }
1543688a08f9SMatthias Ringwald 
15449af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1545688a08f9SMatthias Ringwald 
1546dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1547945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1548f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1549dc300847SMatthias Ringwald 
1550b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1551b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15521f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1553b90c4e75SMatthias Ringwald     } else {
1554b90c4e75SMatthias 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);
1555b35a3de2SMatthias Ringwald     }
1556b35a3de2SMatthias Ringwald }
1557b35a3de2SMatthias Ringwald 
1558688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
155942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1560688a08f9SMatthias Ringwald         // Responder
15614acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15624acf7b7bSMatthias Ringwald             // generate Nb
15634acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15646ca80073SMatthias 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);
15654acf7b7bSMatthias Ringwald         } else {
1566688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15674acf7b7bSMatthias Ringwald         }
1568688a08f9SMatthias Ringwald     } else {
1569688a08f9SMatthias Ringwald         // Initiator role
1570688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1571688a08f9SMatthias Ringwald             case JUST_WORKS:
1572dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1573688a08f9SMatthias Ringwald                 break;
1574688a08f9SMatthias Ringwald 
157547fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1576bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1577688a08f9SMatthias Ringwald                 break;
1578688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1579688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158047fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15814ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1582b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1583688a08f9SMatthias Ringwald                 } else {
1584dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1585688a08f9SMatthias Ringwald                 }
1586688a08f9SMatthias Ringwald                 break;
1587688a08f9SMatthias Ringwald             case OOB:
158865a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1589688a08f9SMatthias Ringwald                 break;
15907bbeb3adSMilanka Ringwald             default:
15917bbeb3adSMilanka Ringwald                 btstack_assert(false);
15927bbeb3adSMilanka Ringwald                 break;
1593688a08f9SMatthias Ringwald         }
1594688a08f9SMatthias Ringwald     }
1595688a08f9SMatthias Ringwald }
1596688a08f9SMatthias Ringwald 
1597aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1598688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1599688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1600688a08f9SMatthias Ringwald 
1601c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1602c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1603a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1604c59d0c92SMatthias Ringwald         return;
1605c59d0c92SMatthias Ringwald     }
1606c59d0c92SMatthias Ringwald 
1607bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1608bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16096857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16102bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1611b4f65634SMatthias Ringwald #endif
1612bd57ffebSMatthias Ringwald 
1613bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1614aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16156535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1616bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1617aec94140SMatthias Ringwald             break;
1618688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1619688a08f9SMatthias Ringwald             // check
1620688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1621bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1622688a08f9SMatthias Ringwald                 break;
1623688a08f9SMatthias Ringwald             }
1624bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1625688a08f9SMatthias Ringwald             break;
1626901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1627901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1628901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1629901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1630901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1631019005a0SMatthias Ringwald             break;
1632019005a0SMatthias Ringwald         }
16330346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16346535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1635bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16360346c37cSMatthias Ringwald             break;
16370346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16386535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1639bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16400346c37cSMatthias Ringwald             break;
16410346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1642b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1643b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1644b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1645b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16466535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16476535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1648893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1649bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1650019005a0SMatthias Ringwald             break;
1651901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16526535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1654901c000fSMatthias Ringwald                 // responder
1655901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1656901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1657901c000fSMatthias Ringwald                 } else {
1658901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1659901c000fSMatthias Ringwald                 }
1660901c000fSMatthias Ringwald             } else {
1661901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1662901c000fSMatthias Ringwald             }
1663901c000fSMatthias Ringwald             break;
1664901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1665901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1666901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1667aec94140SMatthias Ringwald                 break;
1668aec94140SMatthias Ringwald             }
166942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1670901c000fSMatthias Ringwald                 // responder
1671901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1672901c000fSMatthias Ringwald             } else {
1673901c000fSMatthias Ringwald                 // initiator
1674901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1675bd57ffebSMatthias Ringwald             }
1676901c000fSMatthias Ringwald             break;
16776857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
167857132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16796535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168057132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16812bacf595SMatthias Ringwald             break;
168257132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16832bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16842bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16852bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16868974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168755160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16888974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16892bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16902bacf595SMatthias Ringwald             } else {
16912bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16922bacf595SMatthias Ringwald             }
16930ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16942bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16952bacf595SMatthias Ringwald             break;
1696e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1697e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1698e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1699e0a03c85SMatthias Ringwald             break;
1700e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1701e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1702e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1703e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1704e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1705e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1706e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1707c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1708e0a03c85SMatthias Ringwald             break;
1709bdb14b0eSMatthias Ringwald #endif
1710bd57ffebSMatthias Ringwald         default:
1711bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1712bd57ffebSMatthias Ringwald             break;
1713bd57ffebSMatthias Ringwald     }
171470b44dd4SMatthias Ringwald     sm_trigger_run();
1715aec94140SMatthias Ringwald }
1716aec94140SMatthias Ringwald 
1717688a08f9SMatthias 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){
1718dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1719aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17206535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17216535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1722aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1723aec94140SMatthias Ringwald     log_info("f4 key");
1724aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1725aec94140SMatthias Ringwald     log_info("f4 message");
1726dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1727d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1728aec94140SMatthias Ringwald }
1729aec94140SMatthias Ringwald 
17300346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17310346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17320346c37cSMatthias Ringwald 
17330346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17348334d3d8SMatthias Ringwald 
17358334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17368334d3d8SMatthias Ringwald 
173740c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17380346c37cSMatthias Ringwald     // calculate salt for f5
17390346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17400346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17416535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1742d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17430346c37cSMatthias Ringwald }
17440346c37cSMatthias Ringwald 
17450346c37cSMatthias 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){
17460346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17470346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17480346c37cSMatthias Ringwald 
17490346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17500346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17516535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17566535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17570346c37cSMatthias Ringwald     log_info("f5 key");
17580346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17590346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17600346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1761d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17620346c37cSMatthias Ringwald }
17630346c37cSMatthias Ringwald 
17640346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17650346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17660346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17670346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17686535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17696535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
177042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17710346c37cSMatthias Ringwald         // responder
17720346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17730346c37cSMatthias Ringwald     } else {
17740346c37cSMatthias Ringwald         // initiator
17750346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17760346c37cSMatthias Ringwald     }
17770346c37cSMatthias Ringwald }
17780346c37cSMatthias Ringwald 
17790346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17800346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17810346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17820346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17830346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17840346c37cSMatthias Ringwald     // 1..52 setup before
17850346c37cSMatthias Ringwald     log_info("f5 key");
17860346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17870346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17880346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1789d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17900346c37cSMatthias Ringwald }
1791f92edc8eSMatthias Ringwald 
17920346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17930346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17940346c37cSMatthias Ringwald }
17950346c37cSMatthias Ringwald 
179631f061fbSMatthias 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){
17976535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17986535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18006535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18026535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
180331f061fbSMatthias Ringwald }
180431f061fbSMatthias Ringwald 
180531f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180631f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180731f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1808dc300847SMatthias Ringwald     log_info("f6 key");
1809dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1810dc300847SMatthias Ringwald     log_info("f6 message");
1811dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1812d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1813dc300847SMatthias Ringwald }
1814dc300847SMatthias Ringwald 
1815f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1816f92edc8eSMatthias Ringwald // - U is 256 bits
1817f92edc8eSMatthias Ringwald // - V is 256 bits
1818f92edc8eSMatthias Ringwald // - X is 128 bits
1819f92edc8eSMatthias Ringwald // - Y is 128 bits
1820bd57ffebSMatthias 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){
1821bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1822bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18236535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18246535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18256535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1826f92edc8eSMatthias Ringwald     log_info("g2 key");
1827f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1828f92edc8eSMatthias Ringwald     log_info("g2 message");
18292bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1830d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1831f92edc8eSMatthias Ringwald }
1832f92edc8eSMatthias Ringwald 
1833b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1834f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
183542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1836f92edc8eSMatthias Ringwald         // responder
1837fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1838f92edc8eSMatthias Ringwald     } else {
1839f92edc8eSMatthias Ringwald         // initiator
1840fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1841f92edc8eSMatthias Ringwald     }
1842f92edc8eSMatthias Ringwald }
1843f92edc8eSMatthias Ringwald 
1844945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18459af0f475SMatthias Ringwald     uint8_t z = 0;
184640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18479af0f475SMatthias Ringwald         // some form of passkey
18489af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18494ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18509af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18519af0f475SMatthias Ringwald     }
1852fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18539af0f475SMatthias Ringwald }
1854688a08f9SMatthias Ringwald 
1855688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1856a680ba6bSMatthias Ringwald     // OOB
1857a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18584acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18594acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18604acf7b7bSMatthias Ringwald         } else {
18614acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18624acf7b7bSMatthias Ringwald         }
1863a680ba6bSMatthias Ringwald         return;
1864a680ba6bSMatthias Ringwald     }
1865a680ba6bSMatthias Ringwald 
1866688a08f9SMatthias Ringwald     uint8_t z = 0;
186740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1868688a08f9SMatthias Ringwald         // some form of passkey
1869688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1870688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18714ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1872688a08f9SMatthias Ringwald     }
1873fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1874688a08f9SMatthias Ringwald }
1875688a08f9SMatthias Ringwald 
18760346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1877505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18783cf37b8cSMatthias Ringwald 
18793cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18803cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18813cf37b8cSMatthias Ringwald         return;
18823cf37b8cSMatthias Ringwald     } else {
18833cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18843cf37b8cSMatthias Ringwald     }
1885d1a1f6a4SMatthias Ringwald }
18863cf37b8cSMatthias Ringwald 
1887d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1888f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1889f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1890f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1891f3582630SMatthias Ringwald 
1892d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1893d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1894d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1895d1a1f6a4SMatthias Ringwald     // trigger next step
1896d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1897d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1898d1a1f6a4SMatthias Ringwald     }
189970b44dd4SMatthias Ringwald     sm_trigger_run();
1900dc300847SMatthias Ringwald }
1901dc300847SMatthias Ringwald 
1902dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1903dc300847SMatthias Ringwald     // calculate DHKCheck
1904dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1905dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1906dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19076535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19086535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1909dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1910dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1911dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1912dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1913dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1914dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1915dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1916dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1918dc300847SMatthias Ringwald         // responder
191931f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
192031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1921dc300847SMatthias Ringwald     } else {
1922dc300847SMatthias Ringwald         // initiator
192331f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1925dc300847SMatthias Ringwald     }
1926dc300847SMatthias Ringwald }
1927dc300847SMatthias Ringwald 
1928019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1929019005a0SMatthias Ringwald     // validate E = f6()
1930019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1931019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1932019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19336535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19346535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1935019005a0SMatthias Ringwald 
1936019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1937019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1938019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1939019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1940019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1941019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1942019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1943019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
194442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1945019005a0SMatthias Ringwald         // responder
194631f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194731f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1948019005a0SMatthias Ringwald     } else {
1949019005a0SMatthias Ringwald         // initiator
195031f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
195131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1952019005a0SMatthias Ringwald     }
1953019005a0SMatthias Ringwald }
19542bacf595SMatthias Ringwald 
195555c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19562bacf595SMatthias Ringwald 
19572bacf595SMatthias Ringwald //
19582bacf595SMatthias Ringwald // Link Key Conversion Function h6
19592bacf595SMatthias Ringwald //
196057132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19612bacf595SMatthias Ringwald // - W is 128 bits
19622bacf595SMatthias Ringwald // - keyID is 32 bits
19632bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19642bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19652bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19662bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19672bacf595SMatthias Ringwald     log_info("h6 key");
19682bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19692bacf595SMatthias Ringwald     log_info("h6 message");
19702bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1971d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19722bacf595SMatthias Ringwald }
197357132f12SMatthias Ringwald //
197457132f12SMatthias Ringwald // Link Key Conversion Function h7
197557132f12SMatthias Ringwald //
197657132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197757132f12SMatthias Ringwald // - SALT is 128 bits
197857132f12SMatthias Ringwald // - W    is 128 bits
197957132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
198057132f12SMatthias Ringwald 	const uint16_t message_len = 16;
198157132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
198257132f12SMatthias Ringwald 	log_info("h7 key");
198357132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
198457132f12SMatthias Ringwald 	log_info("h7 message");
198557132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198657132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198757132f12SMatthias Ringwald }
19882bacf595SMatthias Ringwald 
1989b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1990b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1991b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1992b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
199357132f12SMatthias Ringwald 
1994c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1995b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19962bacf595SMatthias Ringwald }
19972bacf595SMatthias Ringwald 
1998e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
1999e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2000e0a03c85SMatthias Ringwald }
2001e0a03c85SMatthias Ringwald 
20022bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20032bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20042bacf595SMatthias Ringwald }
20052bacf595SMatthias Ringwald 
2006e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2007e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2008e0a03c85SMatthias Ringwald }
2009e0a03c85SMatthias Ringwald 
2010c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
201157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
201257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
201357132f12SMatthias Ringwald }
2014e0a03c85SMatthias Ringwald 
2015e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2016e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2017e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2018e0a03c85SMatthias Ringwald }
2019e0a03c85SMatthias Ringwald 
2020c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2021e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2022e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2023e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2024e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2025e0a03c85SMatthias Ringwald }
2026e0a03c85SMatthias Ringwald 
2027c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2028c18be159SMatthias 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;
2029c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2030c18be159SMatthias Ringwald }
2031c18be159SMatthias Ringwald 
20329af0f475SMatthias Ringwald #endif
20339af0f475SMatthias Ringwald 
203455c62cf5SMatthias Ringwald #endif
203555c62cf5SMatthias Ringwald 
2036613da3deSMatthias Ringwald // key management legacy connections:
2037613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2038613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2039613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2040613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2041613da3deSMatthias Ringwald 
2042613da3deSMatthias Ringwald // key management secure connections:
2043613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2044613da3deSMatthias Ringwald 
204542134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20465829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20475829ebe2SMatthias Ringwald     int encryption_key_size;
20485829ebe2SMatthias Ringwald     int authenticated;
20495829ebe2SMatthias Ringwald     int authorized;
20503dc3a67dSMatthias Ringwald     int secure_connection;
20515829ebe2SMatthias Ringwald 
20525829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20535829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20543dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20553dc3a67dSMatthias 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);
20565829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20575829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20585829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20593dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20605829ebe2SMatthias Ringwald }
206142134bc6SMatthias Ringwald #endif
2062bd57ffebSMatthias Ringwald 
206342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
206459066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20656535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
206659066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
206759066796SMatthias Ringwald     // re-establish used key encryption size
206859066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20694ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
207059066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20714ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20723dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20733dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
207459066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
207559066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
207659066796SMatthias Ringwald }
207742134bc6SMatthias Ringwald #endif
207859066796SMatthias Ringwald 
20793deb3ec6SMatthias Ringwald // distributed key generation
2080d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20813deb3ec6SMatthias Ringwald     switch (dkg_state){
20823deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20833deb3ec6SMatthias Ringwald             // already busy?
20843deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2085d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20863deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2087d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2088d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2089d1a1f6a4SMatthias 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);
2090d7f1c72eSMatthias Ringwald                 return true;
20913deb3ec6SMatthias Ringwald             }
20923deb3ec6SMatthias Ringwald             break;
20933deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20943deb3ec6SMatthias Ringwald             // already busy?
20953deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2096d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20973deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2098d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2099d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2100d1a1f6a4SMatthias 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);
2101d7f1c72eSMatthias Ringwald                 return true;
21023deb3ec6SMatthias Ringwald             }
21033deb3ec6SMatthias Ringwald             break;
21043deb3ec6SMatthias Ringwald         default:
21053deb3ec6SMatthias Ringwald             break;
21063deb3ec6SMatthias Ringwald     }
2107d7f1c72eSMatthias Ringwald     return false;
2108d7f1c72eSMatthias Ringwald }
21093deb3ec6SMatthias Ringwald 
21103deb3ec6SMatthias Ringwald // random address updates
2111d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21123deb3ec6SMatthias Ringwald     switch (rau_state){
2113fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2114fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21155b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2116d7f1c72eSMatthias Ringwald             return true;
21173deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21183deb3ec6SMatthias Ringwald             // already busy?
21193deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2120d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2121d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2122d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2123d7f1c72eSMatthias Ringwald                 return true;
21243deb3ec6SMatthias Ringwald             }
21253deb3ec6SMatthias Ringwald             break;
21263deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
21273deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
21283deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
21293deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2130d7f1c72eSMatthias Ringwald             return true;
21313deb3ec6SMatthias Ringwald         default:
21323deb3ec6SMatthias Ringwald             break;
21333deb3ec6SMatthias Ringwald     }
2134d7f1c72eSMatthias Ringwald     return false;
2135d7f1c72eSMatthias Ringwald }
21363deb3ec6SMatthias Ringwald 
21373deb3ec6SMatthias Ringwald // CSRK Lookup
2138d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2139d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2140d7f1c72eSMatthias Ringwald 
21413deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21423deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21433deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2144665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2145665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21463deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21473deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21483deb3ec6SMatthias Ringwald                 // and start lookup
21493deb3ec6SMatthias 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);
21503deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21513deb3ec6SMatthias Ringwald                 break;
21523deb3ec6SMatthias Ringwald             }
21533deb3ec6SMatthias Ringwald         }
21543deb3ec6SMatthias Ringwald     }
21553deb3ec6SMatthias Ringwald 
21563deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21573deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2158665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21593deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2160665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21613deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21623deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21633deb3ec6SMatthias Ringwald         }
21643deb3ec6SMatthias Ringwald     }
21653deb3ec6SMatthias Ringwald 
21663deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21673deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2168092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2169092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2170adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21713deb3ec6SMatthias Ringwald             bd_addr_t addr;
21723deb3ec6SMatthias Ringwald             sm_key_t irk;
21733deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21743deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21753deb3ec6SMatthias Ringwald 
2176adf5eaa9SMatthias Ringwald             // skip unused entries
2177adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2178adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2179adf5eaa9SMatthias Ringwald                 continue;
2180adf5eaa9SMatthias Ringwald             }
2181adf5eaa9SMatthias Ringwald 
21825df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21833deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2184a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21853deb3ec6SMatthias Ringwald                 break;
21863deb3ec6SMatthias Ringwald             }
21873deb3ec6SMatthias Ringwald 
2188a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2189a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21903deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21913deb3ec6SMatthias Ringwald                 continue;
21923deb3ec6SMatthias Ringwald             }
21933deb3ec6SMatthias Ringwald 
21943deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21953deb3ec6SMatthias Ringwald 
21963deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21978314c363SMatthias Ringwald             log_info_key("IRK", irk);
21983deb3ec6SMatthias Ringwald 
21996535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2200d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
22013deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2202d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2203d1a1f6a4SMatthias 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);
2204d7f1c72eSMatthias Ringwald             return true;
22053deb3ec6SMatthias Ringwald         }
22063deb3ec6SMatthias Ringwald 
2207092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22083deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22093deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22103deb3ec6SMatthias Ringwald         }
22113deb3ec6SMatthias Ringwald     }
2212d7f1c72eSMatthias Ringwald     return false;
2213d7f1c72eSMatthias Ringwald }
22143deb3ec6SMatthias Ringwald 
2215d7f1c72eSMatthias Ringwald // SC OOB
2216d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2217c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2218c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2219c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2220c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2221c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2222c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2223d7f1c72eSMatthias Ringwald             return true;
2224c59d0c92SMatthias Ringwald         default:
2225c59d0c92SMatthias Ringwald             break;
2226c59d0c92SMatthias Ringwald     }
2227c59d0c92SMatthias Ringwald #endif
2228d7f1c72eSMatthias Ringwald     return false;
2229d7f1c72eSMatthias Ringwald }
2230275aafe8SMatthias Ringwald 
2231687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2232687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2233687a03c8SMatthias Ringwald }
2234687a03c8SMatthias Ringwald 
223541d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2236d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2237d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
223841d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2239e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
224041d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
224141d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
224241d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2243f4935286SMatthias Ringwald 
2244f4935286SMatthias Ringwald             // general
2245f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2246f4935286SMatthias Ringwald                 uint8_t buffer[2];
2247f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2248f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2249f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2250687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2251f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2252f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2253f4935286SMatthias Ringwald                 break;
2254f4935286SMatthias Ringwald             }
2255f4935286SMatthias Ringwald 
225641d32297SMatthias Ringwald             // responder side
225741d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
225841d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
225941d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2260d7f1c72eSMatthias Ringwald                 return true;
22614b8b5afeSMatthias Ringwald 
22624b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22634b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22644b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22654b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2266e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22674b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22684b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2269d7f1c72eSMatthias Ringwald                         return true;
22704b8b5afeSMatthias Ringwald                     default:
22714b8b5afeSMatthias Ringwald                         break;
22724b8b5afeSMatthias Ringwald                 }
22734b8b5afeSMatthias Ringwald                 break;
22744b8b5afeSMatthias Ringwald #endif
227541d32297SMatthias Ringwald             default:
227641d32297SMatthias Ringwald                 break;
227741d32297SMatthias Ringwald         }
227841d32297SMatthias Ringwald     }
2279d7f1c72eSMatthias Ringwald     return false;
2280d7f1c72eSMatthias Ringwald }
22813deb3ec6SMatthias Ringwald 
2282d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22833deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2284d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22853deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22867149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2287665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22883deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22893deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22901979f09cSMatthias Ringwald         bool done = true;
22913deb3ec6SMatthias Ringwald         int err;
229242134bc6SMatthias Ringwald         UNUSED(err);
229334b6528fSMatthias Ringwald 
229434b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
229534b6528fSMatthias Ringwald         // assert ec key is ready
2296505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2297178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2298178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
229934b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
230034b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
230134b6528fSMatthias Ringwald             }
230234b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
230334b6528fSMatthias Ringwald                 continue;
230434b6528fSMatthias Ringwald             }
230534b6528fSMatthias Ringwald         }
230634b6528fSMatthias Ringwald #endif
230734b6528fSMatthias Ringwald 
23083deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
230942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23103deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23113deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
231242134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2313549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
231406cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
231587014f74SMatthias Ringwald #endif
231687014f74SMatthias Ringwald #endif
231734c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23185567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
231934c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2320549ad5d2SMatthias Ringwald #endif
2321c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2322c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2323c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2324c18be159SMatthias Ringwald #endif
232587014f74SMatthias Ringwald 				// just lock context
232687014f74SMatthias Ringwald 				break;
23273deb3ec6SMatthias Ringwald             default:
23281979f09cSMatthias Ringwald                 done = false;
23293deb3ec6SMatthias Ringwald                 break;
23303deb3ec6SMatthias Ringwald         }
23313deb3ec6SMatthias Ringwald         if (done){
23327149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23337149bde5SMatthias 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);
23343deb3ec6SMatthias Ringwald         }
23353deb3ec6SMatthias Ringwald     }
2336d7f1c72eSMatthias Ringwald }
2337d7f1c72eSMatthias Ringwald 
2338403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2339403280b9SMatthias Ringwald     int i;
2340403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2341403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2342403280b9SMatthias Ringwald     uint8_t action = 0;
2343403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2344403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2345403280b9SMatthias Ringwald             bool clear_flag = true;
2346403280b9SMatthias Ringwald             switch (i){
2347403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2348403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2349403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2350403280b9SMatthias Ringwald                 default:
2351403280b9SMatthias Ringwald                     break;
2352403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2353403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2354403280b9SMatthias Ringwald                     num_actions--;
2355403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2356403280b9SMatthias Ringwald                     break;
2357403280b9SMatthias Ringwald             }
2358403280b9SMatthias Ringwald             if (clear_flag){
2359403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2360403280b9SMatthias Ringwald             }
2361403280b9SMatthias Ringwald             action = i;
2362403280b9SMatthias Ringwald             break;
2363403280b9SMatthias Ringwald         }
2364403280b9SMatthias Ringwald     }
2365403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2366403280b9SMatthias Ringwald 
2367403280b9SMatthias Ringwald     // send keypress notification
2368403280b9SMatthias Ringwald     uint8_t buffer[2];
2369403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2370403280b9SMatthias Ringwald     buffer[1] = action;
2371687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2372403280b9SMatthias Ringwald 
2373403280b9SMatthias Ringwald     // try
2374403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2375403280b9SMatthias Ringwald }
2376403280b9SMatthias Ringwald 
2377403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2378403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2379403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2380403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2381403280b9SMatthias Ringwald         uint8_t buffer[17];
2382403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2383403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2384687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2385403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2386403280b9SMatthias Ringwald         return;
2387403280b9SMatthias Ringwald     }
2388403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2389403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2390403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2391403280b9SMatthias Ringwald         uint8_t buffer[11];
2392403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2393403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2394403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2395687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2396403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2397403280b9SMatthias Ringwald         return;
2398403280b9SMatthias Ringwald     }
2399403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2400403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2401403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2402403280b9SMatthias Ringwald         uint8_t buffer[17];
2403403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2404403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &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     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2410403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2411403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2412403280b9SMatthias Ringwald         bd_addr_t local_address;
2413403280b9SMatthias Ringwald         uint8_t buffer[8];
2414403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2415403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2416403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2417403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2418403280b9SMatthias Ringwald                 // public or static random
2419403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2420403280b9SMatthias Ringwald                 break;
2421403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2422403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2423403280b9SMatthias Ringwald                 // fallback to public
2424403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2425403280b9SMatthias Ringwald                 buffer[1] = 0;
2426403280b9SMatthias Ringwald                 break;
2427403280b9SMatthias Ringwald             default:
2428403280b9SMatthias Ringwald                 btstack_assert(false);
2429403280b9SMatthias Ringwald                 break;
2430403280b9SMatthias Ringwald         }
2431403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2432687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2433403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2434403280b9SMatthias Ringwald         return;
2435403280b9SMatthias Ringwald     }
2436403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2437403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2438403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2439403280b9SMatthias Ringwald 
2440403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2441403280b9SMatthias Ringwald         // hack to reproduce test runs
2442403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2443403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2444403280b9SMatthias Ringwald                     }
2445403280b9SMatthias Ringwald 
2446403280b9SMatthias Ringwald                     // store local CSRK
2447403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2448403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2449403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2450403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2451403280b9SMatthias Ringwald                     }
2452403280b9SMatthias Ringwald #endif
2453403280b9SMatthias Ringwald 
2454403280b9SMatthias Ringwald         uint8_t buffer[17];
2455403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2456403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2457687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2458403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2459403280b9SMatthias Ringwald         return;
2460403280b9SMatthias Ringwald     }
2461403280b9SMatthias Ringwald     btstack_assert(false);
2462403280b9SMatthias Ringwald }
2463403280b9SMatthias Ringwald 
2464bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2465bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2466bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2467bbd73538SMatthias Ringwald     // - use secure connections
2468bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2469bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2470bbd73538SMatthias 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;
2471bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2472bbd73538SMatthias Ringwald     // - need identity address / public addr
2473bbd73538SMatthias 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);
2474bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2475bbd73538SMatthias 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)
2476bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2477bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2478bbd73538SMatthias 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.
2479bbd73538SMatthias Ringwald     uint8_t link_key[16];
2480bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2481bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2482bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2483bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2484bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2485bbd73538SMatthias Ringwald         return false;
2486bbd73538SMatthias Ringwald     }
2487bbd73538SMatthias Ringwald     // get started (all of the above are true)
2488bbd73538SMatthias Ringwald     return true;
2489bbd73538SMatthias Ringwald #else
2490bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2491bbd73538SMatthias Ringwald 	return false;
2492bbd73538SMatthias Ringwald #endif
2493bbd73538SMatthias Ringwald }
2494bbd73538SMatthias Ringwald 
24956f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24966f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24976f7422f1SMatthias 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;
24986f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24996f7422f1SMatthias Ringwald     } else {
25006f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25016f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25026f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25036f7422f1SMatthias Ringwald     }
25046f7422f1SMatthias Ringwald }
25056f7422f1SMatthias Ringwald 
2506af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2507af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2508af7ef9d1SMatthias 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;
2509af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2510af7ef9d1SMatthias Ringwald     } else {
2511af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2512af7ef9d1SMatthias Ringwald     }
2513af7ef9d1SMatthias Ringwald }
2514af7ef9d1SMatthias Ringwald 
2515d7f1c72eSMatthias Ringwald static void sm_run(void){
2516d7f1c72eSMatthias Ringwald 
2517d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2518d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2519d7f1c72eSMatthias Ringwald 
2520d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2521d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2522d7f1c72eSMatthias Ringwald 
2523d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2524d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2525d7f1c72eSMatthias Ringwald 
2526d7f1c72eSMatthias Ringwald     bool done;
2527d7f1c72eSMatthias Ringwald 
2528d7f1c72eSMatthias Ringwald     //
2529d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2530d7f1c72eSMatthias Ringwald     //
2531d7f1c72eSMatthias Ringwald 
2532d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2533d7f1c72eSMatthias Ringwald     if (done) return;
2534d7f1c72eSMatthias Ringwald 
2535d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2536d7f1c72eSMatthias Ringwald     if (done) return;
2537d7f1c72eSMatthias Ringwald 
2538d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2539d7f1c72eSMatthias Ringwald     if (done) return;
2540d7f1c72eSMatthias Ringwald 
2541d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2542d7f1c72eSMatthias Ringwald     if (done) return;
2543d7f1c72eSMatthias Ringwald 
2544d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2545d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2546d7f1c72eSMatthias Ringwald 
2547d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2548d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2549d7f1c72eSMatthias Ringwald     if (done) return;
2550d7f1c72eSMatthias Ringwald 
2551d7f1c72eSMatthias Ringwald     //
2552d7f1c72eSMatthias Ringwald     // active connection handling
2553d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2554d7f1c72eSMatthias Ringwald 
2555d7f1c72eSMatthias Ringwald     while (true) {
2556d7f1c72eSMatthias Ringwald 
2557d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2558d7f1c72eSMatthias Ringwald 
2559d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25603deb3ec6SMatthias Ringwald 
25613deb3ec6SMatthias Ringwald         //
25623deb3ec6SMatthias Ringwald         // active connection handling
25633deb3ec6SMatthias Ringwald         //
25643deb3ec6SMatthias Ringwald 
25653cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25663cf37b8cSMatthias Ringwald         if (!connection) {
25673cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25683cf37b8cSMatthias Ringwald             return;
25693cf37b8cSMatthias Ringwald         }
25703cf37b8cSMatthias Ringwald 
25713deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25727149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25737149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25747149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2575b170b20fSMatthias Ringwald             return;
2576b170b20fSMatthias Ringwald         }
25773deb3ec6SMatthias Ringwald 
25783d7fe1e9SMatthias Ringwald         // send keypress notifications
2579dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2580403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2581d7471931SMatthias Ringwald             return;
25823d7fe1e9SMatthias Ringwald         }
25833d7fe1e9SMatthias Ringwald 
25843deb3ec6SMatthias Ringwald         int key_distribution_flags;
258542134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2586b6afa23eSMatthias Ringwald 		int err;
2587b6afa23eSMatthias Ringwald 		UNUSED(err);
25889b75de03SMatthias Ringwald         bool have_ltk;
25899b75de03SMatthias Ringwald         uint8_t ltk[16];
25903deb3ec6SMatthias Ringwald 
25913deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2592dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2593dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2594dd4a08fbSMatthias Ringwald         }
25953deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25963deb3ec6SMatthias Ringwald 
2597f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2598aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2599aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2600aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2601aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2602aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2603aec94140SMatthias Ringwald                 break;
2604688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2605688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2606688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2607688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2608688a08f9SMatthias Ringwald                 break;
2609dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2610dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2611dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2612dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2613dc300847SMatthias Ringwald                 break;
2614019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2615b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2616019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26170346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26180346c37cSMatthias Ringwald                 break;
26190346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2620b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26210346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26220346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26230346c37cSMatthias Ringwald                 break;
26240346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2625b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26260346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26270346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26280346c37cSMatthias Ringwald                 break;
26290346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2630b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26310346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26320346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2633019005a0SMatthias Ringwald                 break;
2634bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2635b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2636bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2637b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2638bd57ffebSMatthias Ringwald                 break;
2639e0a03c85SMatthias Ringwald #endif
2640e0a03c85SMatthias Ringwald 
264142134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26423deb3ec6SMatthias Ringwald             // initiator side
2643f32b7a88SMatthias Ringwald 
26445567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2645f32b7a88SMatthias Ringwald 				sm_reset_setup();
2646f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2647daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2648f32b7a88SMatthias Ringwald 
26493deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26509c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26515567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26523deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2653c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2654c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26553deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26563deb3ec6SMatthias Ringwald                 return;
26573deb3ec6SMatthias Ringwald             }
26583deb3ec6SMatthias Ringwald 
2659b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2660b26f445fSMatthias Ringwald 				sm_reset_setup();
2661b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2662b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2663d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2664b26f445fSMatthias Ringwald 
26651ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26663deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2667687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26683deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26693deb3ec6SMatthias Ringwald                 break;
267042134bc6SMatthias Ringwald #endif
26713deb3ec6SMatthias Ringwald 
267227c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
267341d32297SMatthias Ringwald 
2674c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26751979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26761979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
267727c32905SMatthias Ringwald                 uint8_t buffer[65];
267827c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
267927c32905SMatthias Ringwald                 //
2680fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2681fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2682e53be891SMatthias Ringwald 
2683349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2684349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2685349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2686349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2687349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2688349d0adbSMatthias Ringwald                 }
2689349d0adbSMatthias Ringwald #endif
2690349d0adbSMatthias Ringwald 
269145a61d50SMatthias Ringwald                 // stk generation method
269245a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
269345a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
269445a61d50SMatthias Ringwald                     case JUST_WORKS:
269547fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
269642134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269707036a04SMatthias Ringwald                             // responder
26981979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2699b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
270027c32905SMatthias Ringwald                         } else {
270107036a04SMatthias Ringwald                             // initiator
2702c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270327c32905SMatthias Ringwald                         }
270445a61d50SMatthias Ringwald                         break;
270545a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
270645a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
270747fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
270807036a04SMatthias Ringwald                         // use random TK for display
27096535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27106535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
271145a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
271207036a04SMatthias Ringwald 
271342134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
271445a61d50SMatthias Ringwald                             // responder
2715c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
271645a61d50SMatthias Ringwald                         } else {
271745a61d50SMatthias Ringwald                             // initiator
2718c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271945a61d50SMatthias Ringwald                         }
27201979f09cSMatthias Ringwald                         trigger_user_response = true;
272145a61d50SMatthias Ringwald                         break;
272245a61d50SMatthias Ringwald                     case OOB:
272365a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272465a9a04eSMatthias Ringwald                             // responder
272565a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
272665a9a04eSMatthias Ringwald                         } else {
272765a9a04eSMatthias Ringwald                             // initiator
272865a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272965a9a04eSMatthias Ringwald                         }
273045a61d50SMatthias Ringwald                         break;
27317bbeb3adSMilanka Ringwald                     default:
27327bbeb3adSMilanka Ringwald                         btstack_assert(false);
27337bbeb3adSMilanka Ringwald                         break;
273445a61d50SMatthias Ringwald                 }
273545a61d50SMatthias Ringwald 
2736687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
273727c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2738644c6a1dSMatthias Ringwald 
2739b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2740644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2741644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2742644c6a1dSMatthias Ringwald                 }
2743b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2744b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2745b90c4e75SMatthias Ringwald                 }
274627c32905SMatthias Ringwald                 break;
274727c32905SMatthias Ringwald             }
2748c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2749e53be891SMatthias Ringwald                 uint8_t buffer[17];
2750e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27519af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
275242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2753c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2754e53be891SMatthias Ringwald                 } else {
2755c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2756e53be891SMatthias Ringwald                 }
2757687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2758e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2759e53be891SMatthias Ringwald                 break;
2760e53be891SMatthias Ringwald             }
2761c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2762e53be891SMatthias Ringwald                 uint8_t buffer[17];
2763e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2764e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27659d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27664ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
276740c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
276842134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
276945a61d50SMatthias Ringwald                         // responder
2770c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
277145a61d50SMatthias Ringwald                     } else {
277245a61d50SMatthias Ringwald                         // initiator
2773c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
277445a61d50SMatthias Ringwald                     }
277545a61d50SMatthias Ringwald                 } else {
277640c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
277742134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2778e53be891SMatthias Ringwald                         // responder
277947fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
278040c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2781901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27822886623dSMatthias Ringwald                         } else {
278340c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27842886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2785446a8c36SMatthias Ringwald                         }
2786e53be891SMatthias Ringwald                     } else {
2787136d331aSMatthias Ringwald                         // initiator
2788c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2789e53be891SMatthias Ringwald                     }
279045a61d50SMatthias Ringwald                 }
2791687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2792e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2793e53be891SMatthias Ringwald                 break;
2794e53be891SMatthias Ringwald             }
2795c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2796e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2797e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2798e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2799dc300847SMatthias Ringwald 
280042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2801c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2802e53be891SMatthias Ringwald                 } else {
2803c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2804e53be891SMatthias Ringwald                 }
2805e083ca23SMatthias Ringwald 
2806687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2807e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2808e53be891SMatthias Ringwald                 break;
2809e53be891SMatthias Ringwald             }
2810e53be891SMatthias Ringwald 
2811e53be891SMatthias Ringwald #endif
281242134bc6SMatthias Ringwald 
281342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2814dd12a62bSMatthias Ringwald 
281587014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
281687014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
281787014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2818687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2819c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
282087014f74SMatthias Ringwald 				break;
282187014f74SMatthias Ringwald 			}
282287014f74SMatthias Ringwald 
282338196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
282438196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
282538196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
282638196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
282738196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
282838196718SMatthias Ringwald 						// start using context by loading security info
282938196718SMatthias Ringwald 						sm_reset_setup();
283038196718SMatthias Ringwald 						sm_load_security_info(connection);
283138196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
283238196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
283338196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
283442646f38SMatthias Ringwald                             sm_reencryption_started(connection);
283538196718SMatthias Ringwald                             sm_trigger_run();
283638196718SMatthias Ringwald 							break;
283738196718SMatthias Ringwald 						}
283838196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
283938196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
284038196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
284138196718SMatthias Ringwald 						return;
284238196718SMatthias Ringwald 					default:
284338196718SMatthias Ringwald 						// just wait until IRK lookup is completed
284438196718SMatthias Ringwald 						break;
284538196718SMatthias Ringwald 				}
284638196718SMatthias Ringwald 				break;
284738196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
284838196718SMatthias Ringwald 
2849b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2850b6afa23eSMatthias Ringwald                 sm_reset_setup();
28519b75de03SMatthias Ringwald 
28529b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28539b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28549b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28559b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28569b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28579b75de03SMatthias Ringwald                         if (have_ltk){
28589b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
285919a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28609b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28619b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28629b75de03SMatthias Ringwald                         }
28639b75de03SMatthias Ringwald                         break;
28649b75de03SMatthias Ringwald                     default:
28659b75de03SMatthias Ringwald                         break;
28669b75de03SMatthias Ringwald                 }
28679b75de03SMatthias Ringwald 
2868b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2869d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
287039543d07SMatthias Ringwald 
2871b6afa23eSMatthias Ringwald 				// recover pairing request
2872b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2873b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2874b6afa23eSMatthias Ringwald 
2875b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2876b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2877b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2878b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2879b6afa23eSMatthias Ringwald                     }
2880b6afa23eSMatthias Ringwald #endif
28819305033eSMatthias Ringwald 				if (err != 0){
2882f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2883b6afa23eSMatthias Ringwald 					sm_trigger_run();
2884b6afa23eSMatthias Ringwald 					break;
2885b6afa23eSMatthias Ringwald 				}
2886b6afa23eSMatthias Ringwald 
2887b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2888b6afa23eSMatthias Ringwald 
2889b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2890b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2891b6afa23eSMatthias 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);
2892b6afa23eSMatthias Ringwald 					break;
2893b6afa23eSMatthias Ringwald 				}
2894b6afa23eSMatthias Ringwald 
2895b6afa23eSMatthias Ringwald 				/* fall through */
2896b6afa23eSMatthias Ringwald 
28973deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28981ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2899f55bd529SMatthias Ringwald 
2900f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29013deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29021ad129beSMatthias Ringwald 
2903f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2904f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2905f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2906f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2907f55bd529SMatthias Ringwald                 }
2908f55bd529SMatthias Ringwald #endif
2909f55bd529SMatthias Ringwald                 // setup in response
2910f55bd529SMatthias 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);
2911f55bd529SMatthias 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);
2912f55bd529SMatthias Ringwald 
2913f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29149a90d41aSMatthias 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));
2915f55bd529SMatthias Ringwald 
291627c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2917c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29180b8af2a5SMatthias Ringwald                 } else {
29190b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
292027c32905SMatthias Ringwald                 }
29210b8af2a5SMatthias Ringwald 
2922687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29233deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2924446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2925c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29263deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2927446a8c36SMatthias Ringwald                 }
29283deb3ec6SMatthias Ringwald                 return;
292942134bc6SMatthias Ringwald #endif
29303deb3ec6SMatthias Ringwald 
29313deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29323deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29333deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29349c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
293542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29363deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29373deb3ec6SMatthias Ringwald                 } else {
29383deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29393deb3ec6SMatthias Ringwald                 }
2940687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29413deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29423deb3ec6SMatthias Ringwald                 break;
29433deb3ec6SMatthias Ringwald             }
29443deb3ec6SMatthias Ringwald 
2945d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29463deb3ec6SMatthias Ringwald                 // already busy?
29473deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2948d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2949d1a1f6a4SMatthias 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);
2950d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2951d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2952f3582630SMatthias 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);
29533deb3ec6SMatthias Ringwald                 break;
29543deb3ec6SMatthias Ringwald 
29553deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29563deb3ec6SMatthias Ringwald                 // already busy?
29573deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29583deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2959d1a1f6a4SMatthias 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);
2960d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2961d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2962f3582630SMatthias 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);
29633deb3ec6SMatthias Ringwald                 break;
2964d1a1f6a4SMatthias Ringwald 
29653deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29663deb3ec6SMatthias Ringwald                 // already busy?
29673deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29683deb3ec6SMatthias Ringwald                 // calculate STK
296942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2970d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29713deb3ec6SMatthias Ringwald                 } else {
2972d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29733deb3ec6SMatthias Ringwald                 }
2974d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2975d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2976f3582630SMatthias 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);
29773deb3ec6SMatthias Ringwald                 break;
2978d1a1f6a4SMatthias Ringwald 
29793deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29803deb3ec6SMatthias Ringwald                 // already busy?
29813deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29823deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29839ad0dd7cSMatthias Ringwald 
29849ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29859ad0dd7cSMatthias Ringwald                 // r' = padding || r
29869ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29879ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29886535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29899ad0dd7cSMatthias Ringwald 
29903deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2991d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2992d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2993f3582630SMatthias 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);
2994d1a1f6a4SMatthias Ringwald                 break;
2995d1a1f6a4SMatthias Ringwald 
29963deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29973deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29983deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29999c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
300042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30013deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30023deb3ec6SMatthias Ringwald                 } else {
30033deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30043deb3ec6SMatthias Ringwald                 }
3005687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30063deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30073deb3ec6SMatthias Ringwald                 return;
30083deb3ec6SMatthias Ringwald             }
300942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30103deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30113deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30129c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30133deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30143deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30153deb3ec6SMatthias Ringwald                 return;
30163deb3ec6SMatthias Ringwald             }
3017d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
30183deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30199c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30205567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30213deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30223deb3ec6SMatthias Ringwald                 return;
30233deb3ec6SMatthias Ringwald             }
3024dd12a62bSMatthias Ringwald 
3025dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30263deb3ec6SMatthias Ringwald                 // already busy?
30273deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30283deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3029c61cfe5aSMatthias Ringwald 
3030dd12a62bSMatthias Ringwald 				sm_reset_setup();
3031dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3032dd12a62bSMatthias Ringwald 
303342646f38SMatthias Ringwald 				sm_reencryption_started(connection);
303442646f38SMatthias Ringwald 
3035c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3036c61cfe5aSMatthias Ringwald                 // r' = padding || r
3037c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3038c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30396535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3040c61cfe5aSMatthias Ringwald 
30413deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3042d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3043d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3044f3582630SMatthias 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);
30453deb3ec6SMatthias Ringwald                 return;
304642134bc6SMatthias Ringwald #endif
304742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
304842134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
304942134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
305042134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
305142134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
305242134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
305342134bc6SMatthias Ringwald                 return;
305442134bc6SMatthias Ringwald             }
305542134bc6SMatthias Ringwald #endif
30563deb3ec6SMatthias Ringwald 
30573deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3058403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3059403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30603deb3ec6SMatthias Ringwald                     return;
30613deb3ec6SMatthias Ringwald                 }
30623deb3ec6SMatthias Ringwald 
30633deb3ec6SMatthias Ringwald                 // keys are sent
306442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30653deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
3066*61d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30673deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3068f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3069f5020412SMatthias Ringwald                         // start CTKD right away
3070f5020412SMatthias Ringwald                         continue;
30713deb3ec6SMatthias Ringwald                     } else {
30723deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30733deb3ec6SMatthias Ringwald                     }
30743deb3ec6SMatthias Ringwald                 } else {
30751dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30763deb3ec6SMatthias Ringwald                 }
30773deb3ec6SMatthias Ringwald                 break;
30783deb3ec6SMatthias Ringwald 
3079c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3080c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3081c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3082c18be159SMatthias Ringwald                 sm_reset_setup();
3083c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3084c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3085c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3086c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3087c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3088c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3089c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3090c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3091c18be159SMatthias Ringwald 
3092c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3093c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3094c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3095c18be159SMatthias Ringwald                 // Plus signing key if supported
3096c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3097c18be159SMatthias Ringwald #endif
3098c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3099c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3100c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3101c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3102c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3103c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3104c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3105c18be159SMatthias Ringwald 
3106c18be159SMatthias Ringwald                 // set state and send pairing response
3107c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3108c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3109c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3110c18be159SMatthias Ringwald                 break;
3111c18be159SMatthias Ringwald 
3112c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3113c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3114c18be159SMatthias Ringwald                 sm_reset_setup();
3115c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3116c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3117c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3118c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3119c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3120c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3121c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3122c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3123c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3124c18be159SMatthias Ringwald 
3125c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3126c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3127c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3128c18be159SMatthias Ringwald                 // Plus signing key if supported
3129c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3130c18be159SMatthias Ringwald #endif
3131c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3132c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3133c18be159SMatthias Ringwald 
3134c18be159SMatthias Ringwald                 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use:
3135c18be159SMatthias Ringwald                 // - the IO Capability field,
3136c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3137c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3138c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3139c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3140c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3141c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3142c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3143c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3144c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3145c18be159SMatthias Ringwald 
3146c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3147c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3148c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3149c18be159SMatthias Ringwald 
3150c18be159SMatthias Ringwald                 // set state and send pairing response
3151c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3152c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3153c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3154c18be159SMatthias Ringwald                 break;
3155c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3156c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3157c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3158c18be159SMatthias Ringwald                     return;
3159c18be159SMatthias Ringwald                 }
3160c18be159SMatthias Ringwald                 // keys are sent
3161c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3162c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
3163*61d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3164c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3165c18be159SMatthias Ringwald                         break;
3166c18be159SMatthias Ringwald                     }
3167c18be159SMatthias Ringwald                 }
3168c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3169c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3170c18be159SMatthias Ringwald                 continue;
3171c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3172c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3173c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3174c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3175c18be159SMatthias Ringwald                 break;
3176c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3177c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3178c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3179c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3180c18be159SMatthias Ringwald                 break;
3181c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3182c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3183c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3184c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3185c18be159SMatthias Ringwald                 break;
3186c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3187c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3188c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3189c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3190c18be159SMatthias Ringwald                 break;
3191c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3192c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3193c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3194c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3195c18be159SMatthias Ringwald                 break;
3196c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3197c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3198c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3199c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3200c18be159SMatthias Ringwald                 break;
3201c18be159SMatthias Ringwald #endif
3202c18be159SMatthias Ringwald 
32033deb3ec6SMatthias Ringwald             default:
32043deb3ec6SMatthias Ringwald                 break;
32053deb3ec6SMatthias Ringwald         }
32063deb3ec6SMatthias Ringwald 
32073deb3ec6SMatthias Ringwald         // check again if active connection was released
32087149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32093deb3ec6SMatthias Ringwald     }
32103deb3ec6SMatthias Ringwald }
32113deb3ec6SMatthias Ringwald 
3212d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3213d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3214f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
321504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
321604678764SMatthias Ringwald 
3217f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3218f3582630SMatthias Ringwald     if (connection == NULL) return;
3219f3582630SMatthias Ringwald 
3220d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
322104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3222f3582630SMatthias 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);
3223d1a1f6a4SMatthias Ringwald }
32243deb3ec6SMatthias Ringwald 
3225d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3226f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322804678764SMatthias Ringwald 
3229f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3230f3582630SMatthias Ringwald     if (connection == NULL) return;
3231f3582630SMatthias Ringwald 
32328314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32333deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
323470b44dd4SMatthias Ringwald     sm_trigger_run();
3235d1a1f6a4SMatthias Ringwald }
3236d1a1f6a4SMatthias Ringwald 
3237d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3238d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3239f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324104678764SMatthias Ringwald 
3242f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3243f3582630SMatthias Ringwald     if (connection == NULL) return;
3244f3582630SMatthias Ringwald 
3245d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
324604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3247f3582630SMatthias 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);
3248d1a1f6a4SMatthias Ringwald }
3249d1a1f6a4SMatthias Ringwald 
3250d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3251f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
325204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325304678764SMatthias Ringwald 
3254f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3255f3582630SMatthias Ringwald     if (connection == NULL) return;
3256f3582630SMatthias Ringwald 
3257d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3258d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3259f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
326070b44dd4SMatthias Ringwald         sm_trigger_run();
32613deb3ec6SMatthias Ringwald         return;
32623deb3ec6SMatthias Ringwald     }
326342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32643deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
326570b44dd4SMatthias Ringwald         sm_trigger_run();
32663deb3ec6SMatthias Ringwald     } else {
3267d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3268d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3269f3582630SMatthias 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);
32703deb3ec6SMatthias Ringwald     }
32713deb3ec6SMatthias Ringwald }
3272d1a1f6a4SMatthias Ringwald 
3273d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
327404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3275f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327604678764SMatthias Ringwald 
3277f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3278f3582630SMatthias Ringwald     if (connection == NULL) return;
3279f3582630SMatthias Ringwald 
32803deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32818314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
328242134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32833deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
32843deb3ec6SMatthias Ringwald     } else {
32853deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
32863deb3ec6SMatthias Ringwald     }
328770b44dd4SMatthias Ringwald     sm_trigger_run();
3288d1a1f6a4SMatthias Ringwald }
3289d1a1f6a4SMatthias Ringwald 
3290d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3291d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3292f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
329304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329404678764SMatthias Ringwald 
3295f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3296f3582630SMatthias Ringwald     if (connection == NULL) return;
3297f3582630SMatthias Ringwald 
3298d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
32993deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33003deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33013deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33023deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33033deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33043deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3305d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
330604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3307f3582630SMatthias 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);
33083deb3ec6SMatthias Ringwald }
3309d1a1f6a4SMatthias Ringwald 
33102a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3311d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3312d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
331304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3314f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
331504678764SMatthias Ringwald 
3316f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3317f3582630SMatthias Ringwald     if (connection == NULL) return;
3318f3582630SMatthias Ringwald 
3319d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33203deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33213deb3ec6SMatthias Ringwald 
33223deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33233deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33243deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33253deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33263deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3327d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
332804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3329f3582630SMatthias 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);
33303deb3ec6SMatthias Ringwald }
33312a526f21SMatthias Ringwald #endif
3332d1a1f6a4SMatthias Ringwald 
3333d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3334d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3335f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
333704678764SMatthias Ringwald 
3338f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3339f3582630SMatthias Ringwald     if (connection == NULL) return;
3340f3582630SMatthias Ringwald 
33418314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33423deb3ec6SMatthias Ringwald     // calc CSRK next
3343d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
334404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3345f3582630SMatthias 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);
3346d1a1f6a4SMatthias Ringwald }
3347d1a1f6a4SMatthias Ringwald 
3348d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3349f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
335004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
335104678764SMatthias Ringwald 
3352f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3353f3582630SMatthias Ringwald     if (connection == NULL) return;
3354f3582630SMatthias Ringwald 
3355d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33568314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33573deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33583deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33593deb3ec6SMatthias Ringwald     } else {
33603deb3ec6SMatthias Ringwald         // no keys to send, just continue
336142134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3362*61d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3363c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3364c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3365c5a72e35SMatthias Ringwald             } else {
33663deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33673deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3368c5a72e35SMatthias Ringwald             }
33693deb3ec6SMatthias Ringwald         } else {
3370af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33713deb3ec6SMatthias Ringwald         }
33722bacf595SMatthias Ringwald     }
337370b44dd4SMatthias Ringwald     sm_trigger_run();
3374d1a1f6a4SMatthias Ringwald }
3375d1a1f6a4SMatthias Ringwald 
337642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3377d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3378f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
337904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
338004678764SMatthias Ringwald 
3381f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3382f3582630SMatthias Ringwald     if (connection == NULL) return;
3383f3582630SMatthias Ringwald 
33843deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33858314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3386d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
338770b44dd4SMatthias Ringwald     sm_trigger_run();
3388d1a1f6a4SMatthias Ringwald }
3389d1a1f6a4SMatthias Ringwald #endif
3390d1a1f6a4SMatthias Ringwald 
3391d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3392d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3393d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339404678764SMatthias Ringwald 
3395d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3396d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3397d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3398d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3399d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3400a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
340170b44dd4SMatthias Ringwald         sm_trigger_run();
34023deb3ec6SMatthias Ringwald         return;
34033deb3ec6SMatthias Ringwald     }
3404d1a1f6a4SMatthias Ringwald     // no match, try next
3405d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
340670b44dd4SMatthias Ringwald     sm_trigger_run();
34073deb3ec6SMatthias Ringwald }
34083deb3ec6SMatthias Ringwald 
3409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3410d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3411d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341204678764SMatthias Ringwald 
3413d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3414d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
341570b44dd4SMatthias Ringwald     sm_trigger_run();
34167df18c15SMatthias Ringwald }
3417d1a1f6a4SMatthias Ringwald 
3418d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3419d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3420d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342104678764SMatthias Ringwald 
3422d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3423d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
342470b44dd4SMatthias Ringwald     sm_trigger_run();
34257df18c15SMatthias Ringwald }
3426d1a1f6a4SMatthias Ringwald 
3427d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3428d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3429d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
343004678764SMatthias Ringwald 
34316535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3432d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
343370b44dd4SMatthias Ringwald     sm_trigger_run();
343451fa0b28SMatthias Ringwald }
34357df18c15SMatthias Ringwald 
3436d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3437d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34383deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34393deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34403deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34413deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34423deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34434ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34444ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34453deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34463deb3ec6SMatthias Ringwald             break;
34473deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34483deb3ec6SMatthias Ringwald         default:
34493deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34504ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34513deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
34523deb3ec6SMatthias Ringwald             break;
34533deb3ec6SMatthias Ringwald     }
345470b44dd4SMatthias Ringwald     sm_trigger_run();
34553deb3ec6SMatthias Ringwald }
34563deb3ec6SMatthias Ringwald 
3457c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34586ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3459f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3460f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3461f3582630SMatthias Ringwald     if (connection == NULL) return;
3462c59d0c92SMatthias Ringwald 
346365a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
346470b44dd4SMatthias Ringwald     sm_trigger_run();
346565a9a04eSMatthias Ringwald }
3466d1a1f6a4SMatthias Ringwald 
34676ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34686ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34696ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34706ca80073SMatthias Ringwald     if (connection == NULL) return;
34716ca80073SMatthias Ringwald 
3472b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
347370b44dd4SMatthias Ringwald     sm_trigger_run();
3474d1a1f6a4SMatthias Ringwald }
3475f1c1783eSMatthias Ringwald #endif
3476f1c1783eSMatthias Ringwald 
3477d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3478f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3479f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3480f3582630SMatthias Ringwald     if (connection == NULL) return;
3481f3582630SMatthias Ringwald 
3482d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
348370b44dd4SMatthias Ringwald     sm_trigger_run();
3484d1a1f6a4SMatthias Ringwald }
3485d1a1f6a4SMatthias Ringwald 
3486d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3487f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3488f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3489f3582630SMatthias Ringwald     if (connection == NULL) return;
3490f3582630SMatthias Ringwald 
3491caf15bf3SMatthias Ringwald     sm_reset_tk();
3492caf15bf3SMatthias Ringwald     uint32_t tk;
34935ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
34943deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3495d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
34963deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
34974ea43905SMatthias Ringwald         if (tk >= 999999u){
34984ea43905SMatthias Ringwald             tk = tk - 999999u;
34993deb3ec6SMatthias Ringwald         }
3500caf15bf3SMatthias Ringwald     } else {
3501caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35024b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3503caf15bf3SMatthias Ringwald     }
3504f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
350542134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35063deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35073deb3ec6SMatthias Ringwald     } else {
3508b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3509b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3510b41539d5SMatthias Ringwald         } else {
35113deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35123deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35133deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35143deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3515f3582630SMatthias 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);
35163deb3ec6SMatthias Ringwald             }
35173deb3ec6SMatthias Ringwald         }
3518b41539d5SMatthias Ringwald     }
351970b44dd4SMatthias Ringwald     sm_trigger_run();
35203deb3ec6SMatthias Ringwald }
3521d1a1f6a4SMatthias Ringwald 
3522d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3523f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3524f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3525f3582630SMatthias Ringwald     if (connection == NULL) return;
3526f3582630SMatthias Ringwald 
3527d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3528d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3529d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3530d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
353170b44dd4SMatthias Ringwald     sm_trigger_run();
3532d1a1f6a4SMatthias Ringwald }
3533d1a1f6a4SMatthias Ringwald 
3534d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3535f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3536f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3537f3582630SMatthias Ringwald     if (connection == NULL) return;
3538f3582630SMatthias Ringwald 
3539d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35403deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35414ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35423deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35434ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35448b3ffec5SMatthias 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);
35453deb3ec6SMatthias Ringwald }
3546899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3547899e6e02SMatthias Ringwald     // warn about default ER/IR
35481979f09cSMatthias Ringwald     bool warning = false;
3549899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35501979f09cSMatthias Ringwald         warning = true;
3551899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3552899e6e02SMatthias Ringwald     }
3553899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35541979f09cSMatthias Ringwald         warning = true;
3555899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3556899e6e02SMatthias Ringwald     }
355721045273SMatthias Ringwald     if (warning) {
3558899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3559899e6e02SMatthias Ringwald     }
356021045273SMatthias Ringwald }
3561899e6e02SMatthias Ringwald 
3562899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35631979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35649305033eSMatthias Ringwald     if (arg != NULL){
3565899e6e02SMatthias Ringwald         // key generated, store in tlv
35664ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3567899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3568e0d13a19SMilanka Ringwald         UNUSED(status);
3569899e6e02SMatthias Ringwald     }
3570899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35718d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3572841468bbSMatthias Ringwald 
3573841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3574841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3575841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3576841468bbSMatthias Ringwald     }
3577841468bbSMatthias Ringwald 
357870b44dd4SMatthias Ringwald     sm_trigger_run();
3579899e6e02SMatthias Ringwald }
3580899e6e02SMatthias Ringwald 
3581899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
35821979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35839305033eSMatthias Ringwald     if (arg != 0){
3584899e6e02SMatthias Ringwald         // key generated, store in tlv
35854ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3586899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3587e0d13a19SMilanka Ringwald         UNUSED(status);
3588899e6e02SMatthias Ringwald     }
3589899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3590899e6e02SMatthias Ringwald 
3591899e6e02SMatthias Ringwald     // try load ir
35924ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3593899e6e02SMatthias Ringwald     if (key_size == 16){
3594899e6e02SMatthias Ringwald         // ok, let's continue
3595899e6e02SMatthias Ringwald         log_info("IR from TLV");
3596899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3597899e6e02SMatthias Ringwald     } else {
3598899e6e02SMatthias Ringwald         // invalid, generate new random one
35991979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3600899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3601899e6e02SMatthias Ringwald     }
3602899e6e02SMatthias Ringwald }
36033deb3ec6SMatthias Ringwald 
3604f664b5e8SMatthias 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){
3605f664b5e8SMatthias Ringwald 
3606f664b5e8SMatthias Ringwald     // connection info
3607f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3608f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3609f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3610f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3611f664b5e8SMatthias Ringwald 
3612f664b5e8SMatthias Ringwald     // security properties
3613f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3614f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3615f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3616f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3617f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3618f664b5e8SMatthias Ringwald 
3619f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3620f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3621f664b5e8SMatthias Ringwald 
3622f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3623f664b5e8SMatthias Ringwald }
3624f664b5e8SMatthias Ringwald 
3625d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36263deb3ec6SMatthias Ringwald 
3627cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3628cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36299ec2630cSMatthias Ringwald 
36303deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3631711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3632fbe050beSMatthias Ringwald     uint8_t           status;
3633f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3634f664b5e8SMatthias Ringwald 
36353deb3ec6SMatthias Ringwald     switch (packet_type) {
36363deb3ec6SMatthias Ringwald 
36373deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36380e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36393deb3ec6SMatthias Ringwald 
36403deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
36413deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3642be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
36433deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3644899e6e02SMatthias Ringwald 
3645899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3646899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36479305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
36484ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3649899e6e02SMatthias Ringwald                             if (key_size == 16){
3650899e6e02SMatthias Ringwald                                 // ok, let's continue
3651899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3652899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3653899e6e02SMatthias Ringwald                             } else {
3654899e6e02SMatthias Ringwald                                 // invalid, generate random one
36551979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3656899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3657899e6e02SMatthias Ringwald                             }
3658899e6e02SMatthias Ringwald                         } else {
3659899e6e02SMatthias Ringwald                             sm_validate_er_ir();
36608d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3661841468bbSMatthias Ringwald 
3662841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3663841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3664841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3665841468bbSMatthias Ringwald                             }
3666899e6e02SMatthias Ringwald                         }
36671bf086daSMatthias Ringwald 
36681bf086daSMatthias Ringwald                         // restart random address updates after power cycle
36691bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
36703deb3ec6SMatthias Ringwald 					}
36713deb3ec6SMatthias Ringwald 					break;
3672c18be159SMatthias Ringwald 
36732d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
36742d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
36752d095694SMatthias Ringwald 			        // ignore if connection failed
36762d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
36773deb3ec6SMatthias Ringwald 
36782d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
36792d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
36802d095694SMatthias Ringwald 			        if (!sm_conn) break;
36812d095694SMatthias Ringwald 
36822d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
36832d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
36842d095694SMatthias Ringwald                                        con_handle,
36852d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3686f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
36872d095694SMatthias Ringwald                                        addr);
36882d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
36892d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
36902d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
36912d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3692c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
36932d095694SMatthias Ringwald 			        break;
36942d095694SMatthias Ringwald #endif
3695c18be159SMatthias Ringwald 
3696c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3697c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3698c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3699c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3700c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3701c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3702c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3703c18be159SMatthias Ringwald 			        break;
3704c18be159SMatthias Ringwald #endif
3705c18be159SMatthias Ringwald 
37063deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37073deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37083deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3709f664b5e8SMatthias Ringwald                             // ignore if connection failed
3710f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37113deb3ec6SMatthias Ringwald 
3712711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3713711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37143deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37153deb3ec6SMatthias Ringwald 
3716f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3717f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3718f664b5e8SMatthias Ringwald                                                con_handle,
3719f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3720f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3721f664b5e8SMatthias Ringwald                                                addr);
3722687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3723f664b5e8SMatthias Ringwald 
3724f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3725f664b5e8SMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet)){
3726ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3727ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3728f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3729ba9fc867SMatthias Ringwald                             } else {
3730ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3731ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37323deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37333deb3ec6SMatthias Ringwald                             }
37343deb3ec6SMatthias Ringwald                             break;
37353deb3ec6SMatthias Ringwald 
37363deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3737711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3738711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37393deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37403deb3ec6SMatthias Ringwald 
37413deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37423deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37433deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37443deb3ec6SMatthias Ringwald                                 break;
37453deb3ec6SMatthias Ringwald                             }
3746c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3747778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3748778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3749e53be891SMatthias Ringwald                                 break;
3750e53be891SMatthias Ringwald                             }
37513deb3ec6SMatthias Ringwald 
37523deb3ec6SMatthias Ringwald                             // store rand and ediv
37539c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3754f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3755549ad5d2SMatthias Ringwald 
3756549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3757549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37584ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37596c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
376006cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3761549ad5d2SMatthias Ringwald                                     break;
3762549ad5d2SMatthias Ringwald                                 }
37636c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37646c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37656c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37666c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37676c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
37686c39055aSMatthias Ringwald                                         break;
37696c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
37706c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
37716c39055aSMatthias Ringwald                                         break;
37726c39055aSMatthias Ringwald                                     default:
37736c39055aSMatthias Ringwald                                         // wait for irk look doen
37746c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
37756c39055aSMatthias Ringwald                                         break;
37766c39055aSMatthias Ringwald                                 }
37776c39055aSMatthias Ringwald                                 break;
37786c39055aSMatthias Ringwald                             }
3779549ad5d2SMatthias Ringwald 
3780549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
378106cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3782549ad5d2SMatthias Ringwald #else
3783549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3784549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3785549ad5d2SMatthias Ringwald #endif
37863deb3ec6SMatthias Ringwald                             break;
3787804d3e67SMatthias Ringwald 
37883deb3ec6SMatthias Ringwald                         default:
37893deb3ec6SMatthias Ringwald                             break;
37903deb3ec6SMatthias Ringwald                     }
37913deb3ec6SMatthias Ringwald                     break;
37923deb3ec6SMatthias Ringwald 
37933deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
37943b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3795711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37963deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37973deb3ec6SMatthias Ringwald 
37983b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
37993deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38003deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38013deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
380203a9359aSMatthias Ringwald 
3803fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3804fbe050beSMatthias Ringwald 
38055567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
380603a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3807fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3808fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38098d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38108d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38118d4eef95SMatthias Ringwald                                 } else {
381203a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38138d4eef95SMatthias Ringwald                                 }
3814fbe050beSMatthias Ringwald                             } else {
3815e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3816cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38173b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3818cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38193b7fd749SMatthias Ringwald                             }
3820fbe050beSMatthias Ringwald 
3821fbe050beSMatthias Ringwald                             // emit re-encryption complete
382273102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3823fbe050beSMatthias Ringwald 
3824c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3825c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3826c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38270ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
382803a9359aSMatthias Ringwald                             }
382903a9359aSMatthias Ringwald 
38303deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38313deb3ec6SMatthias Ringwald                             break;
3832fbe050beSMatthias Ringwald 
38333deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3834fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3835dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
383642134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38373deb3ec6SMatthias Ringwald                                 // slave
3838bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3839bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3840bbf8db22SMatthias Ringwald                                 } else {
3841f3582630SMatthias 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);
3842bbf8db22SMatthias Ringwald                                 }
38433deb3ec6SMatthias Ringwald                             } else {
38443deb3ec6SMatthias Ringwald                                 // master
3845*61d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38463deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38473deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3848f3582630SMatthias 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);
38493deb3ec6SMatthias Ringwald                                 } else {
38503deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38513deb3ec6SMatthias Ringwald                                 }
38523deb3ec6SMatthias Ringwald                             }
38533deb3ec6SMatthias Ringwald                             break;
3854c18be159SMatthias Ringwald 
3855c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3856c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3857c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3858c18be159SMatthias Ringwald                             // prepare for pairing request
3859c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3860c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3861c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3862c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3863c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3864c18be159SMatthias Ringwald                             }
3865c18be159SMatthias Ringwald                             break;
3866c18be159SMatthias Ringwald #endif
38673deb3ec6SMatthias Ringwald                         default:
38683deb3ec6SMatthias Ringwald                             break;
38693deb3ec6SMatthias Ringwald                     }
38703deb3ec6SMatthias Ringwald                     break;
38713deb3ec6SMatthias Ringwald 
38723deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3873711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3874711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38753deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38763deb3ec6SMatthias Ringwald 
38773deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
38783deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
38793deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
38803deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
38815567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
38825567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
38835567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38845567aa60SMatthias Ringwald                             } else {
38853deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38865567aa60SMatthias Ringwald                             }
38873deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38883deb3ec6SMatthias Ringwald                             break;
38893deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
389042134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38913deb3ec6SMatthias Ringwald                                 // slave
3892f3582630SMatthias 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);
38933deb3ec6SMatthias Ringwald                             } else {
38943deb3ec6SMatthias Ringwald                                 // master
38953deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38963deb3ec6SMatthias Ringwald                             }
38973deb3ec6SMatthias Ringwald                             break;
38983deb3ec6SMatthias Ringwald                         default:
38993deb3ec6SMatthias Ringwald                             break;
39003deb3ec6SMatthias Ringwald                     }
39013deb3ec6SMatthias Ringwald                     break;
39023deb3ec6SMatthias Ringwald 
39033deb3ec6SMatthias Ringwald 
39043deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3905711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3906711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3907711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39083deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39093deb3ec6SMatthias Ringwald 
391003f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39117f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39127f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39137f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39147f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39157f3f442dSMatthias Ringwald                             break;
39167f3f442dSMatthias Ringwald                         default:
391768a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39180ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39197f3f442dSMatthias Ringwald                             break;
392003f736b1SMatthias Ringwald                     }
3921accbde80SMatthias Ringwald 
39223deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39233deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39243deb3ec6SMatthias Ringwald                     break;
39253deb3ec6SMatthias Ringwald 
39263deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
392733373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
39289091c5f5SMatthias Ringwald                         // set local addr for le device db
392933373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39300c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
393133373e40SMatthias Ringwald                     }
393265b44ffdSMatthias Ringwald                     break;
393365b44ffdSMatthias Ringwald                 default:
393465b44ffdSMatthias Ringwald                     break;
39353deb3ec6SMatthias Ringwald 			}
393665b44ffdSMatthias Ringwald             break;
393765b44ffdSMatthias Ringwald         default:
393865b44ffdSMatthias Ringwald             break;
39393deb3ec6SMatthias Ringwald 	}
39403deb3ec6SMatthias Ringwald 
39413deb3ec6SMatthias Ringwald     sm_run();
39423deb3ec6SMatthias Ringwald }
39433deb3ec6SMatthias Ringwald 
39443deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39453deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39463deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39473deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39483deb3ec6SMatthias Ringwald }
39493deb3ec6SMatthias Ringwald 
3950945888f5SMatthias Ringwald 
395131c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3952945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3953945888f5SMatthias Ringwald     switch (method){
3954945888f5SMatthias Ringwald         case JUST_WORKS:
395547fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3956945888f5SMatthias Ringwald             return 1;
3957945888f5SMatthias Ringwald         default:
3958945888f5SMatthias Ringwald             return 0;
3959945888f5SMatthias Ringwald     }
3960945888f5SMatthias Ringwald }
396107036a04SMatthias Ringwald // responder
3962945888f5SMatthias Ringwald 
3963688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3964688a08f9SMatthias Ringwald     switch (method){
3965688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3966688a08f9SMatthias Ringwald             return 1;
3967688a08f9SMatthias Ringwald         default:
3968688a08f9SMatthias Ringwald             return 0;
3969688a08f9SMatthias Ringwald     }
3970688a08f9SMatthias Ringwald }
397140c5d850SMatthias Ringwald 
397240c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
397340c5d850SMatthias Ringwald     switch (method){
397440c5d850SMatthias Ringwald         case PK_RESP_INPUT:
397540c5d850SMatthias Ringwald         case PK_INIT_INPUT:
397647fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
397740c5d850SMatthias Ringwald             return 1;
397840c5d850SMatthias Ringwald         default:
397940c5d850SMatthias Ringwald             return 0;
398040c5d850SMatthias Ringwald     }
398140c5d850SMatthias Ringwald }
398240c5d850SMatthias Ringwald 
398331c09488SMatthias Ringwald #endif
3984688a08f9SMatthias Ringwald 
39853deb3ec6SMatthias Ringwald /**
39863deb3ec6SMatthias Ringwald  * @return ok
39873deb3ec6SMatthias Ringwald  */
39883deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
39893deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
39903deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
39913deb3ec6SMatthias Ringwald         case JUST_WORKS:
39924ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
39933deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
39943deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
399547fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
39964ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
39973deb3ec6SMatthias Ringwald         case OOB:
39984ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
399947fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40004ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40013deb3ec6SMatthias Ringwald         default:
40023deb3ec6SMatthias Ringwald             return 0;
40033deb3ec6SMatthias Ringwald     }
40043deb3ec6SMatthias Ringwald }
40053deb3ec6SMatthias Ringwald 
40068334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40078334d3d8SMatthias Ringwald 
40084c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40094c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40104c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40114c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40124c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40134c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40144c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40154c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40164c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40177a2e6387SMatthias Ringwald             11, // 0x07 master identification
40184c1d1092SMatthias Ringwald             17, // 0x08 identification information
40194c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40204c1d1092SMatthias Ringwald             17, // 0x0a signing information
40214c1d1092SMatthias Ringwald             2,  // 0x0b security request
40224c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40234c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40244c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
40254c1d1092SMatthias Ringwald     };
40263deb3ec6SMatthias Ringwald 
4027c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4028b170b20fSMatthias Ringwald         sm_run();
4029b170b20fSMatthias Ringwald     }
4030b170b20fSMatthias Ringwald 
40313deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
40324ea43905SMatthias Ringwald     if (size == 0u) return;
40334c1d1092SMatthias Ringwald 
40344c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
40354c1d1092SMatthias Ringwald 
40364c1d1092SMatthias Ringwald     // validate pdu size
40374c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
40387a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
40393deb3ec6SMatthias Ringwald 
4040711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
40413deb3ec6SMatthias Ringwald     if (!sm_conn) return;
40423deb3ec6SMatthias Ringwald 
40434c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
404468a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
40450ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4046accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
40473deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
40483deb3ec6SMatthias Ringwald         return;
40493deb3ec6SMatthias Ringwald     }
40503deb3ec6SMatthias Ringwald 
40514c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
40523deb3ec6SMatthias Ringwald 
40533deb3ec6SMatthias Ringwald     int err;
405442134bc6SMatthias Ringwald     UNUSED(err);
40553deb3ec6SMatthias Ringwald 
40564c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
40573d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
40583d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
40593d7fe1e9SMatthias Ringwald         buffer[1] = 3;
40603d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
40613d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
40623d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
40633d7fe1e9SMatthias Ringwald         return;
40643d7fe1e9SMatthias Ringwald     }
40653d7fe1e9SMatthias Ringwald 
4066a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
4067212d735eSMatthias Ringwald     int have_ltk;
4068212d735eSMatthias Ringwald     uint8_t ltk[16];
4069a6ca6916SDavid Lechner #endif
4070212d735eSMatthias Ringwald 
40713deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
40723deb3ec6SMatthias Ringwald 
4073c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
40743deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
40753deb3ec6SMatthias Ringwald             return;
40763deb3ec6SMatthias Ringwald 
407742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
407842134bc6SMatthias Ringwald 
40793deb3ec6SMatthias Ringwald         // Initiator
40803deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
40814c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
40823deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40833deb3ec6SMatthias Ringwald                 break;
40843deb3ec6SMatthias Ringwald             }
408534c39fbdSMatthias Ringwald 
40862c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
40872c041b42SMatthias Ringwald             if (sm_sc_only_mode){
40882c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
40892c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
4090f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
40912c041b42SMatthias Ringwald                     break;
40922c041b42SMatthias Ringwald                 }
40932c041b42SMatthias Ringwald             }
40942c041b42SMatthias Ringwald #endif
40952c041b42SMatthias Ringwald 
409634c39fbdSMatthias Ringwald             // IRK complete?
409734c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
409834c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
4099dc8ca372SMatthias Ringwald                     // start pairing
41003deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
41013deb3ec6SMatthias Ringwald                     break;
4102e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4103e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4104e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
41058549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
41068549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
41078549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
41085567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4109e061bbd4SMatthias Ringwald                     } else {
4110dc8ca372SMatthias Ringwald                         // start pairing
4111e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4112e061bbd4SMatthias Ringwald                     }
4113e061bbd4SMatthias Ringwald                     break;
411434c39fbdSMatthias Ringwald                 default:
41153deb3ec6SMatthias Ringwald                     // otherwise, store security request
41163deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
41173deb3ec6SMatthias Ringwald                     break;
4118dc8ca372SMatthias Ringwald             }
4119dc8ca372SMatthias Ringwald             break;
41203deb3ec6SMatthias Ringwald 
41213deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4122aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4123aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4124aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4125aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4126aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4127aacfafc3SMatthias Ringwald                 break;
4128aacfafc3SMatthias Ringwald             }
4129aacfafc3SMatthias Ringwald 
4130aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41314c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41323deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41333deb3ec6SMatthias Ringwald                 break;
41343deb3ec6SMatthias Ringwald             }
41350af429c6SMatthias Ringwald 
41363deb3ec6SMatthias Ringwald             // store pairing request
41376535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41386535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41393deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41400af429c6SMatthias Ringwald 
41410af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41420af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41430af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41440af429c6SMatthias Ringwald                 err = test_pairing_failure;
41450af429c6SMatthias Ringwald             }
41460af429c6SMatthias Ringwald #endif
41470af429c6SMatthias Ringwald 
41489305033eSMatthias Ringwald             if (err != 0){
4149f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41503deb3ec6SMatthias Ringwald                 break;
41513deb3ec6SMatthias Ringwald             }
4152b41539d5SMatthias Ringwald 
4153b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4154b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4155f3582630SMatthias 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);
4156b41539d5SMatthias Ringwald                 break;
4157b41539d5SMatthias Ringwald             }
4158b41539d5SMatthias Ringwald 
4159136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4160136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41618cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41628cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4163136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4164136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4165136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4166c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4167136d331aSMatthias Ringwald                     }
41688cba5ca3SMatthias Ringwald                 } else {
4169c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
41708cba5ca3SMatthias Ringwald                 }
4171136d331aSMatthias Ringwald                 break;
4172136d331aSMatthias Ringwald             }
4173136d331aSMatthias Ringwald #endif
41743deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
41753deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
41763deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
41773deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4178f3582630SMatthias 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);
41793deb3ec6SMatthias Ringwald             }
41803deb3ec6SMatthias Ringwald             break;
41813deb3ec6SMatthias Ringwald 
41823deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
41834c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
41843deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41853deb3ec6SMatthias Ringwald                 break;
41863deb3ec6SMatthias Ringwald             }
41873deb3ec6SMatthias Ringwald 
41883deb3ec6SMatthias Ringwald             // store s_confirm
41899c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4190192365feSMatthias Ringwald 
4191aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4192aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4193aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4194aa9b34e5SMatthias Ringwald                 break;
4195aa9b34e5SMatthias Ringwald             }
4196aa9b34e5SMatthias Ringwald 
4197192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4198192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4199192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4200192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4201192365feSMatthias Ringwald             }
4202192365feSMatthias Ringwald #endif
42033deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42043deb3ec6SMatthias Ringwald             break;
42053deb3ec6SMatthias Ringwald 
42063deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42074c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42083deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42093deb3ec6SMatthias Ringwald                 break;;
42103deb3ec6SMatthias Ringwald             }
42113deb3ec6SMatthias Ringwald 
42123deb3ec6SMatthias Ringwald             // received random value
42139c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42143deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42153deb3ec6SMatthias Ringwald             break;
421642134bc6SMatthias Ringwald #endif
42173deb3ec6SMatthias Ringwald 
421842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42193deb3ec6SMatthias Ringwald         // Responder
42203deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42213deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42223deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42234c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42243deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42253deb3ec6SMatthias Ringwald                 break;;
42263deb3ec6SMatthias Ringwald             }
42273deb3ec6SMatthias Ringwald 
42283deb3ec6SMatthias Ringwald             // store pairing request
4229212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4230212d735eSMatthias Ringwald 
4231212d735eSMatthias Ringwald             // check if IRK completed
4232212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4233212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4234212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42353deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42363deb3ec6SMatthias Ringwald                     break;
4237212d735eSMatthias Ringwald                 default:
4238212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4239212d735eSMatthias Ringwald                     break;
4240212d735eSMatthias Ringwald             }
4241212d735eSMatthias Ringwald             break;
424242134bc6SMatthias Ringwald #endif
42433deb3ec6SMatthias Ringwald 
424427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4245c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42464c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
424727c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
424827c32905SMatthias Ringwald                 break;
424927c32905SMatthias Ringwald             }
4250bccf5e67SMatthias Ringwald 
4251e53be891SMatthias Ringwald             // store public key for DH Key calculation
4252fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4253fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4254bccf5e67SMatthias Ringwald 
425502658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
425602658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
425702658749SMatthias Ringwald                 log_info("Remote PK matches ours");
425802658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
425902658749SMatthias Ringwald                 break;
426002658749SMatthias Ringwald             }
426102658749SMatthias Ringwald 
4262d1a1f6a4SMatthias Ringwald             // validate public key
4263d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
42649305033eSMatthias Ringwald             if (err != 0){
426502658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4266349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4267bccf5e67SMatthias Ringwald                 break;
4268bccf5e67SMatthias Ringwald             }
4269891bb64aSMatthias Ringwald 
4270d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4271f3582630SMatthias 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);
42723cf37b8cSMatthias Ringwald 
427365a9a04eSMatthias Ringwald 
427465a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
427542134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4276136d331aSMatthias Ringwald                 // responder
4277c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4278136d331aSMatthias Ringwald             } else {
4279136d331aSMatthias Ringwald                 // initiator
4280a1e31e9cSMatthias Ringwald                 // stk generation method
4281a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4282a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4283a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
428447fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4285c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4286a1e31e9cSMatthias Ringwald                         break;
4287a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
428807036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
428907036a04SMatthias Ringwald                         break;
429007036a04SMatthias Ringwald                     case PK_INIT_INPUT:
429147fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
429207036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
429307036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
429407036a04SMatthias Ringwald                             break;
429507036a04SMatthias Ringwald                         }
4296b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4297a1e31e9cSMatthias Ringwald                         break;
4298a1e31e9cSMatthias Ringwald                     case OOB:
4299d1a1f6a4SMatthias Ringwald                         // generate Nx
43004acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43016ca80073SMatthias 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);
4302a1e31e9cSMatthias Ringwald                         break;
43037bbeb3adSMilanka Ringwald                     default:
43047bbeb3adSMilanka Ringwald                         btstack_assert(false);
43057bbeb3adSMilanka Ringwald                         break;
4306a1e31e9cSMatthias Ringwald                 }
4307136d331aSMatthias Ringwald             }
430827c32905SMatthias Ringwald             break;
4309e53be891SMatthias Ringwald 
4310c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43114c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
431245a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
431345a61d50SMatthias Ringwald                 break;
431445a61d50SMatthias Ringwald             }
431545a61d50SMatthias Ringwald             // received confirm value
431645a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
431745a61d50SMatthias Ringwald 
4318192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4319192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4320192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4321192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4322192365feSMatthias Ringwald             }
4323192365feSMatthias Ringwald #endif
432442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
432545a61d50SMatthias Ringwald                 // responder
432607036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
432707036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
432807036a04SMatthias Ringwald                         // still waiting for passkey
432907036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
433007036a04SMatthias Ringwald                         break;
433107036a04SMatthias Ringwald                     }
433207036a04SMatthias Ringwald                 }
4333b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
433445a61d50SMatthias Ringwald             } else {
433545a61d50SMatthias Ringwald                 // initiator
4336945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43376ca80073SMatthias 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);
4338f1c1783eSMatthias Ringwald                 } else {
4339c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
434045a61d50SMatthias Ringwald                 }
4341f1c1783eSMatthias Ringwald             }
434245a61d50SMatthias Ringwald             break;
434345a61d50SMatthias Ringwald 
4344c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43454c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4346e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4347136d331aSMatthias Ringwald                 break;
4348e53be891SMatthias Ringwald             }
4349e53be891SMatthias Ringwald 
4350e53be891SMatthias Ringwald             // received random value
4351e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4352e53be891SMatthias Ringwald 
43535a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4354ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4355d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4356d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4357d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
435865a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4359d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4360688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4361ae451ec5SMatthias Ringwald                  break;
43625a293e6eSMatthias Ringwald             }
43636f52a196SMatthias Ringwald 
43644acf7b7bSMatthias Ringwald             // OOB
43654acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
43664acf7b7bSMatthias Ringwald 
43674acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
43684acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
43694acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43704ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
43714acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
43724acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
43734acf7b7bSMatthias Ringwald                     } else {
43746535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
43754acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
43764acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
43774acf7b7bSMatthias Ringwald                     }
43784acf7b7bSMatthias Ringwald                 }  else {
43794ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
43804acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
43814acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
43824acf7b7bSMatthias Ringwald                     } else {
43836535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
43844acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
43854acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
43864acf7b7bSMatthias Ringwald                     }
43874acf7b7bSMatthias Ringwald                 }
43884acf7b7bSMatthias Ringwald 
4389a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
43904acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4391a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4392a680ba6bSMatthias Ringwald                      break;
4393a680ba6bSMatthias Ringwald                 }
43944acf7b7bSMatthias Ringwald             }
4395a680ba6bSMatthias Ringwald 
4396a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4397688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4398e53be891SMatthias Ringwald             break;
4399e53be891SMatthias Ringwald 
4400901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4401901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44023cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4403901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4404901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4405901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4406901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4407901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4408901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4409901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4410c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4411901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4412d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44134c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4414e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4415e53be891SMatthias Ringwald                 break;
4416e53be891SMatthias Ringwald             }
4417e53be891SMatthias Ringwald             // store DHKey Check
4418901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4419e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4420446a8c36SMatthias Ringwald 
4421901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4422901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4423019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4424bd57ffebSMatthias Ringwald             }
4425bd57ffebSMatthias Ringwald             break;
442627c32905SMatthias Ringwald #endif
442727c32905SMatthias Ringwald 
442842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44293deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44304c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44313deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
443227c32905SMatthias Ringwald                 break;
44333deb3ec6SMatthias Ringwald             }
44343deb3ec6SMatthias Ringwald 
44353deb3ec6SMatthias Ringwald             // received confirm value
44369c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44373deb3ec6SMatthias Ringwald 
4438192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4439192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4440192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4441192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4442192365feSMatthias Ringwald             }
4443192365feSMatthias Ringwald #endif
44443deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44453deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44465611a760SMatthias 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);
44473deb3ec6SMatthias Ringwald             }
44483deb3ec6SMatthias Ringwald 
44493deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44503deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4451f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44523deb3ec6SMatthias Ringwald                 break;
44533deb3ec6SMatthias Ringwald             }
44543deb3ec6SMatthias Ringwald 
44553deb3ec6SMatthias Ringwald             // wait for user action?
44563deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44573deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44583deb3ec6SMatthias Ringwald                 break;
44593deb3ec6SMatthias Ringwald             }
44603deb3ec6SMatthias Ringwald 
44613deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4462f3582630SMatthias 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);
44633deb3ec6SMatthias Ringwald             break;
44643deb3ec6SMatthias Ringwald 
44653deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
44664c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
44673deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
44683deb3ec6SMatthias Ringwald                 break;;
44693deb3ec6SMatthias Ringwald             }
44703deb3ec6SMatthias Ringwald 
44713deb3ec6SMatthias Ringwald             // received random value
44729c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
44733deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
44743deb3ec6SMatthias Ringwald             break;
447542134bc6SMatthias Ringwald #endif
44763deb3ec6SMatthias Ringwald 
44773deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
44784c1d1092SMatthias Ringwald             switch(sm_pdu_code){
44793deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
44803deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
44819c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
44823deb3ec6SMatthias Ringwald                     break;
44833deb3ec6SMatthias Ringwald 
44843deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
44853deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4486f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
44879c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
44883deb3ec6SMatthias Ringwald                     break;
44893deb3ec6SMatthias Ringwald 
44903deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
44913deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
44929c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
44933deb3ec6SMatthias Ringwald                     break;
44943deb3ec6SMatthias Ringwald 
44953deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
44963deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
44973deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4498724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
44993deb3ec6SMatthias Ringwald                     break;
45003deb3ec6SMatthias Ringwald 
45013deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45023deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45039c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45043deb3ec6SMatthias Ringwald                     break;
45053deb3ec6SMatthias Ringwald                 default:
45063deb3ec6SMatthias Ringwald                     // Unexpected PDU
45073deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45083deb3ec6SMatthias Ringwald                     break;
45093deb3ec6SMatthias Ringwald             }
45103deb3ec6SMatthias Ringwald             // done with key distribution?
4511*61d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45123deb3ec6SMatthias Ringwald 
45133deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45143deb3ec6SMatthias Ringwald 
451542134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45166f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45173deb3ec6SMatthias Ringwald                 } else {
4518625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4519625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4520bbf8db22SMatthias Ringwald                     } else {
4521f3582630SMatthias 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);
4522625f00b2SMatthias Ringwald                     }
45233deb3ec6SMatthias Ringwald                 }
45243deb3ec6SMatthias Ringwald             }
45253deb3ec6SMatthias Ringwald             break;
4526c18be159SMatthias Ringwald 
4527c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4528c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4529c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4530c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4531c18be159SMatthias Ringwald                 break;
4532c18be159SMatthias Ringwald             }
4533c18be159SMatthias Ringwald             // store pairing response
4534c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4535c18be159SMatthias Ringwald 
4536c18be159SMatthias Ringwald             // validate encryption key size
4537c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres));
4538c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4539c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4540c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4541c18be159SMatthias Ringwald             }
4542c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4543c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4544c18be159SMatthias Ringwald                 break;
4545c18be159SMatthias Ringwald             }
4546c18be159SMatthias Ringwald 
4547c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4548c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4549c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4550c18be159SMatthias Ringwald 
4551c18be159SMatthias Ringwald             // skip receive if there are none
4552*61d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4553c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4554c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4555c18be159SMatthias Ringwald             } else {
4556c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4557c18be159SMatthias Ringwald             }
4558c18be159SMatthias Ringwald             break;
4559c18be159SMatthias Ringwald 
4560c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4561c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4562c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4563c18be159SMatthias Ringwald                 break;
4564c18be159SMatthias Ringwald             }
4565c18be159SMatthias Ringwald             // store pairing request
4566c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4567c18be159SMatthias Ringwald             // validate encryption key size
4568c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq));
4569c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4570c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4571c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4572c18be159SMatthias Ringwald             }
4573c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4574c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4575c18be159SMatthias Ringwald                 break;
4576c18be159SMatthias Ringwald             }
4577c18be159SMatthias Ringwald             // trigger response
4578c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4579c18be159SMatthias Ringwald             break;
4580c18be159SMatthias Ringwald 
4581c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4582c18be159SMatthias Ringwald             switch(sm_pdu_code){
4583c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4584c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4585c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4586c18be159SMatthias Ringwald                     break;
4587c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4588c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4589c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4590c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4591c18be159SMatthias Ringwald                     break;
4592c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4593c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4594c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4595c18be159SMatthias Ringwald                     break;
4596c18be159SMatthias Ringwald                 default:
4597c18be159SMatthias Ringwald                     // Unexpected PDU
4598c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4599c18be159SMatthias Ringwald                     break;
4600c18be159SMatthias Ringwald             }
4601c18be159SMatthias Ringwald 
4602c18be159SMatthias Ringwald             // all keys received
4603*61d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4604c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4605c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4606c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4607c18be159SMatthias Ringwald                 } else {
4608c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4609c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4610c18be159SMatthias Ringwald                 }
4611c18be159SMatthias Ringwald             }
4612c18be159SMatthias Ringwald             break;
4613c18be159SMatthias Ringwald #endif
4614c18be159SMatthias Ringwald 
46153deb3ec6SMatthias Ringwald         default:
46163deb3ec6SMatthias Ringwald             // Unexpected PDU
46173deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46182d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46193deb3ec6SMatthias Ringwald             break;
46203deb3ec6SMatthias Ringwald     }
46213deb3ec6SMatthias Ringwald 
462270b44dd4SMatthias Ringwald     // try to send next pdu
462370b44dd4SMatthias Ringwald     sm_trigger_run();
46243deb3ec6SMatthias Ringwald }
46253deb3ec6SMatthias Ringwald 
46263deb3ec6SMatthias Ringwald // Security Manager Client API
4627a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46283deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46293deb3ec6SMatthias Ringwald }
46303deb3ec6SMatthias Ringwald 
46314acf7b7bSMatthias 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)){
4632a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4633a680ba6bSMatthias Ringwald }
4634a680ba6bSMatthias Ringwald 
463589a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
463689a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
463789a78d34SMatthias Ringwald }
463889a78d34SMatthias Ringwald 
46393deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46403deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46413deb3ec6SMatthias Ringwald }
46423deb3ec6SMatthias Ringwald 
46433deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46443deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46453deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46463deb3ec6SMatthias Ringwald }
46473deb3ec6SMatthias Ringwald 
46483deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
464998d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
465098d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
465198d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
465298d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
465398d95509SMatthias Ringwald     }
465498d95509SMatthias Ringwald #endif
46553deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
46563deb3ec6SMatthias Ringwald }
46573deb3ec6SMatthias Ringwald 
46583deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
46593deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
46603deb3ec6SMatthias Ringwald }
46613deb3ec6SMatthias Ringwald 
466242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
46633deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
46643deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
46653deb3ec6SMatthias Ringwald }
466642134bc6SMatthias Ringwald #endif
46673deb3ec6SMatthias Ringwald 
46683deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
46696535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
46703deb3ec6SMatthias Ringwald }
46713deb3ec6SMatthias Ringwald 
46723deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
46736535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
46743deb3ec6SMatthias Ringwald }
46753deb3ec6SMatthias Ringwald 
46763deb3ec6SMatthias Ringwald // Testing support only
46773deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
46786535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4679103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4680841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
46813deb3ec6SMatthias Ringwald }
46823deb3ec6SMatthias Ringwald 
46833deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4684841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
46853deb3ec6SMatthias Ringwald }
46863deb3ec6SMatthias Ringwald 
4687d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4688d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4689d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4690d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
469134b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
469270b44dd4SMatthias Ringwald     sm_trigger_run();
4693d1a1f6a4SMatthias Ringwald }
4694674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
469534b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4696674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4697674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4698674e5b4aSMatthias Ringwald }
4699d1a1f6a4SMatthias Ringwald #endif
4700d1a1f6a4SMatthias Ringwald 
4701192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4702192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4703192365feSMatthias Ringwald     test_pairing_failure = reason;
4704192365feSMatthias Ringwald }
4705192365feSMatthias Ringwald #endif
4706192365feSMatthias Ringwald 
47073deb3ec6SMatthias Ringwald void sm_init(void){
47082d2d4d3cSMatthias Ringwald 
47092d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47102d2d4d3cSMatthias Ringwald 
4711899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4712899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4713899e6e02SMatthias Ringwald 
47143deb3ec6SMatthias Ringwald     // defaults
47153deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47163deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4717b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4718b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4719b4343428SMatthias Ringwald 
47203deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47213deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47223deb3ec6SMatthias Ringwald 
47235ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47241979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4725caf15bf3SMatthias Ringwald 
4726d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4727d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47287a766ebfSMatthias Ringwald #endif
47298d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4730fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47313deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47323deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47333deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47343deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47353deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47363deb3ec6SMatthias Ringwald 
47373deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47387149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47393deb3ec6SMatthias Ringwald 
4740841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47413deb3ec6SMatthias Ringwald 
474284c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
474384c0c5c7SMatthias Ringwald 
4744e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4745e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4746e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4747e03e489aSMatthias Ringwald 
4748d1a1f6a4SMatthias Ringwald     //
4749d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4750d1a1f6a4SMatthias Ringwald 
475151bd74d1SMatthias Ringwald     // init le_device_db
475251bd74d1SMatthias Ringwald     le_device_db_init();
475351bd74d1SMatthias Ringwald 
4754b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4755e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
475627c32905SMatthias Ringwald 
475709e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4758674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4759a3aba2f9SMatthias Ringwald #endif
47602d2d4d3cSMatthias Ringwald 
47612d2d4d3cSMatthias Ringwald     sm_initialized = true;
47623deb3ec6SMatthias Ringwald }
47633deb3ec6SMatthias Ringwald 
476415537ea4SMatthias Ringwald void sm_deinit(void){
476515537ea4SMatthias Ringwald     sm_initialized = false;
476615537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
476715537ea4SMatthias Ringwald }
476815537ea4SMatthias Ringwald 
47694b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
47704b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4771caf15bf3SMatthias Ringwald }
4772caf15bf3SMatthias Ringwald 
47736c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
47741979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
47756c39055aSMatthias Ringwald }
47766c39055aSMatthias Ringwald 
4777711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4778711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
47793deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
47803deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
47813deb3ec6SMatthias Ringwald }
47823deb3ec6SMatthias Ringwald 
478377e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
478477e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
478577e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
478677e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
478777e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
478877e2e5edSMatthias Ringwald }
478977e2e5edSMatthias Ringwald #endif
479077e2e5edSMatthias Ringwald 
47916bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4792711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4793711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47943deb3ec6SMatthias Ringwald     if (!sm_conn) return;
47956bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
47966bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
47973deb3ec6SMatthias Ringwald }
47983deb3ec6SMatthias Ringwald 
47993deb3ec6SMatthias Ringwald // request pairing
4800711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4801711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48023deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48033deb3ec6SMatthias Ringwald 
48047af5dcd5SMatthias Ringwald     bool have_ltk;
48057af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48063deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
480742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
480824c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
480924c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
481024c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48117af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48127af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48137af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48147af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48157af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48167af5dcd5SMatthias Ringwald                         if (have_ltk){
48177af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
481824c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48197af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48207af5dcd5SMatthias Ringwald                             break;
48217af5dcd5SMatthias Ringwald                         }
48227af5dcd5SMatthias Ringwald                         /* fall through */
48237af5dcd5SMatthias Ringwald 
48247af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48257af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48267af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48277af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48287af5dcd5SMatthias Ringwald                         break;
48297af5dcd5SMatthias Ringwald                     default:
48307af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48317af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48327af5dcd5SMatthias Ringwald                         break;
48337af5dcd5SMatthias Ringwald                 }
483424c20dc4SMatthias Ringwald                 break;
483524c20dc4SMatthias Ringwald             default:
483624c20dc4SMatthias Ringwald                 break;
483724c20dc4SMatthias Ringwald         }
48383deb3ec6SMatthias Ringwald     } else {
48393deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4840175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4841175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48423deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48433deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48443dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4845f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4846f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4847f53ec649SMatthias Ringwald                         if (have_ltk){
4848c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48495567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4850c245ca32SMatthias Ringwald                             break;
4851f53ec649SMatthias Ringwald                         }
4852cf373d3aSMatthias Ringwald                         /* fall through */
4853c245ca32SMatthias Ringwald 
485434c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48553deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
48563deb3ec6SMatthias Ringwald                         break;
48573deb3ec6SMatthias Ringwald                     default:
4858d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
485909ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48603deb3ec6SMatthias Ringwald                         break;
48613deb3ec6SMatthias Ringwald                 }
4862175b7faaSMatthias Ringwald                 break;
4863cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4864cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4865cb6d7eb0SMatthias Ringwald                 break;
4866175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
486709ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4868175b7faaSMatthias Ringwald                 break;
4869175b7faaSMatthias Ringwald             default:
4870175b7faaSMatthias Ringwald                 break;
48713deb3ec6SMatthias Ringwald         }
48723deb3ec6SMatthias Ringwald     }
487370b44dd4SMatthias Ringwald     sm_trigger_run();
48743deb3ec6SMatthias Ringwald }
48753deb3ec6SMatthias Ringwald 
48763deb3ec6SMatthias Ringwald // called by client app on authorization request
4877711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4878711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48793deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48803deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4881589f5a99SMatthias 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);
48823deb3ec6SMatthias Ringwald }
48833deb3ec6SMatthias Ringwald 
4884711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4885711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48863deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48873deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4888589f5a99SMatthias Ringwald     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1);
48893deb3ec6SMatthias Ringwald }
48903deb3ec6SMatthias Ringwald 
48913deb3ec6SMatthias Ringwald // GAP Bonding API
48923deb3ec6SMatthias Ringwald 
4893711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4894711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48953deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48963deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
48970af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
48980af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
48990af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49000af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49010af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49020af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49030af429c6SMatthias Ringwald #endif
49040af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4905de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4906de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4907de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
490847fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49090af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4910de2fd182SMatthias Ringwald                     break;
491147fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4912de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4913de2fd182SMatthias Ringwald                     break;
4914de2fd182SMatthias Ringwald                 case JUST_WORKS:
4915de2fd182SMatthias Ringwald                 case OOB:
4916de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4917de2fd182SMatthias Ringwald                     break;
49187bbeb3adSMilanka Ringwald                 default:
49197bbeb3adSMilanka Ringwald                     btstack_assert(false);
49207bbeb3adSMilanka Ringwald                     break;
4921de2fd182SMatthias Ringwald             }
49220af429c6SMatthias Ringwald             break;
49230af429c6SMatthias Ringwald         default:
49240af429c6SMatthias Ringwald             break;
49253deb3ec6SMatthias Ringwald     }
492670b44dd4SMatthias Ringwald     sm_trigger_run();
49273deb3ec6SMatthias Ringwald }
49283deb3ec6SMatthias Ringwald 
4929711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4930711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49313deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49323deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49333deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4934136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4935c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4936bbf8db22SMatthias Ringwald         } else {
4937f3582630SMatthias 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);
4938136d331aSMatthias Ringwald         }
49393deb3ec6SMatthias Ringwald     }
49400346c37cSMatthias Ringwald 
49410346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4942c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4943dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4944446a8c36SMatthias Ringwald     }
49450346c37cSMatthias Ringwald #endif
49460346c37cSMatthias Ringwald 
494770b44dd4SMatthias Ringwald     sm_trigger_run();
49483deb3ec6SMatthias Ringwald }
49493deb3ec6SMatthias Ringwald 
4950c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4951c8c46d51SMatthias Ringwald     // for now, it's the same
4952c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4953c8c46d51SMatthias Ringwald }
4954c8c46d51SMatthias Ringwald 
4955711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4956711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49573deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49583deb3ec6SMatthias Ringwald     sm_reset_tk();
4959f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
49603deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
49613deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4962f3582630SMatthias 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);
49633deb3ec6SMatthias Ringwald     }
49641c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49656535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
49666535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
496707036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
496807036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
496907036a04SMatthias Ringwald     }
49701c516d8fSMatthias Ringwald #endif
497170b44dd4SMatthias Ringwald     sm_trigger_run();
49723deb3ec6SMatthias Ringwald }
49733deb3ec6SMatthias Ringwald 
49743d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
49753d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49763d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49773d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4978dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
49794ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4980dd4a08fbSMatthias Ringwald     switch (action){
4981dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4982dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
49834ea43905SMatthias Ringwald             flags |= (1u << action);
4984dd4a08fbSMatthias Ringwald             break;
4985dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4986dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
49874ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4988dd4a08fbSMatthias Ringwald             break;
4989dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
49904ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4991dd4a08fbSMatthias Ringwald                 // erase actions queued
4992dd4a08fbSMatthias Ringwald                 num_actions--;
49934ea43905SMatthias Ringwald                 if (num_actions == 0u){
4994dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
49954ea43905SMatthias Ringwald                     flags &= 0x19u;
4996dd4a08fbSMatthias Ringwald                 }
4997dd4a08fbSMatthias Ringwald                 break;
4998dd4a08fbSMatthias Ringwald             }
4999dd4a08fbSMatthias Ringwald             num_actions++;
50004ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5001dd4a08fbSMatthias Ringwald             break;
5002dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50034ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5004dd4a08fbSMatthias Ringwald                 // enter actions queued
5005dd4a08fbSMatthias Ringwald                 num_actions--;
50064ea43905SMatthias Ringwald                 if (num_actions == 0u){
5007dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50084ea43905SMatthias Ringwald                     flags &= 0x19u;
5009dd4a08fbSMatthias Ringwald                 }
5010dd4a08fbSMatthias Ringwald                 break;
5011dd4a08fbSMatthias Ringwald             }
5012dd4a08fbSMatthias Ringwald             num_actions++;
50134ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5014dd4a08fbSMatthias Ringwald             break;
5015dd4a08fbSMatthias Ringwald         default:
5016dd4a08fbSMatthias Ringwald             break;
5017dd4a08fbSMatthias Ringwald     }
5018dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
501970b44dd4SMatthias Ringwald     sm_trigger_run();
50203d7fe1e9SMatthias Ringwald }
50213d7fe1e9SMatthias Ringwald 
5022c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5023d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5024d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5025d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
502670b44dd4SMatthias Ringwald     sm_trigger_run();
5027d1a1f6a4SMatthias Ringwald }
5028c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50298334d3d8SMatthias Ringwald 
50308334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50318334d3d8SMatthias Ringwald 
5032c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5033c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5034d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5035d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5036c59d0c92SMatthias Ringwald     return 0;
5037c59d0c92SMatthias Ringwald }
5038c59d0c92SMatthias Ringwald #endif
5039c59d0c92SMatthias Ringwald 
50403deb3ec6SMatthias Ringwald /**
5041ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5042ba394633SMatthias Ringwald  * @param con_handle
5043ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5044ba394633SMatthias Ringwald  */
5045ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5046ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5047ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5048ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5049ba394633SMatthias Ringwald }
5050ba394633SMatthias Ringwald 
5051ba394633SMatthias Ringwald /**
50523deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50533deb3ec6SMatthias Ringwald  * @param handle
50543deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
50553deb3ec6SMatthias Ringwald  */
5056711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5057711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50583deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
50593deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
50603deb3ec6SMatthias Ringwald }
50613deb3ec6SMatthias Ringwald 
50628f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
506347ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
506447ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
506547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
506647ba4de1SMatthias Ringwald             return 0;
506747ba4de1SMatthias Ringwald         default:
50688f57b085SMatthias Ringwald             return 1;
50698f57b085SMatthias Ringwald     }
507047ba4de1SMatthias Ringwald }
5071d70217a2SMatthias Ringwald 
507233373e40SMatthias Ringwald static uint8_t own_address_type(void){
5073b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5074b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5075b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5076b95a5a35SMatthias Ringwald         default:
5077b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5078b95a5a35SMatthias Ringwald     }
507933373e40SMatthias Ringwald }
50808f57b085SMatthias Ringwald 
50813deb3ec6SMatthias Ringwald // GAP LE API
50823deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
50833deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
50843deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5085b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
50868f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
50873deb3ec6SMatthias Ringwald     gap_random_address_update_start();
50883deb3ec6SMatthias Ringwald     gap_random_address_trigger();
50893deb3ec6SMatthias Ringwald }
50903deb3ec6SMatthias Ringwald 
50913deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
50923deb3ec6SMatthias Ringwald     return gap_random_adress_type;
50933deb3ec6SMatthias Ringwald }
50943deb3ec6SMatthias Ringwald 
50953deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
50963deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
50978f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
50983deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
50993deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51003deb3ec6SMatthias Ringwald }
51013deb3ec6SMatthias Ringwald 
5102667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51038f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51046535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
51057e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
510670b44dd4SMatthias Ringwald     sm_trigger_run();
51077e252622SMatthias Ringwald }
51087e252622SMatthias Ringwald 
5109d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51103deb3ec6SMatthias Ringwald /*
51113deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51123deb3ec6SMatthias Ringwald  * @param adv_int_min
51133deb3ec6SMatthias Ringwald  * @param adv_int_max
51143deb3ec6SMatthias Ringwald  * @param adv_type
51153deb3ec6SMatthias Ringwald  * @param direct_address_type
51163deb3ec6SMatthias Ringwald  * @param direct_address
51173deb3ec6SMatthias Ringwald  * @param channel_map
51183deb3ec6SMatthias Ringwald  * @param filter_policy
51193deb3ec6SMatthias Ringwald  *
51203deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51213deb3ec6SMatthias Ringwald  */
51223deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51233deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5124b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51253deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51263deb3ec6SMatthias Ringwald }
5127d70217a2SMatthias Ringwald #endif
5128dcd6c9b5SMatthias Ringwald 
5129dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5130dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5131dcd6c9b5SMatthias Ringwald      // wrong connection
5132dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5133dcd6c9b5SMatthias Ringwald     // already encrypted
5134dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5135dcd6c9b5SMatthias Ringwald     // irk status?
5136dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5137dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5138dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5139dcd6c9b5SMatthias Ringwald             return 0;
5140dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5141dcd6c9b5SMatthias Ringwald             break;
5142dcd6c9b5SMatthias Ringwald         default:
5143dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5144dcd6c9b5SMatthias Ringwald             return 1;
5145dcd6c9b5SMatthias Ringwald     }
5146f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5147f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5148b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5149b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5150b15d5ceaSMatthias Ringwald     } else {
5151dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5152dcd6c9b5SMatthias Ringwald     }
5153b15d5ceaSMatthias Ringwald }
51543cdbe9dbSMatthias Ringwald 
51553cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
51563cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51573cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
51583cdbe9dbSMatthias Ringwald #else
51593cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
51603cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
51613cdbe9dbSMatthias Ringwald #endif
51623cdbe9dbSMatthias Ringwald }
5163052bbdc5SMatthias Ringwald 
5164052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5165052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5166052bbdc5SMatthias Ringwald }
51674f384501SMatthias Ringwald 
51684f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
51694f384501SMatthias Ringwald     uint16_t i;
51704f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
51714f384501SMatthias Ringwald         bd_addr_t entry_address;
51724f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
51734f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
51744f384501SMatthias Ringwald         // skip unused entries
51754f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
51764f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
51774f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
51784f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
51794f384501SMatthias Ringwald #endif
51804f384501SMatthias Ringwald             le_device_db_remove(i);
51814f384501SMatthias Ringwald             break;
51824f384501SMatthias Ringwald         }
51834f384501SMatthias Ringwald     }
51844f384501SMatthias Ringwald }
5185