xref: /btstack/src/ble/sm.c (revision e0a03c851c5ede253cec6e5d61b397f843364e16)
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
373*e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
374*e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
375*e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
376*e0a03c85SMatthias 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 
10753deb3ec6SMatthias Ringwald static int sm_key_distribution_all_received(sm_connection_t * sm_conn){
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;
1696*e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1697*e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1698*e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1699*e0a03c85SMatthias Ringwald             break;
1700*e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1701*e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1702*e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1703*e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1704*e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1705*e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1706*e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1707*e0a03c85SMatthias Ringwald             break;
1708bdb14b0eSMatthias Ringwald #endif
1709bd57ffebSMatthias Ringwald         default:
1710bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1711bd57ffebSMatthias Ringwald             break;
1712bd57ffebSMatthias Ringwald     }
171370b44dd4SMatthias Ringwald     sm_trigger_run();
1714aec94140SMatthias Ringwald }
1715aec94140SMatthias Ringwald 
1716688a08f9SMatthias Ringwald static void f4_engine(sm_connection_t * sm_conn, const sm_key256_t u, const sm_key256_t v, const sm_key_t x, uint8_t z){
1717dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1718aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17196535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17206535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1721aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1722aec94140SMatthias Ringwald     log_info("f4 key");
1723aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1724aec94140SMatthias Ringwald     log_info("f4 message");
1725dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1726d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1727aec94140SMatthias Ringwald }
1728aec94140SMatthias Ringwald 
17290346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17300346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17310346c37cSMatthias Ringwald 
17320346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17338334d3d8SMatthias Ringwald 
17348334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17358334d3d8SMatthias Ringwald 
173640c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17370346c37cSMatthias Ringwald     // calculate salt for f5
17380346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17390346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17406535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1741d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17420346c37cSMatthias Ringwald }
17430346c37cSMatthias Ringwald 
17440346c37cSMatthias Ringwald static inline void f5_mackkey(sm_connection_t * sm_conn, sm_key_t t, const sm_key_t n1, const sm_key_t n2, const sm_key56_t a1, const sm_key56_t a2){
17450346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17460346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17470346c37cSMatthias Ringwald 
17480346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17490346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17506535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17516535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17560346c37cSMatthias Ringwald     log_info("f5 key");
17570346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17580346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17590346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1760d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17610346c37cSMatthias Ringwald }
17620346c37cSMatthias Ringwald 
17630346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17640346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17650346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17660346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17676535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17686535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
176942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17700346c37cSMatthias Ringwald         // responder
17710346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17720346c37cSMatthias Ringwald     } else {
17730346c37cSMatthias Ringwald         // initiator
17740346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17750346c37cSMatthias Ringwald     }
17760346c37cSMatthias Ringwald }
17770346c37cSMatthias Ringwald 
17780346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17790346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17800346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17810346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17820346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17830346c37cSMatthias Ringwald     // 1..52 setup before
17840346c37cSMatthias Ringwald     log_info("f5 key");
17850346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17860346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17870346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1788d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17890346c37cSMatthias Ringwald }
1790f92edc8eSMatthias Ringwald 
17910346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17920346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17930346c37cSMatthias Ringwald }
17940346c37cSMatthias Ringwald 
179531f061fbSMatthias Ringwald static void f6_setup(const sm_key_t n1, const sm_key_t n2, const sm_key_t r, const sm_key24_t io_cap, const sm_key56_t a1, const sm_key56_t a2){
17966535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17976535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17986535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18006535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
180231f061fbSMatthias Ringwald }
180331f061fbSMatthias Ringwald 
180431f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180531f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180631f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1807dc300847SMatthias Ringwald     log_info("f6 key");
1808dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1809dc300847SMatthias Ringwald     log_info("f6 message");
1810dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1811d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1812dc300847SMatthias Ringwald }
1813dc300847SMatthias Ringwald 
1814f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1815f92edc8eSMatthias Ringwald // - U is 256 bits
1816f92edc8eSMatthias Ringwald // - V is 256 bits
1817f92edc8eSMatthias Ringwald // - X is 128 bits
1818f92edc8eSMatthias Ringwald // - Y is 128 bits
1819bd57ffebSMatthias Ringwald static void g2_engine(sm_connection_t * sm_conn, const sm_key256_t u, const sm_key256_t v, const sm_key_t x, const sm_key_t y){
1820bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1821bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18226535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18236535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18246535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1825f92edc8eSMatthias Ringwald     log_info("g2 key");
1826f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1827f92edc8eSMatthias Ringwald     log_info("g2 message");
18282bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1829d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1830f92edc8eSMatthias Ringwald }
1831f92edc8eSMatthias Ringwald 
1832b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1833f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
183442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1835f92edc8eSMatthias Ringwald         // responder
1836fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1837f92edc8eSMatthias Ringwald     } else {
1838f92edc8eSMatthias Ringwald         // initiator
1839fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1840f92edc8eSMatthias Ringwald     }
1841f92edc8eSMatthias Ringwald }
1842f92edc8eSMatthias Ringwald 
1843945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18449af0f475SMatthias Ringwald     uint8_t z = 0;
184540c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18469af0f475SMatthias Ringwald         // some form of passkey
18479af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18484ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18499af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18509af0f475SMatthias Ringwald     }
1851fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18529af0f475SMatthias Ringwald }
1853688a08f9SMatthias Ringwald 
1854688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1855a680ba6bSMatthias Ringwald     // OOB
1856a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18574acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18584acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18594acf7b7bSMatthias Ringwald         } else {
18604acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18614acf7b7bSMatthias Ringwald         }
1862a680ba6bSMatthias Ringwald         return;
1863a680ba6bSMatthias Ringwald     }
1864a680ba6bSMatthias Ringwald 
1865688a08f9SMatthias Ringwald     uint8_t z = 0;
186640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1867688a08f9SMatthias Ringwald         // some form of passkey
1868688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1869688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18704ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1871688a08f9SMatthias Ringwald     }
1872fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1873688a08f9SMatthias Ringwald }
1874688a08f9SMatthias Ringwald 
18750346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1876505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18773cf37b8cSMatthias Ringwald 
18783cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18793cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18803cf37b8cSMatthias Ringwald         return;
18813cf37b8cSMatthias Ringwald     } else {
18823cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18833cf37b8cSMatthias Ringwald     }
1884d1a1f6a4SMatthias Ringwald }
18853cf37b8cSMatthias Ringwald 
1886d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1887f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1888f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1889f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1890f3582630SMatthias Ringwald 
1891d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1892d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1893d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1894d1a1f6a4SMatthias Ringwald     // trigger next step
1895d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1896d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1897d1a1f6a4SMatthias Ringwald     }
189870b44dd4SMatthias Ringwald     sm_trigger_run();
1899dc300847SMatthias Ringwald }
1900dc300847SMatthias Ringwald 
1901dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1902dc300847SMatthias Ringwald     // calculate DHKCheck
1903dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1904dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1905dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19066535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19076535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1908dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1909dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1910dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1911dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1912dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1913dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1914dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1915dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1917dc300847SMatthias Ringwald         // responder
191831f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
191931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1920dc300847SMatthias Ringwald     } else {
1921dc300847SMatthias Ringwald         // initiator
192231f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192331f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1924dc300847SMatthias Ringwald     }
1925dc300847SMatthias Ringwald }
1926dc300847SMatthias Ringwald 
1927019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1928019005a0SMatthias Ringwald     // validate E = f6()
1929019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1930019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1931019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19326535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19336535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1934019005a0SMatthias Ringwald 
1935019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1936019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1937019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1938019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1939019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1940019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1941019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1942019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
194342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1944019005a0SMatthias Ringwald         // responder
194531f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194631f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1947019005a0SMatthias Ringwald     } else {
1948019005a0SMatthias Ringwald         // initiator
194931f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
195031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1951019005a0SMatthias Ringwald     }
1952019005a0SMatthias Ringwald }
19532bacf595SMatthias Ringwald 
195455c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19552bacf595SMatthias Ringwald 
19562bacf595SMatthias Ringwald //
19572bacf595SMatthias Ringwald // Link Key Conversion Function h6
19582bacf595SMatthias Ringwald //
195957132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19602bacf595SMatthias Ringwald // - W is 128 bits
19612bacf595SMatthias Ringwald // - keyID is 32 bits
19622bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19632bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19642bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19652bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19662bacf595SMatthias Ringwald     log_info("h6 key");
19672bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19682bacf595SMatthias Ringwald     log_info("h6 message");
19692bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1970d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19712bacf595SMatthias Ringwald }
197257132f12SMatthias Ringwald //
197357132f12SMatthias Ringwald // Link Key Conversion Function h7
197457132f12SMatthias Ringwald //
197557132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197657132f12SMatthias Ringwald // - SALT is 128 bits
197757132f12SMatthias Ringwald // - W    is 128 bits
197857132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
197957132f12SMatthias Ringwald 	const uint16_t message_len = 16;
198057132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
198157132f12SMatthias Ringwald 	log_info("h7 key");
198257132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
198357132f12SMatthias Ringwald 	log_info("h7 message");
198457132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198557132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198657132f12SMatthias Ringwald }
19872bacf595SMatthias Ringwald 
1988b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1989b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1990b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1991b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
199257132f12SMatthias Ringwald 
1993c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1994b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19952bacf595SMatthias Ringwald }
19962bacf595SMatthias Ringwald 
1997*e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
1998*e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
1999*e0a03c85SMatthias Ringwald }
2000*e0a03c85SMatthias Ringwald 
20012bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20022bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20032bacf595SMatthias Ringwald }
20042bacf595SMatthias Ringwald 
2005*e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2006*e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2007*e0a03c85SMatthias Ringwald }
2008*e0a03c85SMatthias Ringwald 
2009c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
201057132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
201157132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
201257132f12SMatthias Ringwald }
2013*e0a03c85SMatthias Ringwald 
2014*e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2015*e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2016*e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2017*e0a03c85SMatthias Ringwald }
2018*e0a03c85SMatthias Ringwald 
2019*e0a03c85SMatthias Ringwald static void ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2020*e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2021*e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2022*e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2023*e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2024*e0a03c85SMatthias Ringwald }
2025*e0a03c85SMatthias Ringwald 
20269af0f475SMatthias Ringwald #endif
20279af0f475SMatthias Ringwald 
202855c62cf5SMatthias Ringwald #endif
202955c62cf5SMatthias Ringwald 
2030613da3deSMatthias Ringwald // key management legacy connections:
2031613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2032613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2033613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2034613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2035613da3deSMatthias Ringwald 
2036613da3deSMatthias Ringwald // key management secure connections:
2037613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2038613da3deSMatthias Ringwald 
203942134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20405829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20415829ebe2SMatthias Ringwald     int encryption_key_size;
20425829ebe2SMatthias Ringwald     int authenticated;
20435829ebe2SMatthias Ringwald     int authorized;
20443dc3a67dSMatthias Ringwald     int secure_connection;
20455829ebe2SMatthias Ringwald 
20465829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20475829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20483dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20493dc3a67dSMatthias 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);
20505829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20515829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20525829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20533dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20545829ebe2SMatthias Ringwald }
205542134bc6SMatthias Ringwald #endif
2056bd57ffebSMatthias Ringwald 
205742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
205859066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20596535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
206059066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
206159066796SMatthias Ringwald     // re-establish used key encryption size
206259066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20634ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
206459066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20654ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20663dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20673dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
206859066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
206959066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
207059066796SMatthias Ringwald }
207142134bc6SMatthias Ringwald #endif
207259066796SMatthias Ringwald 
20733deb3ec6SMatthias Ringwald // distributed key generation
2074d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20753deb3ec6SMatthias Ringwald     switch (dkg_state){
20763deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20773deb3ec6SMatthias Ringwald             // already busy?
20783deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2079d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20803deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2081d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2082d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2083d1a1f6a4SMatthias 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);
2084d7f1c72eSMatthias Ringwald                 return true;
20853deb3ec6SMatthias Ringwald             }
20863deb3ec6SMatthias Ringwald             break;
20873deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20883deb3ec6SMatthias Ringwald             // already busy?
20893deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2090d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20913deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2092d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2093d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2094d1a1f6a4SMatthias 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);
2095d7f1c72eSMatthias Ringwald                 return true;
20963deb3ec6SMatthias Ringwald             }
20973deb3ec6SMatthias Ringwald             break;
20983deb3ec6SMatthias Ringwald         default:
20993deb3ec6SMatthias Ringwald             break;
21003deb3ec6SMatthias Ringwald     }
2101d7f1c72eSMatthias Ringwald     return false;
2102d7f1c72eSMatthias Ringwald }
21033deb3ec6SMatthias Ringwald 
21043deb3ec6SMatthias Ringwald // random address updates
2105d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21063deb3ec6SMatthias Ringwald     switch (rau_state){
2107fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2108fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21095b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2110d7f1c72eSMatthias Ringwald             return true;
21113deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21123deb3ec6SMatthias Ringwald             // already busy?
21133deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2114d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2115d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2116d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2117d7f1c72eSMatthias Ringwald                 return true;
21183deb3ec6SMatthias Ringwald             }
21193deb3ec6SMatthias Ringwald             break;
21203deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
21213deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
21223deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
21233deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2124d7f1c72eSMatthias Ringwald             return true;
21253deb3ec6SMatthias Ringwald         default:
21263deb3ec6SMatthias Ringwald             break;
21273deb3ec6SMatthias Ringwald     }
2128d7f1c72eSMatthias Ringwald     return false;
2129d7f1c72eSMatthias Ringwald }
21303deb3ec6SMatthias Ringwald 
21313deb3ec6SMatthias Ringwald // CSRK Lookup
2132d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2133d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2134d7f1c72eSMatthias Ringwald 
21353deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21363deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21373deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2138665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2139665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21403deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21413deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21423deb3ec6SMatthias Ringwald                 // and start lookup
21433deb3ec6SMatthias Ringwald                 sm_address_resolution_start_lookup(sm_connection->sm_peer_addr_type, sm_connection->sm_handle, sm_connection->sm_peer_address, ADDRESS_RESOLUTION_FOR_CONNECTION, sm_connection);
21443deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21453deb3ec6SMatthias Ringwald                 break;
21463deb3ec6SMatthias Ringwald             }
21473deb3ec6SMatthias Ringwald         }
21483deb3ec6SMatthias Ringwald     }
21493deb3ec6SMatthias Ringwald 
21503deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21513deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2152665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21533deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2154665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21553deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21563deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21573deb3ec6SMatthias Ringwald         }
21583deb3ec6SMatthias Ringwald     }
21593deb3ec6SMatthias Ringwald 
21603deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21613deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2162092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2163092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2164adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21653deb3ec6SMatthias Ringwald             bd_addr_t addr;
21663deb3ec6SMatthias Ringwald             sm_key_t irk;
21673deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21683deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21693deb3ec6SMatthias Ringwald 
2170adf5eaa9SMatthias Ringwald             // skip unused entries
2171adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2172adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2173adf5eaa9SMatthias Ringwald                 continue;
2174adf5eaa9SMatthias Ringwald             }
2175adf5eaa9SMatthias Ringwald 
21765df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21773deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2178a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21793deb3ec6SMatthias Ringwald                 break;
21803deb3ec6SMatthias Ringwald             }
21813deb3ec6SMatthias Ringwald 
2182a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2183a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21843deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21853deb3ec6SMatthias Ringwald                 continue;
21863deb3ec6SMatthias Ringwald             }
21873deb3ec6SMatthias Ringwald 
21883deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21893deb3ec6SMatthias Ringwald 
21903deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21918314c363SMatthias Ringwald             log_info_key("IRK", irk);
21923deb3ec6SMatthias Ringwald 
21936535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2194d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21953deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2196d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2197d1a1f6a4SMatthias Ringwald             btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL);
2198d7f1c72eSMatthias Ringwald             return true;
21993deb3ec6SMatthias Ringwald         }
22003deb3ec6SMatthias Ringwald 
2201092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22023deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22033deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22043deb3ec6SMatthias Ringwald         }
22053deb3ec6SMatthias Ringwald     }
2206d7f1c72eSMatthias Ringwald     return false;
2207d7f1c72eSMatthias Ringwald }
22083deb3ec6SMatthias Ringwald 
2209d7f1c72eSMatthias Ringwald // SC OOB
2210d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2211c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2212c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2213c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2214c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2215c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2216c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2217d7f1c72eSMatthias Ringwald             return true;
2218c59d0c92SMatthias Ringwald         default:
2219c59d0c92SMatthias Ringwald             break;
2220c59d0c92SMatthias Ringwald     }
2221c59d0c92SMatthias Ringwald #endif
2222d7f1c72eSMatthias Ringwald     return false;
2223d7f1c72eSMatthias Ringwald }
2224275aafe8SMatthias Ringwald 
2225687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2226687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2227687a03c8SMatthias Ringwald }
2228687a03c8SMatthias Ringwald 
222941d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2230d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2231d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
223241d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2233e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
223441d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
223541d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
223641d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2237f4935286SMatthias Ringwald 
2238f4935286SMatthias Ringwald             // general
2239f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2240f4935286SMatthias Ringwald                 uint8_t buffer[2];
2241f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2242f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2243f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2244687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2245f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2246f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2247f4935286SMatthias Ringwald                 break;
2248f4935286SMatthias Ringwald             }
2249f4935286SMatthias Ringwald 
225041d32297SMatthias Ringwald             // responder side
225141d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
225241d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
225341d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2254d7f1c72eSMatthias Ringwald                 return true;
22554b8b5afeSMatthias Ringwald 
22564b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22574b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22584b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22594b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2260e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22614b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22624b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2263d7f1c72eSMatthias Ringwald                         return true;
22644b8b5afeSMatthias Ringwald                     default:
22654b8b5afeSMatthias Ringwald                         break;
22664b8b5afeSMatthias Ringwald                 }
22674b8b5afeSMatthias Ringwald                 break;
22684b8b5afeSMatthias Ringwald #endif
226941d32297SMatthias Ringwald             default:
227041d32297SMatthias Ringwald                 break;
227141d32297SMatthias Ringwald         }
227241d32297SMatthias Ringwald     }
2273d7f1c72eSMatthias Ringwald     return false;
2274d7f1c72eSMatthias Ringwald }
22753deb3ec6SMatthias Ringwald 
2276d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22773deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2278d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22793deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22807149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2281665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22823deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22833deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22841979f09cSMatthias Ringwald         bool done = true;
22853deb3ec6SMatthias Ringwald         int err;
228642134bc6SMatthias Ringwald         UNUSED(err);
228734b6528fSMatthias Ringwald 
228834b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
228934b6528fSMatthias Ringwald         // assert ec key is ready
2290505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2291178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2292178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
229334b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
229434b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
229534b6528fSMatthias Ringwald             }
229634b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
229734b6528fSMatthias Ringwald                 continue;
229834b6528fSMatthias Ringwald             }
229934b6528fSMatthias Ringwald         }
230034b6528fSMatthias Ringwald #endif
230134b6528fSMatthias Ringwald 
23023deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
230342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23043deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23053deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
230642134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2307549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
230806cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
230987014f74SMatthias Ringwald #endif
231087014f74SMatthias Ringwald #endif
231134c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23125567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
231334c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2314549ad5d2SMatthias Ringwald #endif
231587014f74SMatthias Ringwald 				// just lock context
231687014f74SMatthias Ringwald 				break;
23173deb3ec6SMatthias Ringwald             default:
23181979f09cSMatthias Ringwald                 done = false;
23193deb3ec6SMatthias Ringwald                 break;
23203deb3ec6SMatthias Ringwald         }
23213deb3ec6SMatthias Ringwald         if (done){
23227149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23237149bde5SMatthias 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);
23243deb3ec6SMatthias Ringwald         }
23253deb3ec6SMatthias Ringwald     }
2326d7f1c72eSMatthias Ringwald }
2327d7f1c72eSMatthias Ringwald 
2328403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2329403280b9SMatthias Ringwald     int i;
2330403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2331403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2332403280b9SMatthias Ringwald     uint8_t action = 0;
2333403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2334403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2335403280b9SMatthias Ringwald             bool clear_flag = true;
2336403280b9SMatthias Ringwald             switch (i){
2337403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2338403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2339403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2340403280b9SMatthias Ringwald                 default:
2341403280b9SMatthias Ringwald                     break;
2342403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2343403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2344403280b9SMatthias Ringwald                     num_actions--;
2345403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2346403280b9SMatthias Ringwald                     break;
2347403280b9SMatthias Ringwald             }
2348403280b9SMatthias Ringwald             if (clear_flag){
2349403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2350403280b9SMatthias Ringwald             }
2351403280b9SMatthias Ringwald             action = i;
2352403280b9SMatthias Ringwald             break;
2353403280b9SMatthias Ringwald         }
2354403280b9SMatthias Ringwald     }
2355403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2356403280b9SMatthias Ringwald 
2357403280b9SMatthias Ringwald     // send keypress notification
2358403280b9SMatthias Ringwald     uint8_t buffer[2];
2359403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2360403280b9SMatthias Ringwald     buffer[1] = action;
2361687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2362403280b9SMatthias Ringwald 
2363403280b9SMatthias Ringwald     // try
2364403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2365403280b9SMatthias Ringwald }
2366403280b9SMatthias Ringwald 
2367403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2368403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2369403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2370403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2371403280b9SMatthias Ringwald         uint8_t buffer[17];
2372403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2373403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2374687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2375403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2376403280b9SMatthias Ringwald         return;
2377403280b9SMatthias Ringwald     }
2378403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2379403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2380403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2381403280b9SMatthias Ringwald         uint8_t buffer[11];
2382403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2383403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2384403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2385687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2386403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2387403280b9SMatthias Ringwald         return;
2388403280b9SMatthias Ringwald     }
2389403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2390403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2391403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2392403280b9SMatthias Ringwald         uint8_t buffer[17];
2393403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2394403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
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_ADDRESS_INFORMATION){
2400403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2401403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2402403280b9SMatthias Ringwald         bd_addr_t local_address;
2403403280b9SMatthias Ringwald         uint8_t buffer[8];
2404403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2405403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2406403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2407403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2408403280b9SMatthias Ringwald                 // public or static random
2409403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2410403280b9SMatthias Ringwald                 break;
2411403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2412403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2413403280b9SMatthias Ringwald                 // fallback to public
2414403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2415403280b9SMatthias Ringwald                 buffer[1] = 0;
2416403280b9SMatthias Ringwald                 break;
2417403280b9SMatthias Ringwald             default:
2418403280b9SMatthias Ringwald                 btstack_assert(false);
2419403280b9SMatthias Ringwald                 break;
2420403280b9SMatthias Ringwald         }
2421403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2422687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2423403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2424403280b9SMatthias Ringwald         return;
2425403280b9SMatthias Ringwald     }
2426403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2427403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2428403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2429403280b9SMatthias Ringwald 
2430403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2431403280b9SMatthias Ringwald         // hack to reproduce test runs
2432403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2433403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2434403280b9SMatthias Ringwald                     }
2435403280b9SMatthias Ringwald 
2436403280b9SMatthias Ringwald                     // store local CSRK
2437403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2438403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2439403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2440403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2441403280b9SMatthias Ringwald                     }
2442403280b9SMatthias Ringwald #endif
2443403280b9SMatthias Ringwald 
2444403280b9SMatthias Ringwald         uint8_t buffer[17];
2445403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2446403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2447687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2448403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2449403280b9SMatthias Ringwald         return;
2450403280b9SMatthias Ringwald     }
2451403280b9SMatthias Ringwald     btstack_assert(false);
2452403280b9SMatthias Ringwald }
2453403280b9SMatthias Ringwald 
2454bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2455bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2456bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2457bbd73538SMatthias Ringwald     // - use secure connections
2458bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2459bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2460bbd73538SMatthias 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;
2461bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2462bbd73538SMatthias Ringwald     // - need identity address / public addr
2463bbd73538SMatthias 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);
2464bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2465bbd73538SMatthias 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)
2466bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2467bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2468bbd73538SMatthias 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.
2469bbd73538SMatthias Ringwald     uint8_t link_key[16];
2470bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2471bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2472bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2473bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2474bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2475bbd73538SMatthias Ringwald         return false;
2476bbd73538SMatthias Ringwald     }
2477bbd73538SMatthias Ringwald     // get started (all of the above are true)
2478bbd73538SMatthias Ringwald     return true;
2479bbd73538SMatthias Ringwald #else
2480bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2481bbd73538SMatthias Ringwald 	return false;
2482bbd73538SMatthias Ringwald #endif
2483bbd73538SMatthias Ringwald }
2484bbd73538SMatthias Ringwald 
24856f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24866f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24876f7422f1SMatthias 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;
24886f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24896f7422f1SMatthias Ringwald     } else {
24906f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24916f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24926f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24936f7422f1SMatthias Ringwald     }
24946f7422f1SMatthias Ringwald }
24956f7422f1SMatthias Ringwald 
2496af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2497af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2498af7ef9d1SMatthias 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;
2499af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2500af7ef9d1SMatthias Ringwald     } else {
2501af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2502af7ef9d1SMatthias Ringwald     }
2503af7ef9d1SMatthias Ringwald }
2504af7ef9d1SMatthias Ringwald 
2505d7f1c72eSMatthias Ringwald static void sm_run(void){
2506d7f1c72eSMatthias Ringwald 
2507d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2508d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2509d7f1c72eSMatthias Ringwald 
2510d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2511d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2512d7f1c72eSMatthias Ringwald 
2513d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2514d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2515d7f1c72eSMatthias Ringwald 
2516d7f1c72eSMatthias Ringwald     bool done;
2517d7f1c72eSMatthias Ringwald 
2518d7f1c72eSMatthias Ringwald     //
2519d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2520d7f1c72eSMatthias Ringwald     //
2521d7f1c72eSMatthias Ringwald 
2522d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2523d7f1c72eSMatthias Ringwald     if (done) return;
2524d7f1c72eSMatthias Ringwald 
2525d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2526d7f1c72eSMatthias Ringwald     if (done) return;
2527d7f1c72eSMatthias Ringwald 
2528d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2529d7f1c72eSMatthias Ringwald     if (done) return;
2530d7f1c72eSMatthias Ringwald 
2531d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2532d7f1c72eSMatthias Ringwald     if (done) return;
2533d7f1c72eSMatthias Ringwald 
2534d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2535d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2536d7f1c72eSMatthias Ringwald 
2537d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2538d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2539d7f1c72eSMatthias Ringwald     if (done) return;
2540d7f1c72eSMatthias Ringwald 
2541d7f1c72eSMatthias Ringwald     //
2542d7f1c72eSMatthias Ringwald     // active connection handling
2543d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2544d7f1c72eSMatthias Ringwald 
2545d7f1c72eSMatthias Ringwald     while (true) {
2546d7f1c72eSMatthias Ringwald 
2547d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2548d7f1c72eSMatthias Ringwald 
2549d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25503deb3ec6SMatthias Ringwald 
25513deb3ec6SMatthias Ringwald         //
25523deb3ec6SMatthias Ringwald         // active connection handling
25533deb3ec6SMatthias Ringwald         //
25543deb3ec6SMatthias Ringwald 
25553cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25563cf37b8cSMatthias Ringwald         if (!connection) {
25573cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25583cf37b8cSMatthias Ringwald             return;
25593cf37b8cSMatthias Ringwald         }
25603cf37b8cSMatthias Ringwald 
25613deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25627149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25637149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25647149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2565b170b20fSMatthias Ringwald             return;
2566b170b20fSMatthias Ringwald         }
25673deb3ec6SMatthias Ringwald 
25683d7fe1e9SMatthias Ringwald         // send keypress notifications
2569dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2570403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2571d7471931SMatthias Ringwald             return;
25723d7fe1e9SMatthias Ringwald         }
25733d7fe1e9SMatthias Ringwald 
25743deb3ec6SMatthias Ringwald         int key_distribution_flags;
257542134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2576b6afa23eSMatthias Ringwald 		int err;
2577b6afa23eSMatthias Ringwald 		UNUSED(err);
25789b75de03SMatthias Ringwald         bool have_ltk;
25799b75de03SMatthias Ringwald         uint8_t ltk[16];
25803deb3ec6SMatthias Ringwald 
25813deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2582dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2583dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2584dd4a08fbSMatthias Ringwald         }
25853deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25863deb3ec6SMatthias Ringwald 
2587f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2588aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2589aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2590aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2591aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2592aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2593aec94140SMatthias Ringwald                 break;
2594688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2595688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2596688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2597688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2598688a08f9SMatthias Ringwald                 break;
2599dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2600dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2601dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2602dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2603dc300847SMatthias Ringwald                 break;
2604019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2605b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2606019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26070346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26080346c37cSMatthias Ringwald                 break;
26090346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2610b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26110346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26120346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26130346c37cSMatthias Ringwald                 break;
26140346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2615b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26160346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26170346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26180346c37cSMatthias Ringwald                 break;
26190346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2620b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26210346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26220346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2623019005a0SMatthias Ringwald                 break;
2624bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2625b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2626bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2627b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2628bd57ffebSMatthias Ringwald                 break;
2629*e0a03c85SMatthias Ringwald #endif
2630*e0a03c85SMatthias Ringwald 
26316857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
263257132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
26332bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
263457132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
2635c82679c3SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
26362bacf595SMatthias Ringwald                 break;
263757132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
26382bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
263957132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
26402bacf595SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
26412bacf595SMatthias Ringwald                 break;
264257132f12SMatthias Ringwald 			case SM_SC_W2_CALCULATE_ILK_USING_H7:
264357132f12SMatthias Ringwald 				if (!sm_cmac_ready()) break;
264457132f12SMatthias Ringwald 				connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
2645c82679c3SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
264657132f12SMatthias Ringwald 				break;
2647*e0a03c85SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
2648*e0a03c85SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2649*e0a03c85SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
2650*e0a03c85SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
2651*e0a03c85SMatthias Ringwald                 break;
2652*e0a03c85SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
2653*e0a03c85SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2654*e0a03c85SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
2655*e0a03c85SMatthias Ringwald                 h6_calculate_le_ltk(connection);
2656*e0a03c85SMatthias Ringwald                 break;
2657*e0a03c85SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
2658*e0a03c85SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2659*e0a03c85SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
2660*e0a03c85SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
2661*e0a03c85SMatthias Ringwald                 break;
2662a756d52bSMatthias Ringwald #endif
266341d32297SMatthias Ringwald 
266442134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26653deb3ec6SMatthias Ringwald             // initiator side
2666f32b7a88SMatthias Ringwald 
26675567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2668f32b7a88SMatthias Ringwald 				sm_reset_setup();
2669f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2670daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2671f32b7a88SMatthias Ringwald 
26723deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26739c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26745567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26753deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2676c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2677c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26783deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26793deb3ec6SMatthias Ringwald                 return;
26803deb3ec6SMatthias Ringwald             }
26813deb3ec6SMatthias Ringwald 
2682b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2683b26f445fSMatthias Ringwald 				sm_reset_setup();
2684b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2685b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2686d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2687b26f445fSMatthias Ringwald 
26881ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26893deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2690687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26913deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26923deb3ec6SMatthias Ringwald                 break;
269342134bc6SMatthias Ringwald #endif
26943deb3ec6SMatthias Ringwald 
269527c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
269641d32297SMatthias Ringwald 
2697c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26981979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26991979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
270027c32905SMatthias Ringwald                 uint8_t buffer[65];
270127c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
270227c32905SMatthias Ringwald                 //
2703fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2704fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2705e53be891SMatthias Ringwald 
2706349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2707349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2708349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2709349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2710349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2711349d0adbSMatthias Ringwald                 }
2712349d0adbSMatthias Ringwald #endif
2713349d0adbSMatthias Ringwald 
271445a61d50SMatthias Ringwald                 // stk generation method
271545a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
271645a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
271745a61d50SMatthias Ringwald                     case JUST_WORKS:
271847fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
271942134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272007036a04SMatthias Ringwald                             // responder
27211979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2722b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
272327c32905SMatthias Ringwald                         } else {
272407036a04SMatthias Ringwald                             // initiator
2725c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272627c32905SMatthias Ringwald                         }
272745a61d50SMatthias Ringwald                         break;
272845a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
272945a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
273047fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
273107036a04SMatthias Ringwald                         // use random TK for display
27326535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27336535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
273445a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
273507036a04SMatthias Ringwald 
273642134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
273745a61d50SMatthias Ringwald                             // responder
2738c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
273945a61d50SMatthias Ringwald                         } else {
274045a61d50SMatthias Ringwald                             // initiator
2741c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
274245a61d50SMatthias Ringwald                         }
27431979f09cSMatthias Ringwald                         trigger_user_response = true;
274445a61d50SMatthias Ringwald                         break;
274545a61d50SMatthias Ringwald                     case OOB:
274665a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
274765a9a04eSMatthias Ringwald                             // responder
274865a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
274965a9a04eSMatthias Ringwald                         } else {
275065a9a04eSMatthias Ringwald                             // initiator
275165a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
275265a9a04eSMatthias Ringwald                         }
275345a61d50SMatthias Ringwald                         break;
27547bbeb3adSMilanka Ringwald                     default:
27557bbeb3adSMilanka Ringwald                         btstack_assert(false);
27567bbeb3adSMilanka Ringwald                         break;
275745a61d50SMatthias Ringwald                 }
275845a61d50SMatthias Ringwald 
2759687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
276027c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2761644c6a1dSMatthias Ringwald 
2762b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2763644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2764644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2765644c6a1dSMatthias Ringwald                 }
2766b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2767b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2768b90c4e75SMatthias Ringwald                 }
276927c32905SMatthias Ringwald                 break;
277027c32905SMatthias Ringwald             }
2771c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2772e53be891SMatthias Ringwald                 uint8_t buffer[17];
2773e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27749af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
277542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2776c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2777e53be891SMatthias Ringwald                 } else {
2778c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2779e53be891SMatthias Ringwald                 }
2780687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2781e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2782e53be891SMatthias Ringwald                 break;
2783e53be891SMatthias Ringwald             }
2784c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2785e53be891SMatthias Ringwald                 uint8_t buffer[17];
2786e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2787e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27889d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27894ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
279040c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
279142134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
279245a61d50SMatthias Ringwald                         // responder
2793c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
279445a61d50SMatthias Ringwald                     } else {
279545a61d50SMatthias Ringwald                         // initiator
2796c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
279745a61d50SMatthias Ringwald                     }
279845a61d50SMatthias Ringwald                 } else {
279940c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
280042134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2801e53be891SMatthias Ringwald                         // responder
280247fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
280340c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2804901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
28052886623dSMatthias Ringwald                         } else {
280640c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
28072886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2808446a8c36SMatthias Ringwald                         }
2809e53be891SMatthias Ringwald                     } else {
2810136d331aSMatthias Ringwald                         // initiator
2811c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2812e53be891SMatthias Ringwald                     }
281345a61d50SMatthias Ringwald                 }
2814687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2815e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2816e53be891SMatthias Ringwald                 break;
2817e53be891SMatthias Ringwald             }
2818c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2819e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2820e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2821e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2822dc300847SMatthias Ringwald 
282342134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2824c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2825e53be891SMatthias Ringwald                 } else {
2826c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2827e53be891SMatthias Ringwald                 }
2828e083ca23SMatthias Ringwald 
2829687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2830e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2831e53be891SMatthias Ringwald                 break;
2832e53be891SMatthias Ringwald             }
2833e53be891SMatthias Ringwald 
2834e53be891SMatthias Ringwald #endif
283542134bc6SMatthias Ringwald 
283642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2837dd12a62bSMatthias Ringwald 
283887014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
283987014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
284087014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2841687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2842c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
284387014f74SMatthias Ringwald 				break;
284487014f74SMatthias Ringwald 			}
284587014f74SMatthias Ringwald 
284638196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
284738196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
284838196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
284938196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
285038196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
285138196718SMatthias Ringwald 						// start using context by loading security info
285238196718SMatthias Ringwald 						sm_reset_setup();
285338196718SMatthias Ringwald 						sm_load_security_info(connection);
285438196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
285538196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
285638196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
285742646f38SMatthias Ringwald                             sm_reencryption_started(connection);
285838196718SMatthias Ringwald                             sm_trigger_run();
285938196718SMatthias Ringwald 							break;
286038196718SMatthias Ringwald 						}
286138196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
286238196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
286338196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
286438196718SMatthias Ringwald 						return;
286538196718SMatthias Ringwald 					default:
286638196718SMatthias Ringwald 						// just wait until IRK lookup is completed
286738196718SMatthias Ringwald 						break;
286838196718SMatthias Ringwald 				}
286938196718SMatthias Ringwald 				break;
287038196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
287138196718SMatthias Ringwald 
2872b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2873b6afa23eSMatthias Ringwald                 sm_reset_setup();
28749b75de03SMatthias Ringwald 
28759b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28769b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28779b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28789b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28799b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28809b75de03SMatthias Ringwald                         if (have_ltk){
28819b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
288219a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28839b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28849b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28859b75de03SMatthias Ringwald                         }
28869b75de03SMatthias Ringwald                         break;
28879b75de03SMatthias Ringwald                     default:
28889b75de03SMatthias Ringwald                         break;
28899b75de03SMatthias Ringwald                 }
28909b75de03SMatthias Ringwald 
2891b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2892d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
289339543d07SMatthias Ringwald 
2894b6afa23eSMatthias Ringwald 				// recover pairing request
2895b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2896b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2897b6afa23eSMatthias Ringwald 
2898b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2899b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2900b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2901b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2902b6afa23eSMatthias Ringwald                     }
2903b6afa23eSMatthias Ringwald #endif
29049305033eSMatthias Ringwald 				if (err != 0){
2905f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2906b6afa23eSMatthias Ringwald 					sm_trigger_run();
2907b6afa23eSMatthias Ringwald 					break;
2908b6afa23eSMatthias Ringwald 				}
2909b6afa23eSMatthias Ringwald 
2910b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2911b6afa23eSMatthias Ringwald 
2912b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2913b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2914b6afa23eSMatthias 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);
2915b6afa23eSMatthias Ringwald 					break;
2916b6afa23eSMatthias Ringwald 				}
2917b6afa23eSMatthias Ringwald 
2918b6afa23eSMatthias Ringwald 				/* fall through */
2919b6afa23eSMatthias Ringwald 
29203deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29211ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2922f55bd529SMatthias Ringwald 
2923f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29243deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29251ad129beSMatthias Ringwald 
2926f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2927f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2928f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2929f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2930f55bd529SMatthias Ringwald                 }
2931f55bd529SMatthias Ringwald #endif
2932f55bd529SMatthias Ringwald                 // setup in response
2933f55bd529SMatthias 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);
2934f55bd529SMatthias 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);
2935f55bd529SMatthias Ringwald 
2936f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29379a90d41aSMatthias 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));
2938f55bd529SMatthias Ringwald 
293927c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2940c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29410b8af2a5SMatthias Ringwald                 } else {
29420b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
294327c32905SMatthias Ringwald                 }
29440b8af2a5SMatthias Ringwald 
2945687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29463deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2947446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2948c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29493deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2950446a8c36SMatthias Ringwald                 }
29513deb3ec6SMatthias Ringwald                 return;
295242134bc6SMatthias Ringwald #endif
29533deb3ec6SMatthias Ringwald 
29543deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29553deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29563deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29579c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
295842134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29593deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29603deb3ec6SMatthias Ringwald                 } else {
29613deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29623deb3ec6SMatthias Ringwald                 }
2963687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29643deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29653deb3ec6SMatthias Ringwald                 break;
29663deb3ec6SMatthias Ringwald             }
29673deb3ec6SMatthias Ringwald 
2968d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29693deb3ec6SMatthias Ringwald                 // already busy?
29703deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2971d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2972d1a1f6a4SMatthias 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);
2973d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2974d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2975f3582630SMatthias 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);
29763deb3ec6SMatthias Ringwald                 break;
29773deb3ec6SMatthias Ringwald 
29783deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29793deb3ec6SMatthias Ringwald                 // already busy?
29803deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29813deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2982d1a1f6a4SMatthias 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);
2983d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2984d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2985f3582630SMatthias 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);
29863deb3ec6SMatthias Ringwald                 break;
2987d1a1f6a4SMatthias Ringwald 
29883deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29893deb3ec6SMatthias Ringwald                 // already busy?
29903deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29913deb3ec6SMatthias Ringwald                 // calculate STK
299242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2993d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29943deb3ec6SMatthias Ringwald                 } else {
2995d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29963deb3ec6SMatthias Ringwald                 }
2997d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2998d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2999f3582630SMatthias 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);
30003deb3ec6SMatthias Ringwald                 break;
3001d1a1f6a4SMatthias Ringwald 
30023deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
30033deb3ec6SMatthias Ringwald                 // already busy?
30043deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30053deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
30069ad0dd7cSMatthias Ringwald 
30079ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
30089ad0dd7cSMatthias Ringwald                 // r' = padding || r
30099ad0dd7cSMatthias Ringwald                 // r - 64 bit value
30109ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30116535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
30129ad0dd7cSMatthias Ringwald 
30133deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3014d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
3015d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3016f3582630SMatthias 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);
3017d1a1f6a4SMatthias Ringwald                 break;
3018d1a1f6a4SMatthias Ringwald 
30193deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30203deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30213deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30229c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
302342134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30243deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30253deb3ec6SMatthias Ringwald                 } else {
30263deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30273deb3ec6SMatthias Ringwald                 }
3028687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30293deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30303deb3ec6SMatthias Ringwald                 return;
30313deb3ec6SMatthias Ringwald             }
303242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30333deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30343deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30359c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30363deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30373deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30383deb3ec6SMatthias Ringwald                 return;
30393deb3ec6SMatthias Ringwald             }
3040d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
30413deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30429c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30435567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30443deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30453deb3ec6SMatthias Ringwald                 return;
30463deb3ec6SMatthias Ringwald             }
3047dd12a62bSMatthias Ringwald 
3048dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30493deb3ec6SMatthias Ringwald                 // already busy?
30503deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30513deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3052c61cfe5aSMatthias Ringwald 
3053dd12a62bSMatthias Ringwald 				sm_reset_setup();
3054dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3055dd12a62bSMatthias Ringwald 
305642646f38SMatthias Ringwald 				sm_reencryption_started(connection);
305742646f38SMatthias Ringwald 
3058c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3059c61cfe5aSMatthias Ringwald                 // r' = padding || r
3060c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3061c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30626535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3063c61cfe5aSMatthias Ringwald 
30643deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3065d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3066d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3067f3582630SMatthias 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);
30683deb3ec6SMatthias Ringwald                 return;
306942134bc6SMatthias Ringwald #endif
307042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
307142134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
307242134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
307342134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
307442134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
307542134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
307642134bc6SMatthias Ringwald                 return;
307742134bc6SMatthias Ringwald             }
307842134bc6SMatthias Ringwald #endif
30793deb3ec6SMatthias Ringwald 
30803deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3081403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3082403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30833deb3ec6SMatthias Ringwald                     return;
30843deb3ec6SMatthias Ringwald                 }
30853deb3ec6SMatthias Ringwald 
30863deb3ec6SMatthias Ringwald                 // keys are sent
308742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30883deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
30893deb3ec6SMatthias Ringwald                     if (sm_key_distribution_all_received(connection)){
30903deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3091f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3092f5020412SMatthias Ringwald                         // start CTKD right away
3093f5020412SMatthias Ringwald                         continue;
30943deb3ec6SMatthias Ringwald                     } else {
30953deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30963deb3ec6SMatthias Ringwald                     }
30973deb3ec6SMatthias Ringwald                 } else {
30981dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30993deb3ec6SMatthias Ringwald                 }
31003deb3ec6SMatthias Ringwald                 break;
31013deb3ec6SMatthias Ringwald 
31023deb3ec6SMatthias Ringwald             default:
31033deb3ec6SMatthias Ringwald                 break;
31043deb3ec6SMatthias Ringwald         }
31053deb3ec6SMatthias Ringwald 
31063deb3ec6SMatthias Ringwald         // check again if active connection was released
31077149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
31083deb3ec6SMatthias Ringwald     }
31093deb3ec6SMatthias Ringwald }
31103deb3ec6SMatthias Ringwald 
3111d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3112d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3113f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
311404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
311504678764SMatthias Ringwald 
3116f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3117f3582630SMatthias Ringwald     if (connection == NULL) return;
3118f3582630SMatthias Ringwald 
3119d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
312004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3121f3582630SMatthias 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);
3122d1a1f6a4SMatthias Ringwald }
31233deb3ec6SMatthias Ringwald 
3124d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3125f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
312604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
312704678764SMatthias Ringwald 
3128f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3129f3582630SMatthias Ringwald     if (connection == NULL) return;
3130f3582630SMatthias Ringwald 
31318314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
31323deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
313370b44dd4SMatthias Ringwald     sm_trigger_run();
3134d1a1f6a4SMatthias Ringwald }
3135d1a1f6a4SMatthias Ringwald 
3136d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3137d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3138f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
313904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
314004678764SMatthias Ringwald 
3141f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3142f3582630SMatthias Ringwald     if (connection == NULL) return;
3143f3582630SMatthias Ringwald 
3144d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
314504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3146f3582630SMatthias 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);
3147d1a1f6a4SMatthias Ringwald }
3148d1a1f6a4SMatthias Ringwald 
3149d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3150f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
315104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
315204678764SMatthias Ringwald 
3153f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3154f3582630SMatthias Ringwald     if (connection == NULL) return;
3155f3582630SMatthias Ringwald 
3156d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3157d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3158f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
315970b44dd4SMatthias Ringwald         sm_trigger_run();
31603deb3ec6SMatthias Ringwald         return;
31613deb3ec6SMatthias Ringwald     }
316242134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31633deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
316470b44dd4SMatthias Ringwald         sm_trigger_run();
31653deb3ec6SMatthias Ringwald     } else {
3166d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3167d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3168f3582630SMatthias 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);
31693deb3ec6SMatthias Ringwald     }
31703deb3ec6SMatthias Ringwald }
3171d1a1f6a4SMatthias Ringwald 
3172d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
317304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3174f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
317504678764SMatthias Ringwald 
3176f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3177f3582630SMatthias Ringwald     if (connection == NULL) return;
3178f3582630SMatthias Ringwald 
31793deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
31808314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
318142134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31823deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
31833deb3ec6SMatthias Ringwald     } else {
31843deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
31853deb3ec6SMatthias Ringwald     }
318670b44dd4SMatthias Ringwald     sm_trigger_run();
3187d1a1f6a4SMatthias Ringwald }
3188d1a1f6a4SMatthias Ringwald 
3189d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3190d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3191f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
319204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
319304678764SMatthias Ringwald 
3194f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3195f3582630SMatthias Ringwald     if (connection == NULL) return;
3196f3582630SMatthias Ringwald 
3197d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31983deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31993deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
32003deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
32013deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
32023deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
32033deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3204d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
320504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3206f3582630SMatthias 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);
32073deb3ec6SMatthias Ringwald }
3208d1a1f6a4SMatthias Ringwald 
32092a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3210d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3211d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
321204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3213f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
321404678764SMatthias Ringwald 
3215f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3216f3582630SMatthias Ringwald     if (connection == NULL) return;
3217f3582630SMatthias Ringwald 
3218d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
32193deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
32203deb3ec6SMatthias Ringwald 
32213deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
32223deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
32233deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
32243deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
32253deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3226d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
322704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3228f3582630SMatthias 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);
32293deb3ec6SMatthias Ringwald }
32302a526f21SMatthias Ringwald #endif
3231d1a1f6a4SMatthias Ringwald 
3232d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3233d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3234f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323604678764SMatthias Ringwald 
3237f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3238f3582630SMatthias Ringwald     if (connection == NULL) return;
3239f3582630SMatthias Ringwald 
32408314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
32413deb3ec6SMatthias Ringwald     // calc CSRK next
3242d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
324304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3244f3582630SMatthias 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);
3245d1a1f6a4SMatthias Ringwald }
3246d1a1f6a4SMatthias Ringwald 
3247d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3248f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325004678764SMatthias Ringwald 
3251f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3252f3582630SMatthias Ringwald     if (connection == NULL) return;
3253f3582630SMatthias Ringwald 
3254d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
32558314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
32563deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
32573deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
32583deb3ec6SMatthias Ringwald     } else {
32593deb3ec6SMatthias Ringwald         // no keys to send, just continue
326042134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3261c5a72e35SMatthias Ringwald             if (sm_key_distribution_all_received(connection)){
3262c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3263c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3264c5a72e35SMatthias Ringwald             } else {
32653deb3ec6SMatthias Ringwald                 // slave -> receive master keys
32663deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3267c5a72e35SMatthias Ringwald             }
32683deb3ec6SMatthias Ringwald         } else {
3269af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
32703deb3ec6SMatthias Ringwald         }
32712bacf595SMatthias Ringwald     }
327270b44dd4SMatthias Ringwald     sm_trigger_run();
3273d1a1f6a4SMatthias Ringwald }
3274d1a1f6a4SMatthias Ringwald 
327542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3276d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3277f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327904678764SMatthias Ringwald 
3280f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3281f3582630SMatthias Ringwald     if (connection == NULL) return;
3282f3582630SMatthias Ringwald 
32833deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32848314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3285d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
328670b44dd4SMatthias Ringwald     sm_trigger_run();
3287d1a1f6a4SMatthias Ringwald }
3288d1a1f6a4SMatthias Ringwald #endif
3289d1a1f6a4SMatthias Ringwald 
3290d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3291d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3292d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329304678764SMatthias Ringwald 
3294d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3295d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3296d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3297d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3298d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3299a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
330070b44dd4SMatthias Ringwald         sm_trigger_run();
33013deb3ec6SMatthias Ringwald         return;
33023deb3ec6SMatthias Ringwald     }
3303d1a1f6a4SMatthias Ringwald     // no match, try next
3304d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
330570b44dd4SMatthias Ringwald     sm_trigger_run();
33063deb3ec6SMatthias Ringwald }
33073deb3ec6SMatthias Ringwald 
3308d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3309d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3310d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
331104678764SMatthias Ringwald 
3312d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3313d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
331470b44dd4SMatthias Ringwald     sm_trigger_run();
33157df18c15SMatthias Ringwald }
3316d1a1f6a4SMatthias Ringwald 
3317d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3318d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3319d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
332004678764SMatthias Ringwald 
3321d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3322d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
332370b44dd4SMatthias Ringwald     sm_trigger_run();
33247df18c15SMatthias Ringwald }
3325d1a1f6a4SMatthias Ringwald 
3326d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3327d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3328d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
332904678764SMatthias Ringwald 
33306535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3331d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
333270b44dd4SMatthias Ringwald     sm_trigger_run();
333351fa0b28SMatthias Ringwald }
33347df18c15SMatthias Ringwald 
3335d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3336d1a1f6a4SMatthias Ringwald     UNUSED(arg);
33373deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
33383deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
33393deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
33403deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
33413deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
33424ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33434ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
33443deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
33453deb3ec6SMatthias Ringwald             break;
33463deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
33473deb3ec6SMatthias Ringwald         default:
33483deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
33494ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33503deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
33513deb3ec6SMatthias Ringwald             break;
33523deb3ec6SMatthias Ringwald     }
335370b44dd4SMatthias Ringwald     sm_trigger_run();
33543deb3ec6SMatthias Ringwald }
33553deb3ec6SMatthias Ringwald 
3356c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
33576ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3358f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3359f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3360f3582630SMatthias Ringwald     if (connection == NULL) return;
3361c59d0c92SMatthias Ringwald 
336265a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
336370b44dd4SMatthias Ringwald     sm_trigger_run();
336465a9a04eSMatthias Ringwald }
3365d1a1f6a4SMatthias Ringwald 
33666ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
33676ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
33686ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
33696ca80073SMatthias Ringwald     if (connection == NULL) return;
33706ca80073SMatthias Ringwald 
3371b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
337270b44dd4SMatthias Ringwald     sm_trigger_run();
3373d1a1f6a4SMatthias Ringwald }
3374f1c1783eSMatthias Ringwald #endif
3375f1c1783eSMatthias Ringwald 
3376d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3377f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3378f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3379f3582630SMatthias Ringwald     if (connection == NULL) return;
3380f3582630SMatthias Ringwald 
3381d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
338270b44dd4SMatthias Ringwald     sm_trigger_run();
3383d1a1f6a4SMatthias Ringwald }
3384d1a1f6a4SMatthias Ringwald 
3385d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3386f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3387f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3388f3582630SMatthias Ringwald     if (connection == NULL) return;
3389f3582630SMatthias Ringwald 
3390caf15bf3SMatthias Ringwald     sm_reset_tk();
3391caf15bf3SMatthias Ringwald     uint32_t tk;
33925ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
33933deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3394d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
33953deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
33964ea43905SMatthias Ringwald         if (tk >= 999999u){
33974ea43905SMatthias Ringwald             tk = tk - 999999u;
33983deb3ec6SMatthias Ringwald         }
3399caf15bf3SMatthias Ringwald     } else {
3400caf15bf3SMatthias Ringwald         // override with pre-defined passkey
34014b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3402caf15bf3SMatthias Ringwald     }
3403f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
340442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
34053deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
34063deb3ec6SMatthias Ringwald     } else {
3407b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3408b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3409b41539d5SMatthias Ringwald         } else {
34103deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
34113deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
34123deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
34133deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3414f3582630SMatthias 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);
34153deb3ec6SMatthias Ringwald             }
34163deb3ec6SMatthias Ringwald         }
3417b41539d5SMatthias Ringwald     }
341870b44dd4SMatthias Ringwald     sm_trigger_run();
34193deb3ec6SMatthias Ringwald }
3420d1a1f6a4SMatthias Ringwald 
3421d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3422f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3423f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3424f3582630SMatthias Ringwald     if (connection == NULL) return;
3425f3582630SMatthias Ringwald 
3426d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3427d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3428d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3429d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
343070b44dd4SMatthias Ringwald     sm_trigger_run();
3431d1a1f6a4SMatthias Ringwald }
3432d1a1f6a4SMatthias Ringwald 
3433d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3434f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3435f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3436f3582630SMatthias Ringwald     if (connection == NULL) return;
3437f3582630SMatthias Ringwald 
3438d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
34393deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
34404ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
34413deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
34424ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
34438b3ffec5SMatthias 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);
34443deb3ec6SMatthias Ringwald }
3445899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3446899e6e02SMatthias Ringwald     // warn about default ER/IR
34471979f09cSMatthias Ringwald     bool warning = false;
3448899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
34491979f09cSMatthias Ringwald         warning = true;
3450899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3451899e6e02SMatthias Ringwald     }
3452899e6e02SMatthias Ringwald     if (sm_er_is_default()){
34531979f09cSMatthias Ringwald         warning = true;
3454899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3455899e6e02SMatthias Ringwald     }
345621045273SMatthias Ringwald     if (warning) {
3457899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3458899e6e02SMatthias Ringwald     }
345921045273SMatthias Ringwald }
3460899e6e02SMatthias Ringwald 
3461899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
34621979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34639305033eSMatthias Ringwald     if (arg != NULL){
3464899e6e02SMatthias Ringwald         // key generated, store in tlv
34654ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3466899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3467e0d13a19SMilanka Ringwald         UNUSED(status);
3468899e6e02SMatthias Ringwald     }
3469899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
34708d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3471841468bbSMatthias Ringwald 
3472841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3473841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3474841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3475841468bbSMatthias Ringwald     }
3476841468bbSMatthias Ringwald 
347770b44dd4SMatthias Ringwald     sm_trigger_run();
3478899e6e02SMatthias Ringwald }
3479899e6e02SMatthias Ringwald 
3480899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
34811979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34829305033eSMatthias Ringwald     if (arg != 0){
3483899e6e02SMatthias Ringwald         // key generated, store in tlv
34844ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3485899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3486e0d13a19SMilanka Ringwald         UNUSED(status);
3487899e6e02SMatthias Ringwald     }
3488899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3489899e6e02SMatthias Ringwald 
3490899e6e02SMatthias Ringwald     // try load ir
34914ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3492899e6e02SMatthias Ringwald     if (key_size == 16){
3493899e6e02SMatthias Ringwald         // ok, let's continue
3494899e6e02SMatthias Ringwald         log_info("IR from TLV");
3495899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3496899e6e02SMatthias Ringwald     } else {
3497899e6e02SMatthias Ringwald         // invalid, generate new random one
34981979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3499899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3500899e6e02SMatthias Ringwald     }
3501899e6e02SMatthias Ringwald }
35023deb3ec6SMatthias Ringwald 
3503f664b5e8SMatthias 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){
3504f664b5e8SMatthias Ringwald 
3505f664b5e8SMatthias Ringwald     // connection info
3506f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3507f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3508f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3509f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3510f664b5e8SMatthias Ringwald 
3511f664b5e8SMatthias Ringwald     // security properties
3512f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3513f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3514f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3515f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3516f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3517f664b5e8SMatthias Ringwald 
3518f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3519f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3520f664b5e8SMatthias Ringwald 
3521f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3522f664b5e8SMatthias Ringwald }
3523f664b5e8SMatthias Ringwald 
3524d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
35253deb3ec6SMatthias Ringwald 
3526cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3527cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
35289ec2630cSMatthias Ringwald 
35293deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3530711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3531fbe050beSMatthias Ringwald     uint8_t           status;
3532f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3533f664b5e8SMatthias Ringwald 
35343deb3ec6SMatthias Ringwald     switch (packet_type) {
35353deb3ec6SMatthias Ringwald 
35363deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
35370e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
35383deb3ec6SMatthias Ringwald 
35393deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
35403deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3541be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
35423deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3543899e6e02SMatthias Ringwald 
3544899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3545899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
35469305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
35474ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3548899e6e02SMatthias Ringwald                             if (key_size == 16){
3549899e6e02SMatthias Ringwald                                 // ok, let's continue
3550899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3551899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3552899e6e02SMatthias Ringwald                             } else {
3553899e6e02SMatthias Ringwald                                 // invalid, generate random one
35541979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3555899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3556899e6e02SMatthias Ringwald                             }
3557899e6e02SMatthias Ringwald                         } else {
3558899e6e02SMatthias Ringwald                             sm_validate_er_ir();
35598d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3560841468bbSMatthias Ringwald 
3561841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3562841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3563841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3564841468bbSMatthias Ringwald                             }
3565899e6e02SMatthias Ringwald                         }
35661bf086daSMatthias Ringwald 
35671bf086daSMatthias Ringwald                         // restart random address updates after power cycle
35681bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
35693deb3ec6SMatthias Ringwald 					}
35703deb3ec6SMatthias Ringwald 					break;
35712d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
35722d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
35732d095694SMatthias Ringwald 			        // ignore if connection failed
35742d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
35753deb3ec6SMatthias Ringwald 
35762d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
35772d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
35782d095694SMatthias Ringwald 			        if (!sm_conn) break;
35792d095694SMatthias Ringwald 
35802d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
35812d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
35822d095694SMatthias Ringwald                                        con_handle,
35832d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3584f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
35852d095694SMatthias Ringwald                                        addr);
35862d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
35872d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
35882d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
35892d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
35902d095694SMatthias Ringwald 			        break;
35912d095694SMatthias Ringwald #endif
35923deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
35933deb3ec6SMatthias Ringwald                     switch (packet[2]) {
35943deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3595f664b5e8SMatthias Ringwald                             // ignore if connection failed
3596f664b5e8SMatthias Ringwald                             if (packet[3]) return;
35973deb3ec6SMatthias Ringwald 
3598711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3599711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
36003deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
36013deb3ec6SMatthias Ringwald 
3602f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3603f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3604f664b5e8SMatthias Ringwald                                                con_handle,
3605f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3606f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3607f664b5e8SMatthias Ringwald                                                addr);
3608687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3609f664b5e8SMatthias Ringwald 
3610f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3611f664b5e8SMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet)){
3612ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3613ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3614f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3615ba9fc867SMatthias Ringwald                             } else {
3616ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3617ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
36183deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36193deb3ec6SMatthias Ringwald                             }
36203deb3ec6SMatthias Ringwald                             break;
36213deb3ec6SMatthias Ringwald 
36223deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3623711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3624711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
36253deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
36263deb3ec6SMatthias Ringwald 
36273deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
36283deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
36293deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
36303deb3ec6SMatthias Ringwald                                 break;
36313deb3ec6SMatthias Ringwald                             }
3632c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3633778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3634778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3635e53be891SMatthias Ringwald                                 break;
3636e53be891SMatthias Ringwald                             }
36373deb3ec6SMatthias Ringwald 
36383deb3ec6SMatthias Ringwald                             // store rand and ediv
36399c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3640f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3641549ad5d2SMatthias Ringwald 
3642549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3643549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
36444ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
36456c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
364606cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3647549ad5d2SMatthias Ringwald                                     break;
3648549ad5d2SMatthias Ringwald                                 }
36496c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
36506c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
36516c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
36526c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
36536c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
36546c39055aSMatthias Ringwald                                         break;
36556c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
36566c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
36576c39055aSMatthias Ringwald                                         break;
36586c39055aSMatthias Ringwald                                     default:
36596c39055aSMatthias Ringwald                                         // wait for irk look doen
36606c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
36616c39055aSMatthias Ringwald                                         break;
36626c39055aSMatthias Ringwald                                 }
36636c39055aSMatthias Ringwald                                 break;
36646c39055aSMatthias Ringwald                             }
3665549ad5d2SMatthias Ringwald 
3666549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
366706cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3668549ad5d2SMatthias Ringwald #else
3669549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3670549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3671549ad5d2SMatthias Ringwald #endif
36723deb3ec6SMatthias Ringwald                             break;
3673804d3e67SMatthias Ringwald 
36743deb3ec6SMatthias Ringwald                         default:
36753deb3ec6SMatthias Ringwald                             break;
36763deb3ec6SMatthias Ringwald                     }
36773deb3ec6SMatthias Ringwald                     break;
36783deb3ec6SMatthias Ringwald 
36793deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
36803b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3681711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36823deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36833deb3ec6SMatthias Ringwald 
36843b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
36853deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
36863deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
36873deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
368803a9359aSMatthias Ringwald 
3689fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3690fbe050beSMatthias Ringwald 
36915567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
369203a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3693fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3694fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
36958d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
36968d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36978d4eef95SMatthias Ringwald                                 } else {
369803a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36998d4eef95SMatthias Ringwald                                 }
3700fbe050beSMatthias Ringwald                             } else {
3701e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3702cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
37033b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3704cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
37053b7fd749SMatthias Ringwald                             }
3706fbe050beSMatthias Ringwald 
3707fbe050beSMatthias Ringwald                             // emit re-encryption complete
370873102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3709fbe050beSMatthias Ringwald 
3710c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3711c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3712c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
37130ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
371403a9359aSMatthias Ringwald                             }
371503a9359aSMatthias Ringwald 
37163deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
37173deb3ec6SMatthias Ringwald                             break;
3718fbe050beSMatthias Ringwald 
37193deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3720fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3721dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
372242134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
37233deb3ec6SMatthias Ringwald                                 // slave
3724bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3725bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3726bbf8db22SMatthias Ringwald                                 } else {
3727f3582630SMatthias 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);
3728bbf8db22SMatthias Ringwald                                 }
37293deb3ec6SMatthias Ringwald                             } else {
37303deb3ec6SMatthias Ringwald                                 // master
37313deb3ec6SMatthias Ringwald                                 if (sm_key_distribution_all_received(sm_conn)){
37323deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
37333deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3734f3582630SMatthias 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);
37353deb3ec6SMatthias Ringwald                                 } else {
37363deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
37373deb3ec6SMatthias Ringwald                                 }
37383deb3ec6SMatthias Ringwald                             }
37393deb3ec6SMatthias Ringwald                             break;
37403deb3ec6SMatthias Ringwald                         default:
37413deb3ec6SMatthias Ringwald                             break;
37423deb3ec6SMatthias Ringwald                     }
37433deb3ec6SMatthias Ringwald                     break;
37443deb3ec6SMatthias Ringwald 
37453deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3746711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3747711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37483deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37493deb3ec6SMatthias Ringwald 
37503deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
37513deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
37523deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
37533deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37545567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
37555567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
37565567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
37575567aa60SMatthias Ringwald                             } else {
37583deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37595567aa60SMatthias Ringwald                             }
37603deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
37613deb3ec6SMatthias Ringwald                             break;
37623deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
376342134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
37643deb3ec6SMatthias Ringwald                                 // slave
3765f3582630SMatthias 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);
37663deb3ec6SMatthias Ringwald                             } else {
37673deb3ec6SMatthias Ringwald                                 // master
37683deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
37693deb3ec6SMatthias Ringwald                             }
37703deb3ec6SMatthias Ringwald                             break;
37713deb3ec6SMatthias Ringwald                         default:
37723deb3ec6SMatthias Ringwald                             break;
37733deb3ec6SMatthias Ringwald                     }
37743deb3ec6SMatthias Ringwald                     break;
37753deb3ec6SMatthias Ringwald 
37763deb3ec6SMatthias Ringwald 
37773deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3778711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3779711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3780711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37813deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37823deb3ec6SMatthias Ringwald 
378303f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
37847f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37857f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
37867f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
37877f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
37887f3f442dSMatthias Ringwald                             break;
37897f3f442dSMatthias Ringwald                         default:
379068a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37910ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
37927f3f442dSMatthias Ringwald                             break;
379303f736b1SMatthias Ringwald                     }
3794accbde80SMatthias Ringwald 
37953deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
37963deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
37973deb3ec6SMatthias Ringwald                     break;
37983deb3ec6SMatthias Ringwald 
37993deb3ec6SMatthias Ringwald 				case HCI_EVENT_COMMAND_COMPLETE:
380033373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
38019091c5f5SMatthias Ringwald                         // set local addr for le device db
380233373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
38030c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
380433373e40SMatthias Ringwald                     }
380565b44ffdSMatthias Ringwald                     break;
380665b44ffdSMatthias Ringwald                 default:
380765b44ffdSMatthias Ringwald                     break;
38083deb3ec6SMatthias Ringwald 			}
380965b44ffdSMatthias Ringwald             break;
381065b44ffdSMatthias Ringwald         default:
381165b44ffdSMatthias Ringwald             break;
38123deb3ec6SMatthias Ringwald 	}
38133deb3ec6SMatthias Ringwald 
38143deb3ec6SMatthias Ringwald     sm_run();
38153deb3ec6SMatthias Ringwald }
38163deb3ec6SMatthias Ringwald 
38173deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
38183deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
38193deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
38203deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
38213deb3ec6SMatthias Ringwald }
38223deb3ec6SMatthias Ringwald 
3823945888f5SMatthias Ringwald 
382431c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3825945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3826945888f5SMatthias Ringwald     switch (method){
3827945888f5SMatthias Ringwald         case JUST_WORKS:
382847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3829945888f5SMatthias Ringwald             return 1;
3830945888f5SMatthias Ringwald         default:
3831945888f5SMatthias Ringwald             return 0;
3832945888f5SMatthias Ringwald     }
3833945888f5SMatthias Ringwald }
383407036a04SMatthias Ringwald // responder
3835945888f5SMatthias Ringwald 
3836688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3837688a08f9SMatthias Ringwald     switch (method){
3838688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3839688a08f9SMatthias Ringwald             return 1;
3840688a08f9SMatthias Ringwald         default:
3841688a08f9SMatthias Ringwald             return 0;
3842688a08f9SMatthias Ringwald     }
3843688a08f9SMatthias Ringwald }
384440c5d850SMatthias Ringwald 
384540c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
384640c5d850SMatthias Ringwald     switch (method){
384740c5d850SMatthias Ringwald         case PK_RESP_INPUT:
384840c5d850SMatthias Ringwald         case PK_INIT_INPUT:
384947fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
385040c5d850SMatthias Ringwald             return 1;
385140c5d850SMatthias Ringwald         default:
385240c5d850SMatthias Ringwald             return 0;
385340c5d850SMatthias Ringwald     }
385440c5d850SMatthias Ringwald }
385540c5d850SMatthias Ringwald 
385631c09488SMatthias Ringwald #endif
3857688a08f9SMatthias Ringwald 
38583deb3ec6SMatthias Ringwald /**
38593deb3ec6SMatthias Ringwald  * @return ok
38603deb3ec6SMatthias Ringwald  */
38613deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
38623deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
38633deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
38643deb3ec6SMatthias Ringwald         case JUST_WORKS:
38654ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
38663deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
38673deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
386847fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
38694ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
38703deb3ec6SMatthias Ringwald         case OOB:
38714ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
387247fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
38734ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
38743deb3ec6SMatthias Ringwald         default:
38753deb3ec6SMatthias Ringwald             return 0;
38763deb3ec6SMatthias Ringwald     }
38773deb3ec6SMatthias Ringwald }
38783deb3ec6SMatthias Ringwald 
38798334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
38808334d3d8SMatthias Ringwald 
38814c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
38824c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
38834c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
38844c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
38854c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
38864c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
38874c1d1092SMatthias Ringwald             17, // 0x04 pairing random
38884c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
38894c1d1092SMatthias Ringwald             17, // 0x06 encryption information
38907a2e6387SMatthias Ringwald             11, // 0x07 master identification
38914c1d1092SMatthias Ringwald             17, // 0x08 identification information
38924c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
38934c1d1092SMatthias Ringwald             17, // 0x0a signing information
38944c1d1092SMatthias Ringwald             2,  // 0x0b security request
38954c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
38964c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
38974c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
38984c1d1092SMatthias Ringwald     };
38993deb3ec6SMatthias Ringwald 
3900c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3901b170b20fSMatthias Ringwald         sm_run();
3902b170b20fSMatthias Ringwald     }
3903b170b20fSMatthias Ringwald 
39043deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
39054ea43905SMatthias Ringwald     if (size == 0u) return;
39064c1d1092SMatthias Ringwald 
39074c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
39084c1d1092SMatthias Ringwald 
39094c1d1092SMatthias Ringwald     // validate pdu size
39104c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
39117a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
39123deb3ec6SMatthias Ringwald 
3913711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
39143deb3ec6SMatthias Ringwald     if (!sm_conn) return;
39153deb3ec6SMatthias Ringwald 
39164c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
391768a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
39180ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3919accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
39203deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
39213deb3ec6SMatthias Ringwald         return;
39223deb3ec6SMatthias Ringwald     }
39233deb3ec6SMatthias Ringwald 
39244c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
39253deb3ec6SMatthias Ringwald 
39263deb3ec6SMatthias Ringwald     int err;
392742134bc6SMatthias Ringwald     UNUSED(err);
39283deb3ec6SMatthias Ringwald 
39294c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
39303d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
39313d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
39323d7fe1e9SMatthias Ringwald         buffer[1] = 3;
39333d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
39343d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
39353d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
39363d7fe1e9SMatthias Ringwald         return;
39373d7fe1e9SMatthias Ringwald     }
39383d7fe1e9SMatthias Ringwald 
3939a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
3940212d735eSMatthias Ringwald     int have_ltk;
3941212d735eSMatthias Ringwald     uint8_t ltk[16];
3942a6ca6916SDavid Lechner #endif
3943212d735eSMatthias Ringwald 
39443deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
39453deb3ec6SMatthias Ringwald 
3946c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
39473deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
39483deb3ec6SMatthias Ringwald             return;
39493deb3ec6SMatthias Ringwald 
395042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
395142134bc6SMatthias Ringwald 
39523deb3ec6SMatthias Ringwald         // Initiator
39533deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
39544c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
39553deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39563deb3ec6SMatthias Ringwald                 break;
39573deb3ec6SMatthias Ringwald             }
395834c39fbdSMatthias Ringwald 
39592c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
39602c041b42SMatthias Ringwald             if (sm_sc_only_mode){
39612c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
39622c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
3963f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
39642c041b42SMatthias Ringwald                     break;
39652c041b42SMatthias Ringwald                 }
39662c041b42SMatthias Ringwald             }
39672c041b42SMatthias Ringwald #endif
39682c041b42SMatthias Ringwald 
396934c39fbdSMatthias Ringwald             // IRK complete?
397034c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
397134c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
3972dc8ca372SMatthias Ringwald                     // start pairing
39733deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
39743deb3ec6SMatthias Ringwald                     break;
3975e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
3976e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3977e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
39788549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
39798549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
39808549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
39815567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
3982e061bbd4SMatthias Ringwald                     } else {
3983dc8ca372SMatthias Ringwald                         // start pairing
3984e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3985e061bbd4SMatthias Ringwald                     }
3986e061bbd4SMatthias Ringwald                     break;
398734c39fbdSMatthias Ringwald                 default:
39883deb3ec6SMatthias Ringwald                     // otherwise, store security request
39893deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
39903deb3ec6SMatthias Ringwald                     break;
3991dc8ca372SMatthias Ringwald             }
3992dc8ca372SMatthias Ringwald             break;
39933deb3ec6SMatthias Ringwald 
39943deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3995aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
3996aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3997aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3998aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3999aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4000aacfafc3SMatthias Ringwald                 break;
4001aacfafc3SMatthias Ringwald             }
4002aacfafc3SMatthias Ringwald 
4003aacfafc3SMatthias Ringwald             // all other pdus are incorrect
40044c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
40053deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40063deb3ec6SMatthias Ringwald                 break;
40073deb3ec6SMatthias Ringwald             }
40080af429c6SMatthias Ringwald 
40093deb3ec6SMatthias Ringwald             // store pairing request
40106535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
40116535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
40123deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
40130af429c6SMatthias Ringwald 
40140af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
40150af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
40160af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
40170af429c6SMatthias Ringwald                 err = test_pairing_failure;
40180af429c6SMatthias Ringwald             }
40190af429c6SMatthias Ringwald #endif
40200af429c6SMatthias Ringwald 
40219305033eSMatthias Ringwald             if (err != 0){
4022f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
40233deb3ec6SMatthias Ringwald                 break;
40243deb3ec6SMatthias Ringwald             }
4025b41539d5SMatthias Ringwald 
4026b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4027b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4028f3582630SMatthias 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);
4029b41539d5SMatthias Ringwald                 break;
4030b41539d5SMatthias Ringwald             }
4031b41539d5SMatthias Ringwald 
4032136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4033136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
40348cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
40358cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4036136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4037136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4038136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4039c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4040136d331aSMatthias Ringwald                     }
40418cba5ca3SMatthias Ringwald                 } else {
4042c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
40438cba5ca3SMatthias Ringwald                 }
4044136d331aSMatthias Ringwald                 break;
4045136d331aSMatthias Ringwald             }
4046136d331aSMatthias Ringwald #endif
40473deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
40483deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
40493deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
40503deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4051f3582630SMatthias 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);
40523deb3ec6SMatthias Ringwald             }
40533deb3ec6SMatthias Ringwald             break;
40543deb3ec6SMatthias Ringwald 
40553deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
40564c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
40573deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40583deb3ec6SMatthias Ringwald                 break;
40593deb3ec6SMatthias Ringwald             }
40603deb3ec6SMatthias Ringwald 
40613deb3ec6SMatthias Ringwald             // store s_confirm
40629c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4063192365feSMatthias Ringwald 
4064aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4065aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4066aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4067aa9b34e5SMatthias Ringwald                 break;
4068aa9b34e5SMatthias Ringwald             }
4069aa9b34e5SMatthias Ringwald 
4070192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4071192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4072192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4073192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4074192365feSMatthias Ringwald             }
4075192365feSMatthias Ringwald #endif
40763deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
40773deb3ec6SMatthias Ringwald             break;
40783deb3ec6SMatthias Ringwald 
40793deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
40804c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
40813deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40823deb3ec6SMatthias Ringwald                 break;;
40833deb3ec6SMatthias Ringwald             }
40843deb3ec6SMatthias Ringwald 
40853deb3ec6SMatthias Ringwald             // received random value
40869c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
40873deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
40883deb3ec6SMatthias Ringwald             break;
408942134bc6SMatthias Ringwald #endif
40903deb3ec6SMatthias Ringwald 
409142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
40923deb3ec6SMatthias Ringwald         // Responder
40933deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
40943deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
40953deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
40964c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
40973deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40983deb3ec6SMatthias Ringwald                 break;;
40993deb3ec6SMatthias Ringwald             }
41003deb3ec6SMatthias Ringwald 
41013deb3ec6SMatthias Ringwald             // store pairing request
4102212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4103212d735eSMatthias Ringwald 
4104212d735eSMatthias Ringwald             // check if IRK completed
4105212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4106212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4107212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
41083deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
41093deb3ec6SMatthias Ringwald                     break;
4110212d735eSMatthias Ringwald                 default:
4111212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4112212d735eSMatthias Ringwald                     break;
4113212d735eSMatthias Ringwald             }
4114212d735eSMatthias Ringwald             break;
411542134bc6SMatthias Ringwald #endif
41163deb3ec6SMatthias Ringwald 
411727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4118c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
41194c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
412027c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
412127c32905SMatthias Ringwald                 break;
412227c32905SMatthias Ringwald             }
4123bccf5e67SMatthias Ringwald 
4124e53be891SMatthias Ringwald             // store public key for DH Key calculation
4125fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4126fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4127bccf5e67SMatthias Ringwald 
412802658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
412902658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
413002658749SMatthias Ringwald                 log_info("Remote PK matches ours");
413102658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
413202658749SMatthias Ringwald                 break;
413302658749SMatthias Ringwald             }
413402658749SMatthias Ringwald 
4135d1a1f6a4SMatthias Ringwald             // validate public key
4136d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
41379305033eSMatthias Ringwald             if (err != 0){
413802658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4139349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4140bccf5e67SMatthias Ringwald                 break;
4141bccf5e67SMatthias Ringwald             }
4142891bb64aSMatthias Ringwald 
4143d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4144f3582630SMatthias 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);
41453cf37b8cSMatthias Ringwald 
414665a9a04eSMatthias Ringwald 
414765a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
414842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4149136d331aSMatthias Ringwald                 // responder
4150c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4151136d331aSMatthias Ringwald             } else {
4152136d331aSMatthias Ringwald                 // initiator
4153a1e31e9cSMatthias Ringwald                 // stk generation method
4154a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4155a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4156a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
415747fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4158c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4159a1e31e9cSMatthias Ringwald                         break;
4160a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
416107036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
416207036a04SMatthias Ringwald                         break;
416307036a04SMatthias Ringwald                     case PK_INIT_INPUT:
416447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
416507036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
416607036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
416707036a04SMatthias Ringwald                             break;
416807036a04SMatthias Ringwald                         }
4169b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4170a1e31e9cSMatthias Ringwald                         break;
4171a1e31e9cSMatthias Ringwald                     case OOB:
4172d1a1f6a4SMatthias Ringwald                         // generate Nx
41734acf7b7bSMatthias Ringwald                         log_info("Generate Na");
41746ca80073SMatthias 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);
4175a1e31e9cSMatthias Ringwald                         break;
41767bbeb3adSMilanka Ringwald                     default:
41777bbeb3adSMilanka Ringwald                         btstack_assert(false);
41787bbeb3adSMilanka Ringwald                         break;
4179a1e31e9cSMatthias Ringwald                 }
4180136d331aSMatthias Ringwald             }
418127c32905SMatthias Ringwald             break;
4182e53be891SMatthias Ringwald 
4183c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
41844c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
418545a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
418645a61d50SMatthias Ringwald                 break;
418745a61d50SMatthias Ringwald             }
418845a61d50SMatthias Ringwald             // received confirm value
418945a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
419045a61d50SMatthias Ringwald 
4191192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4192192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4193192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4194192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4195192365feSMatthias Ringwald             }
4196192365feSMatthias Ringwald #endif
419742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
419845a61d50SMatthias Ringwald                 // responder
419907036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
420007036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
420107036a04SMatthias Ringwald                         // still waiting for passkey
420207036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
420307036a04SMatthias Ringwald                         break;
420407036a04SMatthias Ringwald                     }
420507036a04SMatthias Ringwald                 }
4206b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
420745a61d50SMatthias Ringwald             } else {
420845a61d50SMatthias Ringwald                 // initiator
4209945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
42106ca80073SMatthias 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);
4211f1c1783eSMatthias Ringwald                 } else {
4212c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
421345a61d50SMatthias Ringwald                 }
4214f1c1783eSMatthias Ringwald             }
421545a61d50SMatthias Ringwald             break;
421645a61d50SMatthias Ringwald 
4217c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
42184c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4219e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4220136d331aSMatthias Ringwald                 break;
4221e53be891SMatthias Ringwald             }
4222e53be891SMatthias Ringwald 
4223e53be891SMatthias Ringwald             // received random value
4224e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4225e53be891SMatthias Ringwald 
42265a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4227ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4228d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4229d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4230d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
423165a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4232d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4233688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4234ae451ec5SMatthias Ringwald                  break;
42355a293e6eSMatthias Ringwald             }
42366f52a196SMatthias Ringwald 
42374acf7b7bSMatthias Ringwald             // OOB
42384acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
42394acf7b7bSMatthias Ringwald 
42404acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
42414acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
42424acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
42434ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
42444acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
42454acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
42464acf7b7bSMatthias Ringwald                     } else {
42476535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
42484acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
42494acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
42504acf7b7bSMatthias Ringwald                     }
42514acf7b7bSMatthias Ringwald                 }  else {
42524ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
42534acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
42544acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
42554acf7b7bSMatthias Ringwald                     } else {
42566535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
42574acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
42584acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
42594acf7b7bSMatthias Ringwald                     }
42604acf7b7bSMatthias Ringwald                 }
42614acf7b7bSMatthias Ringwald 
4262a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
42634acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4264a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4265a680ba6bSMatthias Ringwald                      break;
4266a680ba6bSMatthias Ringwald                 }
42674acf7b7bSMatthias Ringwald             }
4268a680ba6bSMatthias Ringwald 
4269a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4270688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4271e53be891SMatthias Ringwald             break;
4272e53be891SMatthias Ringwald 
4273901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4274901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
42753cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4276901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4277901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4278901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4279901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4280901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4281901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4282901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4283c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4284901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4285d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
42864c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4287e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4288e53be891SMatthias Ringwald                 break;
4289e53be891SMatthias Ringwald             }
4290e53be891SMatthias Ringwald             // store DHKey Check
4291901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4292e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4293446a8c36SMatthias Ringwald 
4294901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4295901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4296019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4297bd57ffebSMatthias Ringwald             }
4298bd57ffebSMatthias Ringwald             break;
429927c32905SMatthias Ringwald #endif
430027c32905SMatthias Ringwald 
430142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43023deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
43034c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
43043deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
430527c32905SMatthias Ringwald                 break;
43063deb3ec6SMatthias Ringwald             }
43073deb3ec6SMatthias Ringwald 
43083deb3ec6SMatthias Ringwald             // received confirm value
43099c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
43103deb3ec6SMatthias Ringwald 
4311192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4312192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4313192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4314192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4315192365feSMatthias Ringwald             }
4316192365feSMatthias Ringwald #endif
43173deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
43183deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
43195611a760SMatthias 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);
43203deb3ec6SMatthias Ringwald             }
43213deb3ec6SMatthias Ringwald 
43223deb3ec6SMatthias Ringwald             // handle user cancel pairing?
43233deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4324f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
43253deb3ec6SMatthias Ringwald                 break;
43263deb3ec6SMatthias Ringwald             }
43273deb3ec6SMatthias Ringwald 
43283deb3ec6SMatthias Ringwald             // wait for user action?
43293deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
43303deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
43313deb3ec6SMatthias Ringwald                 break;
43323deb3ec6SMatthias Ringwald             }
43333deb3ec6SMatthias Ringwald 
43343deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4335f3582630SMatthias 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);
43363deb3ec6SMatthias Ringwald             break;
43373deb3ec6SMatthias Ringwald 
43383deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
43394c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
43403deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43413deb3ec6SMatthias Ringwald                 break;;
43423deb3ec6SMatthias Ringwald             }
43433deb3ec6SMatthias Ringwald 
43443deb3ec6SMatthias Ringwald             // received random value
43459c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
43463deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
43473deb3ec6SMatthias Ringwald             break;
434842134bc6SMatthias Ringwald #endif
43493deb3ec6SMatthias Ringwald 
43503deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
43514c1d1092SMatthias Ringwald             switch(sm_pdu_code){
43523deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
43533deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
43549c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
43553deb3ec6SMatthias Ringwald                     break;
43563deb3ec6SMatthias Ringwald 
43573deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
43583deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4359f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
43609c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
43613deb3ec6SMatthias Ringwald                     break;
43623deb3ec6SMatthias Ringwald 
43633deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
43643deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
43659c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
43663deb3ec6SMatthias Ringwald                     break;
43673deb3ec6SMatthias Ringwald 
43683deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
43693deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
43703deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4371724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
43723deb3ec6SMatthias Ringwald                     break;
43733deb3ec6SMatthias Ringwald 
43743deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
43753deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
43769c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
43773deb3ec6SMatthias Ringwald                     break;
43783deb3ec6SMatthias Ringwald                 default:
43793deb3ec6SMatthias Ringwald                     // Unexpected PDU
43803deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
43813deb3ec6SMatthias Ringwald                     break;
43823deb3ec6SMatthias Ringwald             }
43833deb3ec6SMatthias Ringwald             // done with key distribution?
43843deb3ec6SMatthias Ringwald             if (sm_key_distribution_all_received(sm_conn)){
43853deb3ec6SMatthias Ringwald 
43863deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
43873deb3ec6SMatthias Ringwald 
438842134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43896f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
43903deb3ec6SMatthias Ringwald                 } else {
4391625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4392625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4393bbf8db22SMatthias Ringwald                     } else {
4394f3582630SMatthias 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);
4395625f00b2SMatthias Ringwald                     }
43963deb3ec6SMatthias Ringwald                 }
43973deb3ec6SMatthias Ringwald             }
43983deb3ec6SMatthias Ringwald             break;
43993deb3ec6SMatthias Ringwald         default:
44003deb3ec6SMatthias Ringwald             // Unexpected PDU
44013deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
44022d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
44033deb3ec6SMatthias Ringwald             break;
44043deb3ec6SMatthias Ringwald     }
44053deb3ec6SMatthias Ringwald 
440670b44dd4SMatthias Ringwald     // try to send next pdu
440770b44dd4SMatthias Ringwald     sm_trigger_run();
44083deb3ec6SMatthias Ringwald }
44093deb3ec6SMatthias Ringwald 
44103deb3ec6SMatthias Ringwald // Security Manager Client API
4411a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
44123deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
44133deb3ec6SMatthias Ringwald }
44143deb3ec6SMatthias Ringwald 
44154acf7b7bSMatthias 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)){
4416a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4417a680ba6bSMatthias Ringwald }
4418a680ba6bSMatthias Ringwald 
441989a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
442089a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
442189a78d34SMatthias Ringwald }
442289a78d34SMatthias Ringwald 
44233deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
44243deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
44253deb3ec6SMatthias Ringwald }
44263deb3ec6SMatthias Ringwald 
44273deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
44283deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
44293deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
44303deb3ec6SMatthias Ringwald }
44313deb3ec6SMatthias Ringwald 
44323deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
443398d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
443498d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
443598d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
443698d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
443798d95509SMatthias Ringwald     }
443898d95509SMatthias Ringwald #endif
44393deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
44403deb3ec6SMatthias Ringwald }
44413deb3ec6SMatthias Ringwald 
44423deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
44433deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
44443deb3ec6SMatthias Ringwald }
44453deb3ec6SMatthias Ringwald 
444642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44473deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
44483deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
44493deb3ec6SMatthias Ringwald }
445042134bc6SMatthias Ringwald #endif
44513deb3ec6SMatthias Ringwald 
44523deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
44536535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
44543deb3ec6SMatthias Ringwald }
44553deb3ec6SMatthias Ringwald 
44563deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
44576535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
44583deb3ec6SMatthias Ringwald }
44593deb3ec6SMatthias Ringwald 
44603deb3ec6SMatthias Ringwald // Testing support only
44613deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
44626535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4463103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4464841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
44653deb3ec6SMatthias Ringwald }
44663deb3ec6SMatthias Ringwald 
44673deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4468841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
44693deb3ec6SMatthias Ringwald }
44703deb3ec6SMatthias Ringwald 
4471d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4472d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4473d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4474d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
447534b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
447670b44dd4SMatthias Ringwald     sm_trigger_run();
4477d1a1f6a4SMatthias Ringwald }
4478674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
447934b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4480674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4481674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4482674e5b4aSMatthias Ringwald }
4483d1a1f6a4SMatthias Ringwald #endif
4484d1a1f6a4SMatthias Ringwald 
4485192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4486192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4487192365feSMatthias Ringwald     test_pairing_failure = reason;
4488192365feSMatthias Ringwald }
4489192365feSMatthias Ringwald #endif
4490192365feSMatthias Ringwald 
44913deb3ec6SMatthias Ringwald void sm_init(void){
44922d2d4d3cSMatthias Ringwald 
44932d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
44942d2d4d3cSMatthias Ringwald 
4495899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4496899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4497899e6e02SMatthias Ringwald 
44983deb3ec6SMatthias Ringwald     // defaults
44993deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
45003deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4501b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4502b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4503b4343428SMatthias Ringwald 
45043deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
45053deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
45063deb3ec6SMatthias Ringwald 
45075ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
45081979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4509caf15bf3SMatthias Ringwald 
4510d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4511d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
45127a766ebfSMatthias Ringwald #endif
45138d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4514fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
45153deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
45163deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
45173deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
45183deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
45193deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
45203deb3ec6SMatthias Ringwald 
45213deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
45227149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
45233deb3ec6SMatthias Ringwald 
4524841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
45253deb3ec6SMatthias Ringwald 
452684c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
452784c0c5c7SMatthias Ringwald 
4528e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4529e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4530e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4531e03e489aSMatthias Ringwald 
4532d1a1f6a4SMatthias Ringwald     //
4533d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4534d1a1f6a4SMatthias Ringwald 
453551bd74d1SMatthias Ringwald     // init le_device_db
453651bd74d1SMatthias Ringwald     le_device_db_init();
453751bd74d1SMatthias Ringwald 
4538b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4539e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
454027c32905SMatthias Ringwald 
454109e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4542674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4543a3aba2f9SMatthias Ringwald #endif
45442d2d4d3cSMatthias Ringwald 
45452d2d4d3cSMatthias Ringwald     sm_initialized = true;
45463deb3ec6SMatthias Ringwald }
45473deb3ec6SMatthias Ringwald 
454815537ea4SMatthias Ringwald void sm_deinit(void){
454915537ea4SMatthias Ringwald     sm_initialized = false;
455015537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
455115537ea4SMatthias Ringwald }
455215537ea4SMatthias Ringwald 
45534b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
45544b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4555caf15bf3SMatthias Ringwald }
4556caf15bf3SMatthias Ringwald 
45576c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
45581979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
45596c39055aSMatthias Ringwald }
45606c39055aSMatthias Ringwald 
4561711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4562711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
45633deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
45643deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
45653deb3ec6SMatthias Ringwald }
45663deb3ec6SMatthias Ringwald 
456777e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
456877e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
456977e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
457077e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
457177e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
457277e2e5edSMatthias Ringwald }
457377e2e5edSMatthias Ringwald #endif
457477e2e5edSMatthias Ringwald 
45756bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4576711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4577711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45783deb3ec6SMatthias Ringwald     if (!sm_conn) return;
45796bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
45806bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
45813deb3ec6SMatthias Ringwald }
45823deb3ec6SMatthias Ringwald 
45833deb3ec6SMatthias Ringwald // request pairing
4584711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4585711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45863deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45873deb3ec6SMatthias Ringwald 
45887af5dcd5SMatthias Ringwald     bool have_ltk;
45897af5dcd5SMatthias Ringwald     uint8_t ltk[16];
45903deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
459142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
459224c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
459324c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
459424c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
45957af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45967af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45977af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
45987af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
45997af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
46007af5dcd5SMatthias Ringwald                         if (have_ltk){
46017af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
460224c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
46037af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
46047af5dcd5SMatthias Ringwald                             break;
46057af5dcd5SMatthias Ringwald                         }
46067af5dcd5SMatthias Ringwald                         /* fall through */
46077af5dcd5SMatthias Ringwald 
46087af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
46097af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
46107af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
46117af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
46127af5dcd5SMatthias Ringwald                         break;
46137af5dcd5SMatthias Ringwald                     default:
46147af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
46157af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
46167af5dcd5SMatthias Ringwald                         break;
46177af5dcd5SMatthias Ringwald                 }
461824c20dc4SMatthias Ringwald                 break;
461924c20dc4SMatthias Ringwald             default:
462024c20dc4SMatthias Ringwald                 break;
462124c20dc4SMatthias Ringwald         }
46223deb3ec6SMatthias Ringwald     } else {
46233deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4624175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4625175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
46263deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
46273deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
46283dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4629f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4630f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4631f53ec649SMatthias Ringwald                         if (have_ltk){
4632c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
46335567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4634c245ca32SMatthias Ringwald                             break;
4635f53ec649SMatthias Ringwald                         }
4636cf373d3aSMatthias Ringwald                         /* fall through */
4637c245ca32SMatthias Ringwald 
463834c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
46393deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
46403deb3ec6SMatthias Ringwald                         break;
46413deb3ec6SMatthias Ringwald                     default:
4642d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
464309ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
46443deb3ec6SMatthias Ringwald                         break;
46453deb3ec6SMatthias Ringwald                 }
4646175b7faaSMatthias Ringwald                 break;
4647cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4648cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4649cb6d7eb0SMatthias Ringwald                 break;
4650175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
465109ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4652175b7faaSMatthias Ringwald                 break;
4653175b7faaSMatthias Ringwald             default:
4654175b7faaSMatthias Ringwald                 break;
46553deb3ec6SMatthias Ringwald         }
46563deb3ec6SMatthias Ringwald     }
465770b44dd4SMatthias Ringwald     sm_trigger_run();
46583deb3ec6SMatthias Ringwald }
46593deb3ec6SMatthias Ringwald 
46603deb3ec6SMatthias Ringwald // called by client app on authorization request
4661711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4662711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46633deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46643deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4665589f5a99SMatthias 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);
46663deb3ec6SMatthias Ringwald }
46673deb3ec6SMatthias Ringwald 
4668711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4669711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46703deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46713deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4672589f5a99SMatthias 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);
46733deb3ec6SMatthias Ringwald }
46743deb3ec6SMatthias Ringwald 
46753deb3ec6SMatthias Ringwald // GAP Bonding API
46763deb3ec6SMatthias Ringwald 
4677711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4678711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46793deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46803deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
46810af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
46820af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
46830af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46840af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
46850af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
46860af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
46870af429c6SMatthias Ringwald #endif
46880af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4689de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4690de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4691de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
469247fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
46930af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4694de2fd182SMatthias Ringwald                     break;
469547fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4696de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4697de2fd182SMatthias Ringwald                     break;
4698de2fd182SMatthias Ringwald                 case JUST_WORKS:
4699de2fd182SMatthias Ringwald                 case OOB:
4700de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4701de2fd182SMatthias Ringwald                     break;
47027bbeb3adSMilanka Ringwald                 default:
47037bbeb3adSMilanka Ringwald                     btstack_assert(false);
47047bbeb3adSMilanka Ringwald                     break;
4705de2fd182SMatthias Ringwald             }
47060af429c6SMatthias Ringwald             break;
47070af429c6SMatthias Ringwald         default:
47080af429c6SMatthias Ringwald             break;
47093deb3ec6SMatthias Ringwald     }
471070b44dd4SMatthias Ringwald     sm_trigger_run();
47113deb3ec6SMatthias Ringwald }
47123deb3ec6SMatthias Ringwald 
4713711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4714711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47153deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
47163deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
47173deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4718136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4719c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4720bbf8db22SMatthias Ringwald         } else {
4721f3582630SMatthias 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);
4722136d331aSMatthias Ringwald         }
47233deb3ec6SMatthias Ringwald     }
47240346c37cSMatthias Ringwald 
47250346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4726c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4727dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4728446a8c36SMatthias Ringwald     }
47290346c37cSMatthias Ringwald #endif
47300346c37cSMatthias Ringwald 
473170b44dd4SMatthias Ringwald     sm_trigger_run();
47323deb3ec6SMatthias Ringwald }
47333deb3ec6SMatthias Ringwald 
4734c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4735c8c46d51SMatthias Ringwald     // for now, it's the same
4736c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4737c8c46d51SMatthias Ringwald }
4738c8c46d51SMatthias Ringwald 
4739711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4740711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47413deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
47423deb3ec6SMatthias Ringwald     sm_reset_tk();
4743f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
47443deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
47453deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4746f3582630SMatthias 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);
47473deb3ec6SMatthias Ringwald     }
47481c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
47496535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
47506535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
475107036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
475207036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
475307036a04SMatthias Ringwald     }
47541c516d8fSMatthias Ringwald #endif
475570b44dd4SMatthias Ringwald     sm_trigger_run();
47563deb3ec6SMatthias Ringwald }
47573deb3ec6SMatthias Ringwald 
47583d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
47593d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47603d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
47613d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4762dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
47634ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4764dd4a08fbSMatthias Ringwald     switch (action){
4765dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4766dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
47674ea43905SMatthias Ringwald             flags |= (1u << action);
4768dd4a08fbSMatthias Ringwald             break;
4769dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4770dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
47714ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4772dd4a08fbSMatthias Ringwald             break;
4773dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
47744ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4775dd4a08fbSMatthias Ringwald                 // erase actions queued
4776dd4a08fbSMatthias Ringwald                 num_actions--;
47774ea43905SMatthias Ringwald                 if (num_actions == 0u){
4778dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47794ea43905SMatthias Ringwald                     flags &= 0x19u;
4780dd4a08fbSMatthias Ringwald                 }
4781dd4a08fbSMatthias Ringwald                 break;
4782dd4a08fbSMatthias Ringwald             }
4783dd4a08fbSMatthias Ringwald             num_actions++;
47844ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4785dd4a08fbSMatthias Ringwald             break;
4786dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
47874ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4788dd4a08fbSMatthias Ringwald                 // enter actions queued
4789dd4a08fbSMatthias Ringwald                 num_actions--;
47904ea43905SMatthias Ringwald                 if (num_actions == 0u){
4791dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47924ea43905SMatthias Ringwald                     flags &= 0x19u;
4793dd4a08fbSMatthias Ringwald                 }
4794dd4a08fbSMatthias Ringwald                 break;
4795dd4a08fbSMatthias Ringwald             }
4796dd4a08fbSMatthias Ringwald             num_actions++;
47974ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4798dd4a08fbSMatthias Ringwald             break;
4799dd4a08fbSMatthias Ringwald         default:
4800dd4a08fbSMatthias Ringwald             break;
4801dd4a08fbSMatthias Ringwald     }
4802dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
480370b44dd4SMatthias Ringwald     sm_trigger_run();
48043d7fe1e9SMatthias Ringwald }
48053d7fe1e9SMatthias Ringwald 
4806c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4807d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
4808d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4809d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
481070b44dd4SMatthias Ringwald     sm_trigger_run();
4811d1a1f6a4SMatthias Ringwald }
4812c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
48138334d3d8SMatthias Ringwald 
48148334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
48158334d3d8SMatthias Ringwald 
4816c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4817c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
4818d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4819d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4820c59d0c92SMatthias Ringwald     return 0;
4821c59d0c92SMatthias Ringwald }
4822c59d0c92SMatthias Ringwald #endif
4823c59d0c92SMatthias Ringwald 
48243deb3ec6SMatthias Ringwald /**
4825ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
4826ba394633SMatthias Ringwald  * @param con_handle
4827ba394633SMatthias Ringwald  * @return irk_lookup_state_t
4828ba394633SMatthias Ringwald  */
4829ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4830ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4831ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
4832ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
4833ba394633SMatthias Ringwald }
4834ba394633SMatthias Ringwald 
4835ba394633SMatthias Ringwald /**
48363deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
48373deb3ec6SMatthias Ringwald  * @param handle
48383deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
48393deb3ec6SMatthias Ringwald  */
4840711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
4841711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48423deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
48433deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
48443deb3ec6SMatthias Ringwald }
48453deb3ec6SMatthias Ringwald 
48468f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
484747ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
484847ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
484947ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
485047ba4de1SMatthias Ringwald             return 0;
485147ba4de1SMatthias Ringwald         default:
48528f57b085SMatthias Ringwald             return 1;
48538f57b085SMatthias Ringwald     }
485447ba4de1SMatthias Ringwald }
4855d70217a2SMatthias Ringwald 
485633373e40SMatthias Ringwald static uint8_t own_address_type(void){
4857b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
4858b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4859b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
4860b95a5a35SMatthias Ringwald         default:
4861b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
4862b95a5a35SMatthias Ringwald     }
486333373e40SMatthias Ringwald }
48648f57b085SMatthias Ringwald 
48653deb3ec6SMatthias Ringwald // GAP LE API
48663deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
48673deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48683deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
4869b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
48708f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48713deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48723deb3ec6SMatthias Ringwald     gap_random_address_trigger();
48733deb3ec6SMatthias Ringwald }
48743deb3ec6SMatthias Ringwald 
48753deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
48763deb3ec6SMatthias Ringwald     return gap_random_adress_type;
48773deb3ec6SMatthias Ringwald }
48783deb3ec6SMatthias Ringwald 
48793deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
48803deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
48818f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48823deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48833deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48843deb3ec6SMatthias Ringwald }
48853deb3ec6SMatthias Ringwald 
4886667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
48878f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
48886535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
48897e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
489070b44dd4SMatthias Ringwald     sm_trigger_run();
48917e252622SMatthias Ringwald }
48927e252622SMatthias Ringwald 
4893d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48943deb3ec6SMatthias Ringwald /*
48953deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
48963deb3ec6SMatthias Ringwald  * @param adv_int_min
48973deb3ec6SMatthias Ringwald  * @param adv_int_max
48983deb3ec6SMatthias Ringwald  * @param adv_type
48993deb3ec6SMatthias Ringwald  * @param direct_address_type
49003deb3ec6SMatthias Ringwald  * @param direct_address
49013deb3ec6SMatthias Ringwald  * @param channel_map
49023deb3ec6SMatthias Ringwald  * @param filter_policy
49033deb3ec6SMatthias Ringwald  *
49043deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
49053deb3ec6SMatthias Ringwald  */
49063deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
49073deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4908b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
49093deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
49103deb3ec6SMatthias Ringwald }
4911d70217a2SMatthias Ringwald #endif
4912dcd6c9b5SMatthias Ringwald 
4913dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4914dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4915dcd6c9b5SMatthias Ringwald      // wrong connection
4916dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
4917dcd6c9b5SMatthias Ringwald     // already encrypted
4918dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
4919dcd6c9b5SMatthias Ringwald     // irk status?
4920dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
4921dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
4922dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
4923dcd6c9b5SMatthias Ringwald             return 0;
4924dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
4925dcd6c9b5SMatthias Ringwald             break;
4926dcd6c9b5SMatthias Ringwald         default:
4927dcd6c9b5SMatthias Ringwald             // IR Lookup pending
4928dcd6c9b5SMatthias Ringwald             return 1;
4929dcd6c9b5SMatthias Ringwald     }
4930f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
4931f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
4932b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
4933b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
4934b15d5ceaSMatthias Ringwald     } else {
4935dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4936dcd6c9b5SMatthias Ringwald     }
4937b15d5ceaSMatthias Ringwald }
49383cdbe9dbSMatthias Ringwald 
49393cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
49403cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49413cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
49423cdbe9dbSMatthias Ringwald #else
49433cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
49443cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
49453cdbe9dbSMatthias Ringwald #endif
49463cdbe9dbSMatthias Ringwald }
4947052bbdc5SMatthias Ringwald 
4948052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
4949052bbdc5SMatthias Ringwald     return sm_persistent_irk;
4950052bbdc5SMatthias Ringwald }
49514f384501SMatthias Ringwald 
49524f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
49534f384501SMatthias Ringwald     uint16_t i;
49544f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
49554f384501SMatthias Ringwald         bd_addr_t entry_address;
49564f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
49574f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
49584f384501SMatthias Ringwald         // skip unused entries
49594f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
49604f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
49614f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
49624f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
49634f384501SMatthias Ringwald #endif
49644f384501SMatthias Ringwald             le_device_db_remove(i);
49654f384501SMatthias Ringwald             break;
49664f384501SMatthias Ringwald         }
49674f384501SMatthias Ringwald     }
49684f384501SMatthias Ringwald }
4969