xref: /btstack/src/ble/sm.c (revision 9a90d41a90419fc57d4b4322581e045ea15946a2)
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;
311*9a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3133deb3ec6SMatthias Ringwald 
3143deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3153deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3163deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
317a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
31827c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3193deb3ec6SMatthias Ringwald 
3203deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3213deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3223deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3233deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3273deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3283deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3293deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3303deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3313deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3323deb3ec6SMatthias Ringwald 
33368437d83SMatthias Ringwald     uint8_t   sm_state_vars;
334e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
335fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
336446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
337446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
338d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
339e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
340e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
341446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
342446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3432bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
344a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3457df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
346e53be891SMatthias Ringwald #endif
34727c32905SMatthias Ringwald 
3483deb3ec6SMatthias Ringwald     // Phase 3
3493deb3ec6SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // key distribution, we generate
3513deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3523deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3543deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3553deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3563deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3583deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3593deb3ec6SMatthias Ringwald 
3603deb3ec6SMatthias Ringwald     // key distribution, received from peer
3613deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3623deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3643deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3653deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3663deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3683deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3693deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
370715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
371715a43d1SMatthias Ringwald     int       sm_le_device_index;
372715a43d1SMatthias Ringwald #endif
3733deb3ec6SMatthias Ringwald } sm_setup_context_t;
3743deb3ec6SMatthias Ringwald 
3753deb3ec6SMatthias Ringwald //
3763deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3773deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3783deb3ec6SMatthias Ringwald 
3793deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3807149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3813deb3ec6SMatthias Ringwald 
3823deb3ec6SMatthias Ringwald // @returns 1 if oob data is available
3833deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3843deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3854acf7b7bSMatthias Ringwald static int (*sm_get_sc_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_sc_peer_confirm, uint8_t * oob_sc_peer_random);
3863deb3ec6SMatthias Ringwald 
3873deb3ec6SMatthias Ringwald static void sm_run(void);
388711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
389711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
3903deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3913deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
392d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
393d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
394d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
395d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
396d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
397d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
398d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4022a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4052a526f21SMatthias Ringwald #endif
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
410d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4116d80b495SMatthias Ringwald static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash));
41234b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4136ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4146ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4152a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
416d1a1f6a4SMatthias Ringwald #endif
4170ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4183deb3ec6SMatthias Ringwald 
4193deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4203deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4213deb3ec6SMatthias Ringwald }
4223deb3ec6SMatthias Ringwald 
4231fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4241fbd72c5SMatthias Ringwald //     return packet[0];
4251fbd72c5SMatthias Ringwald // }
4261fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4271fbd72c5SMatthias Ringwald     return packet[1];
4281fbd72c5SMatthias Ringwald }
4291fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4301fbd72c5SMatthias Ringwald     return packet[2];
4311fbd72c5SMatthias Ringwald }
4321fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4331fbd72c5SMatthias Ringwald     return packet[3];
4341fbd72c5SMatthias Ringwald }
4351fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4361fbd72c5SMatthias Ringwald     return packet[4];
4371fbd72c5SMatthias Ringwald }
4381fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4391fbd72c5SMatthias Ringwald     return packet[5];
4401fbd72c5SMatthias Ringwald }
4411fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4421fbd72c5SMatthias Ringwald     return packet[6];
4431fbd72c5SMatthias Ringwald }
4441fbd72c5SMatthias Ringwald 
4451fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4461fbd72c5SMatthias Ringwald     packet[0] = code;
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4491fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4521fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4531fbd72c5SMatthias Ringwald }
4541fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4551fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4561fbd72c5SMatthias Ringwald }
4571fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4581fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4591fbd72c5SMatthias Ringwald }
4601fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4611fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4621fbd72c5SMatthias Ringwald }
4631fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4641fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4651fbd72c5SMatthias Ringwald }
4661fbd72c5SMatthias Ringwald 
4673deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4681979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4693deb3ec6SMatthias Ringwald     int i;
4703764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47184c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4721979f09cSMatthias Ringwald             return false;
47384c0c5c7SMatthias Ringwald         }
4743deb3ec6SMatthias Ringwald     }
4751979f09cSMatthias Ringwald     return true;
4763deb3ec6SMatthias Ringwald }
4773deb3ec6SMatthias Ringwald 
4781979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4793764b551SMatthias Ringwald     return sm_is_null(random, 8);
4803764b551SMatthias Ringwald }
4813764b551SMatthias Ringwald 
4821979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4833764b551SMatthias Ringwald     return sm_is_null(key, 16);
4843764b551SMatthias Ringwald }
4853764b551SMatthias Ringwald 
48670b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
48770b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
48870b44dd4SMatthias Ringwald 	UNUSED(ts);
48970b44dd4SMatthias Ringwald 	sm_run();
49070b44dd4SMatthias Ringwald }
49170b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4922d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49384c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49470b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49570b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49670b44dd4SMatthias Ringwald }
49770b44dd4SMatthias Ringwald 
4983deb3ec6SMatthias Ringwald // Key utils
4993deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5003deb3ec6SMatthias Ringwald     int i;
5013deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5023deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5033deb3ec6SMatthias Ringwald     }
5043deb3ec6SMatthias Ringwald }
5053deb3ec6SMatthias Ringwald 
5063deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5073deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5083deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5093deb3ec6SMatthias Ringwald     int i;
5103deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5113deb3ec6SMatthias Ringwald         key[15-i] = 0;
5123deb3ec6SMatthias Ringwald     }
5133deb3ec6SMatthias Ringwald }
5143deb3ec6SMatthias Ringwald 
515899e6e02SMatthias Ringwald // ER / IR checks
51621045273SMatthias Ringwald static void sm_er_ir_set_default(void){
517899e6e02SMatthias Ringwald     int i;
518899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
519899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
520899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
521899e6e02SMatthias Ringwald     }
522899e6e02SMatthias Ringwald }
523899e6e02SMatthias Ringwald 
524899e6e02SMatthias Ringwald static int sm_er_is_default(void){
525899e6e02SMatthias Ringwald     int i;
526899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
527899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
528899e6e02SMatthias Ringwald     }
529899e6e02SMatthias Ringwald     return 1;
530899e6e02SMatthias Ringwald }
531899e6e02SMatthias Ringwald 
532899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
533899e6e02SMatthias Ringwald     int i;
534899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
535899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
536899e6e02SMatthias Ringwald     }
537899e6e02SMatthias Ringwald     return 1;
538899e6e02SMatthias Ringwald }
539899e6e02SMatthias Ringwald 
54073102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54173102768SMatthias Ringwald     UNUSED(channel);
54273102768SMatthias Ringwald 
54373102768SMatthias Ringwald     // log event
54473102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54573102768SMatthias Ringwald     // dispatch to all event handlers
54673102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
54773102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
54873102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
54973102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55073102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55173102768SMatthias Ringwald     }
55273102768SMatthias Ringwald }
55373102768SMatthias Ringwald 
55473102768SMatthias Ringwald static void sm_setup_event_base(uint8_t * event, int event_size, uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
55573102768SMatthias Ringwald     event[0] = type;
55673102768SMatthias Ringwald     event[1] = event_size - 2;
55773102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
55873102768SMatthias Ringwald     event[4] = addr_type;
55973102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56073102768SMatthias Ringwald }
56173102768SMatthias Ringwald 
56273102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56373102768SMatthias Ringwald     uint8_t event[11];
56473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56673102768SMatthias Ringwald }
56773102768SMatthias Ringwald 
56873102768SMatthias Ringwald static void sm_notify_client_passkey(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint32_t passkey){
56973102768SMatthias Ringwald     uint8_t event[15];
57073102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57173102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57373102768SMatthias Ringwald }
57473102768SMatthias Ringwald 
57573102768SMatthias Ringwald static void sm_notify_client_index(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint16_t index){
57673102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57773102768SMatthias Ringwald     bd_addr_t identity_address;
57873102768SMatthias Ringwald     int identity_address_type;
57973102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58073102768SMatthias Ringwald 
58173102768SMatthias Ringwald     uint8_t event[20];
58273102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58373102768SMatthias Ringwald     event[11] = identity_address_type;
58473102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58573102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58773102768SMatthias Ringwald }
58873102768SMatthias Ringwald 
58973102768SMatthias Ringwald static void sm_notify_client_status(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint8_t status){
59073102768SMatthias Ringwald     uint8_t event[12];
59173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59273102768SMatthias Ringwald     event[11] = status;
59373102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59473102768SMatthias Ringwald }
59573102768SMatthias Ringwald 
59673102768SMatthias Ringwald 
59773102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
59873102768SMatthias Ringwald 
5993ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6003ab61f77SMatthias Ringwald 
6017b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60273102768SMatthias Ringwald 
60373102768SMatthias Ringwald     int       identity_addr_type;
60473102768SMatthias Ringwald     bd_addr_t identity_addr;
6053c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6063c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6083c0e26deSMatthias Ringwald     } else {
6093c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6103c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6113c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6123c0e26deSMatthias Ringwald     }
61373102768SMatthias Ringwald 
61473102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61573102768SMatthias Ringwald }
61673102768SMatthias Ringwald 
61773102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
61873102768SMatthias Ringwald 
61960be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62060be5b21SMatthias Ringwald 
6217b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62273102768SMatthias Ringwald 
62373102768SMatthias Ringwald     int       identity_addr_type;
62473102768SMatthias Ringwald     bd_addr_t identity_addr;
6253c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6263c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6283c0e26deSMatthias Ringwald     } else {
6293c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6303c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6313c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6323c0e26deSMatthias Ringwald     }
63373102768SMatthias Ringwald 
63473102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63573102768SMatthias Ringwald }
63673102768SMatthias Ringwald 
637d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
638d3c12277SMatthias Ringwald 
639d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
640d3c12277SMatthias Ringwald 
641d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
642d3c12277SMatthias Ringwald 
643d3c12277SMatthias Ringwald     uint8_t event[11];
644d3c12277SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_STARTED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
645d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
646d3c12277SMatthias Ringwald }
647d3c12277SMatthias Ringwald 
6480ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
649f61072f5SMatthias Ringwald 
650d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
651d77906ffSMatthias Ringwald 
65269f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65369f82ad8SMatthias Ringwald 
6540ccf6c9cSMatthias Ringwald     uint8_t event[13];
6550ccf6c9cSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_COMPLETE, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
6560ccf6c9cSMatthias Ringwald     event[11] = status;
6570ccf6c9cSMatthias Ringwald     event[12] = reason;
6580ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6590ccf6c9cSMatthias Ringwald }
6600ccf6c9cSMatthias Ringwald 
6613deb3ec6SMatthias Ringwald // SMP Timeout implementation
6623deb3ec6SMatthias Ringwald 
6633deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6643deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6653deb3ec6SMatthias Ringwald //
6663deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6673deb3ec6SMatthias Ringwald //
6683deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6693deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6703deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6713deb3ec6SMatthias Ringwald // established.
6723deb3ec6SMatthias Ringwald 
673ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6743deb3ec6SMatthias Ringwald     log_info("SM timeout");
675c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6763deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67768a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6780ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6793deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6803deb3ec6SMatthias Ringwald 
6813deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6823deb3ec6SMatthias Ringwald     sm_run();
6833deb3ec6SMatthias Ringwald }
6843deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
685528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
687528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
688528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
689528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6903deb3ec6SMatthias Ringwald }
6913deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
692528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6933deb3ec6SMatthias Ringwald }
6943deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6953deb3ec6SMatthias Ringwald     sm_timeout_stop();
6963deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald 
6993deb3ec6SMatthias Ringwald // end of sm timeout
7003deb3ec6SMatthias Ringwald 
7013deb3ec6SMatthias Ringwald // GAP Random Address updates
7023deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
703ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7043deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7053deb3ec6SMatthias Ringwald 
7063deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
707899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
708d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
709fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71070b44dd4SMatthias Ringwald     sm_trigger_run();
7113deb3ec6SMatthias Ringwald }
7123deb3ec6SMatthias Ringwald 
713ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7149ec2630cSMatthias Ringwald     UNUSED(timer);
7159ec2630cSMatthias Ringwald 
7163deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
717528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
718528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7193deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7203deb3ec6SMatthias Ringwald }
7213deb3ec6SMatthias Ringwald 
7223deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
723528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
724528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
725528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7263deb3ec6SMatthias Ringwald }
7273deb3ec6SMatthias Ringwald 
7283deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
729528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7303deb3ec6SMatthias Ringwald }
7313deb3ec6SMatthias Ringwald 
7323deb3ec6SMatthias Ringwald // ah(k,r) helper
7333deb3ec6SMatthias Ringwald // r = padding || r
7343deb3ec6SMatthias Ringwald // r - 24 bit value
7354a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7363deb3ec6SMatthias Ringwald     // r'= padding || r
7373deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7386535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7393deb3ec6SMatthias Ringwald }
7403deb3ec6SMatthias Ringwald 
7413deb3ec6SMatthias Ringwald // d1 helper
7423deb3ec6SMatthias Ringwald // d' = padding || r || d
7433deb3ec6SMatthias Ringwald // d,r - 16 bit values
7444a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7453deb3ec6SMatthias Ringwald     // d'= padding || r || d
7463deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
747f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
748f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7493deb3ec6SMatthias Ringwald }
7503deb3ec6SMatthias Ringwald 
7513deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7524a6806f3SMatthias Ringwald static void sm_c1_t1(sm_key_t r, uint8_t preq[7], uint8_t pres[7], uint8_t iat, uint8_t rat, uint8_t * t1){
7533deb3ec6SMatthias Ringwald 
7543deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7553deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7563deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7573deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7583deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7593deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald     sm_key_t p1;
7629c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7639c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7643deb3ec6SMatthias Ringwald     p1[14] = rat;
7653deb3ec6SMatthias Ringwald     p1[15] = iat;
7668314c363SMatthias Ringwald     log_info_key("p1", p1);
7678314c363SMatthias Ringwald     log_info_key("r", r);
7683deb3ec6SMatthias Ringwald 
7693deb3ec6SMatthias Ringwald     // t1 = r xor p1
7703deb3ec6SMatthias Ringwald     int i;
7713deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7723deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7733deb3ec6SMatthias Ringwald     }
7748314c363SMatthias Ringwald     log_info_key("t1", t1);
7753deb3ec6SMatthias Ringwald }
7763deb3ec6SMatthias Ringwald 
7773deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7784a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7793deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7803deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7813deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7823deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7833deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7843deb3ec6SMatthias Ringwald 
7853deb3ec6SMatthias Ringwald     sm_key_t p2;
7863deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7876535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7886535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7898314c363SMatthias Ringwald     log_info_key("p2", p2);
7903deb3ec6SMatthias Ringwald 
7913deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7923deb3ec6SMatthias Ringwald     int i;
7933deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7943deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7953deb3ec6SMatthias Ringwald     }
7968314c363SMatthias Ringwald     log_info_key("t3", t3);
7973deb3ec6SMatthias Ringwald }
7983deb3ec6SMatthias Ringwald 
7994a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8008314c363SMatthias Ringwald     log_info_key("r1", r1);
8018314c363SMatthias Ringwald     log_info_key("r2", r2);
8026535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8036535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8043deb3ec6SMatthias Ringwald }
8053deb3ec6SMatthias Ringwald 
806fbe050beSMatthias Ringwald 
8073deb3ec6SMatthias Ringwald // decide on stk generation based on
8083deb3ec6SMatthias Ringwald // - pairing request
8093deb3ec6SMatthias Ringwald // - io capabilities
8103deb3ec6SMatthias Ringwald // - OOB data availability
8113deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8123deb3ec6SMatthias Ringwald 
8138334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8148334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8158334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8168334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8178334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8188334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8198334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8208334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8218334d3d8SMatthias Ringwald     };
8228334d3d8SMatthias Ringwald 
8238334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8248334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8258334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8278334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8288334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8298334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8308334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8318334d3d8SMatthias Ringwald     };
8328334d3d8SMatthias Ringwald #endif
8338334d3d8SMatthias Ringwald 
8343deb3ec6SMatthias Ringwald     // default: just works
8353deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8363deb3ec6SMatthias Ringwald 
83727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83827c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83927c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8404ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84127c32905SMatthias Ringwald #else
84227c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84327c32905SMatthias Ringwald #endif
84498d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84527c32905SMatthias Ringwald 
84665a9a04eSMatthias Ringwald 
84765a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8481979f09cSMatthias Ringwald     bool use_oob;
84965a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85065a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85165a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8521979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85365a9a04eSMatthias Ringwald     } else {
85465a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85565a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8561979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85765a9a04eSMatthias Ringwald     }
85865a9a04eSMatthias Ringwald     if (use_oob){
85965a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86065a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86165a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86265a9a04eSMatthias Ringwald         return;
86365a9a04eSMatthias Ringwald     }
86465a9a04eSMatthias Ringwald 
86527c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86627c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86727c32905SMatthias Ringwald     // model shall be used.
8684ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8694ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87027c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87127c32905SMatthias Ringwald         return;
87227c32905SMatthias Ringwald     }
87327c32905SMatthias Ringwald 
8743deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8753deb3ec6SMatthias Ringwald     sm_reset_tk();
8763deb3ec6SMatthias Ringwald 
8773deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8788da2e96dSMatthias Ringwald     if ((sm_pairing_packet_get_io_capability(setup->sm_m_preq) > IO_CAPABILITY_KEYBOARD_DISPLAY) || (sm_pairing_packet_get_io_capability(setup->sm_s_pres) > IO_CAPABILITY_KEYBOARD_DISPLAY)){
8793deb3ec6SMatthias Ringwald         return;
8803deb3ec6SMatthias Ringwald     }
8813deb3ec6SMatthias Ringwald 
8823deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8833deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88427c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88527c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88627c32905SMatthias Ringwald 
88727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
888c6b7cbd9SMatthias Ringwald     // table not define by default
88927c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89027c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89127c32905SMatthias Ringwald     }
89227c32905SMatthias Ringwald #endif
89327c32905SMatthias Ringwald     setup->sm_stk_generation_method = generation_method[sm_pairing_packet_get_io_capability(setup->sm_s_pres)][sm_pairing_packet_get_io_capability(setup->sm_m_preq)];
89427c32905SMatthias Ringwald 
8953deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8961ad129beSMatthias Ringwald         sm_pairing_packet_get_io_capability(setup->sm_m_preq), sm_pairing_packet_get_io_capability(setup->sm_s_pres), setup->sm_stk_generation_method);
8973deb3ec6SMatthias Ringwald }
8983deb3ec6SMatthias Ringwald 
8993deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9003deb3ec6SMatthias Ringwald     int flags = 0;
9013deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9023deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9033deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9043deb3ec6SMatthias Ringwald     }
9053deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9073deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9083deb3ec6SMatthias Ringwald     }
9093deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     return flags;
9133deb3ec6SMatthias Ringwald }
9143deb3ec6SMatthias Ringwald 
915*9a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9163deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
917*9a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
918*9a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
919715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9209790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
921715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9229790be5fSMatthias Ringwald #endif
9233deb3ec6SMatthias Ringwald }
9243deb3ec6SMatthias Ringwald 
9253deb3ec6SMatthias Ringwald // CSRK Key Lookup
9263deb3ec6SMatthias Ringwald 
9273deb3ec6SMatthias Ringwald 
9283deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9293deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9303deb3ec6SMatthias Ringwald }
9313deb3ec6SMatthias Ringwald 
932711e6c80SMatthias Ringwald static void sm_address_resolution_start_lookup(uint8_t addr_type, hci_con_handle_t con_handle, bd_addr_t addr, address_resolution_mode_t mode, void * context){
9336535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9343deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9353deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9363deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9373deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
938711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9393deb3ec6SMatthias Ringwald }
9403deb3ec6SMatthias Ringwald 
9413deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9423deb3ec6SMatthias Ringwald     // check if already in list
943665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9443deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
945665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
946665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
947665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9483deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9493deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9503deb3ec6SMatthias Ringwald         // already in list
9513deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9523deb3ec6SMatthias Ringwald     }
9533deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9543deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9553deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9566535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
957665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
95870b44dd4SMatthias Ringwald     sm_trigger_run();
9593deb3ec6SMatthias Ringwald     return 0;
9603deb3ec6SMatthias Ringwald }
9613deb3ec6SMatthias Ringwald 
962d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
963d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
964514d35fcSMatthias Ringwald 
965d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
966d1a1f6a4SMatthias Ringwald     UNUSED(arg);
967d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
968d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
96970b44dd4SMatthias Ringwald     sm_trigger_run();
9703deb3ec6SMatthias Ringwald }
971514d35fcSMatthias Ringwald 
9724dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9734ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9743deb3ec6SMatthias Ringwald }
9756d80b495SMatthias Ringwald #endif
9763deb3ec6SMatthias Ringwald 
9776d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
978514d35fcSMatthias Ringwald // generic cmac calculation
979d1a1f6a4SMatthias Ringwald static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash)){
980d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
981d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
982d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9833deb3ec6SMatthias Ringwald }
9847a766ebfSMatthias Ringwald #endif
9853deb3ec6SMatthias Ringwald 
986514d35fcSMatthias Ringwald // cmac for ATT Message signing
9877a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
988d1a1f6a4SMatthias Ringwald 
989d1a1f6a4SMatthias Ringwald static void sm_cmac_generator_start(const sm_key_t key, uint16_t message_len, uint8_t (*get_byte_callback)(uint16_t offset), void (*done_callback)(uint8_t * hash)){
990d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
991d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
992d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
993d1a1f6a4SMatthias Ringwald }
994d1a1f6a4SMatthias Ringwald 
9954dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
996d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
997d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
9984dfd504aSMatthias Ringwald         return 0;
9994dfd504aSMatthias Ringwald     }
10004dfd504aSMatthias Ringwald 
1001d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10024dfd504aSMatthias Ringwald 
1003d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10044dfd504aSMatthias Ringwald     if (offset < 3){
1005d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10064dfd504aSMatthias Ringwald     }
1007d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10084dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1009d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10104dfd504aSMatthias Ringwald     }
1011d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10124dfd504aSMatthias Ringwald }
10134dfd504aSMatthias Ringwald 
10144dfd504aSMatthias Ringwald void sm_cmac_signed_write_start(const sm_key_t k, uint8_t opcode, hci_con_handle_t con_handle, uint16_t message_len, const uint8_t * message, uint32_t sign_counter, void (*done_handler)(uint8_t * hash)){
1015514d35fcSMatthias Ringwald     // ATT Message Signing
1016d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1017d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1018d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1019514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1020d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1021d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1022d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10233deb3ec6SMatthias Ringwald }
10247a766ebfSMatthias Ringwald #endif
10253deb3ec6SMatthias Ringwald 
10263deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1027446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10283deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1029d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10303deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10313deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10333deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10345611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10353deb3ec6SMatthias Ringwald             } else {
1036c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10373deb3ec6SMatthias Ringwald             }
10383deb3ec6SMatthias Ringwald             break;
10393deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
104042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1041c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10423deb3ec6SMatthias Ringwald             } else {
10433deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10445611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10453deb3ec6SMatthias Ringwald             }
10463deb3ec6SMatthias Ringwald             break;
104747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10483deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10495611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10503deb3ec6SMatthias Ringwald             break;
105147fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1052446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1053c8c46d51SMatthias Ringwald             sm_notify_client_passkey(SM_EVENT_NUMERIC_COMPARISON_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
105427c32905SMatthias Ringwald             break;
10553deb3ec6SMatthias Ringwald         case JUST_WORKS:
10563deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10575611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_JUST_WORKS_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10583deb3ec6SMatthias Ringwald             break;
10593deb3ec6SMatthias Ringwald         case OOB:
10603deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10613deb3ec6SMatthias Ringwald             break;
10627bbeb3adSMilanka Ringwald         default:
10637bbeb3adSMilanka Ringwald             btstack_assert(false);
10647bbeb3adSMilanka Ringwald             break;
10653deb3ec6SMatthias Ringwald     }
10663deb3ec6SMatthias Ringwald }
10673deb3ec6SMatthias Ringwald 
10683deb3ec6SMatthias Ringwald static int sm_key_distribution_all_received(sm_connection_t * sm_conn){
10693deb3ec6SMatthias Ringwald     int recv_flags;
107042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
107152f9cf63SMatthias Ringwald         // slave / responder
10721ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres));
10733deb3ec6SMatthias Ringwald     } else {
10743deb3ec6SMatthias Ringwald         // master / initiator
10751ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
10763deb3ec6SMatthias Ringwald     }
1077eddc894fSMatthias Ringwald 
1078eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1079*9a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1080eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1081eddc894fSMatthias Ringwald         recv_flags &= ~(SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION | SM_KEYDIST_FLAG_MASTER_IDENTIFICATION);
1082eddc894fSMatthias Ringwald     }
1083eddc894fSMatthias Ringwald #endif
1084eddc894fSMatthias Ringwald 
10853deb3ec6SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, recv_flags);
108644263cccSMatthias Ringwald     return (setup->sm_key_distribution_received_set & recv_flags) == recv_flags;
10873deb3ec6SMatthias Ringwald }
10883deb3ec6SMatthias Ringwald 
1089711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10907149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10913deb3ec6SMatthias Ringwald         sm_timeout_stop();
10927149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1093711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1094c085d9ffSMatthias Ringwald 
1095c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1096c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1097c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1098c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1099c085d9ffSMatthias Ringwald         }
1100c085d9ffSMatthias Ringwald #endif
11013deb3ec6SMatthias Ringwald     }
11023deb3ec6SMatthias Ringwald }
11033deb3ec6SMatthias Ringwald 
11047d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11051dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11060ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11071dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11081dca9d8aSMatthias Ringwald }
11091dca9d8aSMatthias Ringwald 
11103deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1111bb09604fSMatthias Ringwald 
1112bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11133deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1114bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11153deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1116bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1117bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1118bb09604fSMatthias Ringwald #endif
11197ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11207ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11217ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11227ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11237ece0eaaSMatthias Ringwald         }
11247ece0eaaSMatthias Ringwald #endif
11253deb3ec6SMatthias Ringwald     }
11263deb3ec6SMatthias Ringwald     return flags;
11273deb3ec6SMatthias Ringwald }
11283deb3ec6SMatthias Ringwald 
1129d7471931SMatthias Ringwald static void sm_reset_setup(void){
11303deb3ec6SMatthias Ringwald     // fill in sm setup
1131901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1132dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
11333deb3ec6SMatthias Ringwald     sm_reset_tk();
1134d7471931SMatthias Ringwald }
1135d7471931SMatthias Ringwald 
1136d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1137d7471931SMatthias Ringwald 
1138d7471931SMatthias Ringwald     // fill in sm setup
11393deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11406535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11413deb3ec6SMatthias Ringwald 
1142a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
1143a680ba6bSMatthias Ringwald     setup->sm_have_oob_data = 0;
11449305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1145a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11463deb3ec6SMatthias Ringwald     }
11473deb3ec6SMatthias Ringwald 
1148a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1149a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11504acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11514acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1152a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11539305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11544acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1155a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1156a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1157a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1158a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11594acf7b7bSMatthias Ringwald                     setup->sm_ra);
11604acf7b7bSMatthias Ringwald             } else {
11614acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11624acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11634acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11644acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11654acf7b7bSMatthias Ringwald                     setup->sm_rb);
11664acf7b7bSMatthias Ringwald             }
1167a680ba6bSMatthias Ringwald         } else {
1168a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1169a680ba6bSMatthias Ringwald         }
1170a680ba6bSMatthias Ringwald     }
1171a680ba6bSMatthias Ringwald #endif
1172a680ba6bSMatthias Ringwald 
11733deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11753deb3ec6SMatthias Ringwald         // slave
11763deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11773deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1178d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11796535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1180d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11813deb3ec6SMatthias Ringwald     } else {
11823deb3ec6SMatthias Ringwald         // master
11833deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11843deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1185d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11866535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1187d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11883deb3ec6SMatthias Ringwald 
11893deb3ec6SMatthias Ringwald         int key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11901ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11911ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11923deb3ec6SMatthias Ringwald     }
11933deb3ec6SMatthias Ringwald 
119457132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
11952c041b42SMatthias Ringwald     uint8_t max_encryptinon_key_size = sm_max_encryption_key_size;
11962c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11972c041b42SMatthias Ringwald     // enable SC for SC only mode
11982c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11992c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
12002c041b42SMatthias Ringwald         max_encryptinon_key_size = 16;
12012c041b42SMatthias Ringwald     }
12022c041b42SMatthias Ringwald #endif
120357132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120457132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120557132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120657132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120757132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120857132f12SMatthias Ringwald 	}
120957132f12SMatthias Ringwald #endif
12101ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1211a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1212df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
12132c041b42SMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryptinon_key_size);
12143deb3ec6SMatthias Ringwald }
12153deb3ec6SMatthias Ringwald 
12163deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12173deb3ec6SMatthias Ringwald 
12183deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
1219*9a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
1220*9a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
122142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
122252f9cf63SMatthias Ringwald         // slave / responder
12233deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
1224*9a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
1225*9a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12263deb3ec6SMatthias Ringwald     } else {
12273deb3ec6SMatthias Ringwald         // master / initiator
12283deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
1229*9a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
1230*9a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12313deb3ec6SMatthias Ringwald     }
12323deb3ec6SMatthias Ringwald 
12333deb3ec6SMatthias Ringwald     // check key size
12342c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12352c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12362c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12372c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12382c041b42SMatthias Ringwald     }
12392c041b42SMatthias Ringwald #endif
12401ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12414ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12423deb3ec6SMatthias Ringwald 
1243eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12443deb3ec6SMatthias Ringwald     sm_setup_tk();
12453deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12463deb3ec6SMatthias Ringwald 
12473deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12483deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12493deb3ec6SMatthias Ringwald 
1250eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12512c041b42SMatthias Ringwald     // Check LE SC Only mode
12523cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12533cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12543cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12553cdbe9dbSMatthias Ringwald     }
12563cdbe9dbSMatthias Ringwald 
1257*9a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1258eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1259*9a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
1260*9a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1261eddc894fSMatthias Ringwald     }
1262eddc894fSMatthias Ringwald #endif
1263eddc894fSMatthias Ringwald 
126452f9cf63SMatthias Ringwald     // identical to responder
1265*9a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
126652f9cf63SMatthias Ringwald 
12673deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1268c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     return 0;
12713deb3ec6SMatthias Ringwald }
12723deb3ec6SMatthias Ringwald 
12733deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12743deb3ec6SMatthias Ringwald 
12753deb3ec6SMatthias Ringwald     // cache and reset context
12763deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12773deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12783deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12793deb3ec6SMatthias Ringwald 
12803deb3ec6SMatthias Ringwald     // reset context
12813deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12823deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12833deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1284711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12853deb3ec6SMatthias Ringwald 
12863deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1287d2e90122SMatthias Ringwald     sm_key_t ltk;
12881979f09cSMatthias Ringwald     bool have_ltk;
12896c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12901979f09cSMatthias Ringwald     bool trigger_pairing;
129142134bc6SMatthias Ringwald #endif
12923deb3ec6SMatthias Ringwald     switch (mode){
12933deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12943deb3ec6SMatthias Ringwald             break;
12953deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12963deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1297711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12986c44b759SMatthias Ringwald 
12996c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
13006c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
13016c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
13026c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
13036c44b759SMatthias Ringwald 
13043deb3ec6SMatthias Ringwald             switch (event){
1305a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13063deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13073deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1308a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13096c44b759SMatthias Ringwald 
13106c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13116c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13126c44b759SMatthias Ringwald 
13136c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13146c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1315212d735eSMatthias Ringwald                         // IRK required before, continue
13166c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13176c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13186c39055aSMatthias Ringwald                             break;
13196c39055aSMatthias Ringwald                         }
1320212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1321212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1322212d735eSMatthias Ringwald                             break;
1323212d735eSMatthias Ringwald                         }
13247af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13257af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13266c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13277af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13287af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13296c44b759SMatthias Ringwald #endif
13307af5dcd5SMatthias Ringwald 
13317af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13321979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13337af5dcd5SMatthias Ringwald 
13347af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13357af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13367af5dcd5SMatthias Ringwald                             if (have_ltk){
13377af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13387af5dcd5SMatthias Ringwald                             } else {
13397af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13407af5dcd5SMatthias Ringwald                             }
13417af5dcd5SMatthias Ringwald                             sm_trigger_run();
13426c44b759SMatthias Ringwald                         }
13436c44b759SMatthias Ringwald #endif
13446c44b759SMatthias Ringwald                     } else {
13456c44b759SMatthias Ringwald 
134642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13476c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13486c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13496c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13501979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13513deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
135209ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
135332bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1354c245ca32SMatthias Ringwald 
1355d4af1595SMatthias Ringwald                         if (have_ltk){
13566a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1357b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135832bc5d65SMatthias Ringwald #else
135932bc5d65SMatthias Ringwald                             if (trigger_pairing){
136032bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
136132bc5d65SMatthias Ringwald                             } else {
136232bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
136332bc5d65SMatthias Ringwald                             }
136432bc5d65SMatthias Ringwald #endif
136532bc5d65SMatthias Ringwald                         }
136632bc5d65SMatthias Ringwald 
136732bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13686c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13695567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1370d4af1595SMatthias Ringwald                             break;
1371d4af1595SMatthias Ringwald                         }
13726c44b759SMatthias Ringwald 
13736c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13746c44b759SMatthias Ringwald                         if (trigger_pairing){
13753deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1376d4af1595SMatthias Ringwald                             break;
13773deb3ec6SMatthias Ringwald                         }
137842134bc6SMatthias Ringwald #endif
1379298ab52bSMatthias Ringwald                     }
13803deb3ec6SMatthias Ringwald                     break;
13813deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13823deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13836c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13847af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13856c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13866c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13876c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13886c39055aSMatthias Ringwald                         }
13897af5dcd5SMatthias Ringwald                         // send security request if requested
13907af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13917af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13927af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13937af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13947af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13957af5dcd5SMatthias Ringwald                         }
13966c39055aSMatthias Ringwald                         break;
13977af5dcd5SMatthias Ringwald #endif
13986c39055aSMatthias Ringwald                     }
139942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
140009ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
14013deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
140209ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
14033deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
140442134bc6SMatthias Ringwald #endif
14053deb3ec6SMatthias Ringwald                     break;
14067bbeb3adSMilanka Ringwald 
14077bbeb3adSMilanka Ringwald                 default:
14087bbeb3adSMilanka Ringwald                     btstack_assert(false);
14097bbeb3adSMilanka Ringwald                     break;
14103deb3ec6SMatthias Ringwald             }
14113deb3ec6SMatthias Ringwald             break;
14123deb3ec6SMatthias Ringwald         default:
14133deb3ec6SMatthias Ringwald             break;
14143deb3ec6SMatthias Ringwald     }
14153deb3ec6SMatthias Ringwald 
14163deb3ec6SMatthias Ringwald     switch (event){
1417a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1418711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14193deb3ec6SMatthias Ringwald             break;
14203deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1421711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14223deb3ec6SMatthias Ringwald             break;
14237bbeb3adSMilanka Ringwald         default:
14247bbeb3adSMilanka Ringwald             btstack_assert(false);
14257bbeb3adSMilanka Ringwald             break;
14263deb3ec6SMatthias Ringwald     }
14273deb3ec6SMatthias Ringwald }
14283deb3ec6SMatthias Ringwald 
14293deb3ec6SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
14303deb3ec6SMatthias Ringwald 
14313deb3ec6SMatthias Ringwald     int le_db_index = -1;
14323deb3ec6SMatthias Ringwald 
143327ef8bc8SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
14341979f09cSMatthias Ringwald     bool bonding_enabed = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
143527ef8bc8SMatthias Ringwald                          & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
14364ea43905SMatthias Ringwald                          & SM_AUTHREQ_BONDING ) != 0u;
143727ef8bc8SMatthias Ringwald 
143827ef8bc8SMatthias Ringwald     if (bonding_enabed){
143927ef8bc8SMatthias Ringwald 
14403deb3ec6SMatthias Ringwald         // lookup device based on IRK
14413deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14423deb3ec6SMatthias Ringwald             int i;
1443092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14443deb3ec6SMatthias Ringwald                 sm_key_t irk;
14453deb3ec6SMatthias Ringwald                 bd_addr_t address;
1446c7e2c1a5SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14473deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, irk);
1448adf5eaa9SMatthias Ringwald                 // skip unused entries
1449c7e2c1a5SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1450c7e2c1a5SMatthias Ringwald                 // compare IRK
1451c7e2c1a5SMatthias Ringwald                 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1452c7e2c1a5SMatthias Ringwald 
14533deb3ec6SMatthias Ringwald                 log_info("sm: device found for IRK, updating");
14543deb3ec6SMatthias Ringwald                 le_db_index = i;
14553deb3ec6SMatthias Ringwald                 break;
14563deb3ec6SMatthias Ringwald             }
1457c7e2c1a5SMatthias Ringwald         } else {
1458c7e2c1a5SMatthias Ringwald             // assert IRK is set to zero
1459c7e2c1a5SMatthias Ringwald             memset(setup->sm_peer_irk, 0, 16);
14603deb3ec6SMatthias Ringwald         }
14613deb3ec6SMatthias Ringwald 
14623deb3ec6SMatthias Ringwald         // if not found, lookup via public address if possible
14633deb3ec6SMatthias Ringwald         log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1464c1ab6cc1SMatthias Ringwald         if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14653deb3ec6SMatthias Ringwald             int i;
1466092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14673deb3ec6SMatthias Ringwald                 bd_addr_t address;
1468adf5eaa9SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14693deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, NULL);
1470adf5eaa9SMatthias Ringwald                 // skip unused entries
1471adf5eaa9SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14723deb3ec6SMatthias Ringwald                 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14735df9dc78SMatthias Ringwald                 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14743deb3ec6SMatthias Ringwald                     log_info("sm: device found for public address, updating");
14753deb3ec6SMatthias Ringwald                     le_db_index = i;
14763deb3ec6SMatthias Ringwald                     break;
14773deb3ec6SMatthias Ringwald                 }
14783deb3ec6SMatthias Ringwald             }
14793deb3ec6SMatthias Ringwald         }
14803deb3ec6SMatthias Ringwald 
14813deb3ec6SMatthias Ringwald         // if not found, add to db
148202b02cffSMatthias Ringwald         bool new_to_le_device_db = false;
14833deb3ec6SMatthias Ringwald         if (le_db_index < 0) {
14843deb3ec6SMatthias Ringwald             le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
148502b02cffSMatthias Ringwald 			new_to_le_device_db = true;
14863deb3ec6SMatthias Ringwald         }
14873deb3ec6SMatthias Ringwald 
14883deb3ec6SMatthias Ringwald         if (le_db_index >= 0){
14893deb3ec6SMatthias Ringwald 
149002b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
149102b02cffSMatthias Ringwald         	if (!new_to_le_device_db){
149202b02cffSMatthias Ringwald 				hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
149302b02cffSMatthias Ringwald         	}
149402b02cffSMatthias Ringwald 			hci_load_le_device_db_entry_into_resolving_list(le_db_index);
149502b02cffSMatthias Ringwald #else
149602b02cffSMatthias Ringwald 			UNUSED(new_to_le_device_db);
149702b02cffSMatthias Ringwald #endif
149802b02cffSMatthias Ringwald 
149948163929SMatthias 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);
1500e1086030SMatthias Ringwald             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
15017710ebd2SMatthias Ringwald             sm_conn->sm_le_db_index = le_db_index;
150248163929SMatthias Ringwald 
1503eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
15043deb3ec6SMatthias Ringwald             // store local CSRK
1505715a43d1SMatthias Ringwald             setup->sm_le_device_index = le_db_index;
1506715a43d1SMatthias Ringwald             if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15073deb3ec6SMatthias Ringwald                 log_info("sm: store local CSRK");
15083deb3ec6SMatthias Ringwald                 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15093deb3ec6SMatthias Ringwald                 le_device_db_local_counter_set(le_db_index, 0);
15103deb3ec6SMatthias Ringwald             }
15113deb3ec6SMatthias Ringwald 
15123deb3ec6SMatthias Ringwald             // store remote CSRK
15133deb3ec6SMatthias Ringwald             if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15143deb3ec6SMatthias Ringwald                 log_info("sm: store remote CSRK");
15153deb3ec6SMatthias Ringwald                 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15163deb3ec6SMatthias Ringwald                 le_device_db_remote_counter_set(le_db_index, 0);
15173deb3ec6SMatthias Ringwald             }
1518eda85fbfSMatthias Ringwald #endif
151978f44163SMatthias Ringwald             // store encryption information for secure connections: LTK generated by ECDH
152078f44163SMatthias Ringwald             if (setup->sm_use_secure_connections){
1521e6343eb6SMatthias Ringwald                 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
152278f44163SMatthias Ringwald                 uint8_t zero_rand[8];
152378f44163SMatthias Ringwald                 memset(zero_rand, 0, 8);
152478f44163SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15253dc3a67dSMatthias Ringwald                     sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
152678f44163SMatthias Ringwald             }
152778f44163SMatthias Ringwald 
1528e6343eb6SMatthias Ringwald             // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152978f44163SMatthias Ringwald             else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
153078f44163SMatthias Ringwald                    && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1531e6343eb6SMatthias Ringwald                 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15323deb3ec6SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15333dc3a67dSMatthias Ringwald                     sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
153478f44163SMatthias Ringwald 
15353deb3ec6SMatthias Ringwald             }
15363deb3ec6SMatthias Ringwald         }
153727ef8bc8SMatthias Ringwald     } else {
153827ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153927ef8bc8SMatthias Ringwald     }
15403deb3ec6SMatthias Ringwald }
15413deb3ec6SMatthias Ringwald 
1542688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1543f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1544688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1545688a08f9SMatthias Ringwald }
1546688a08f9SMatthias Ringwald 
1547688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1548688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1549688a08f9SMatthias Ringwald }
1550688a08f9SMatthias Ringwald 
15519af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1552688a08f9SMatthias Ringwald 
1553dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1554945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1555f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1556dc300847SMatthias Ringwald 
1557b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1558b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15591f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1560b90c4e75SMatthias Ringwald     } else {
1561b90c4e75SMatthias 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);
1562b35a3de2SMatthias Ringwald     }
1563b35a3de2SMatthias Ringwald }
1564b35a3de2SMatthias Ringwald 
1565688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
156642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1567688a08f9SMatthias Ringwald         // Responder
15684acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15694acf7b7bSMatthias Ringwald             // generate Nb
15704acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15716ca80073SMatthias 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);
15724acf7b7bSMatthias Ringwald         } else {
1573688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15744acf7b7bSMatthias Ringwald         }
1575688a08f9SMatthias Ringwald     } else {
1576688a08f9SMatthias Ringwald         // Initiator role
1577688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1578688a08f9SMatthias Ringwald             case JUST_WORKS:
1579dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1580688a08f9SMatthias Ringwald                 break;
1581688a08f9SMatthias Ringwald 
158247fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1583bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1584688a08f9SMatthias Ringwald                 break;
1585688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1586688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158747fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15884ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1589b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1590688a08f9SMatthias Ringwald                 } else {
1591dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1592688a08f9SMatthias Ringwald                 }
1593688a08f9SMatthias Ringwald                 break;
1594688a08f9SMatthias Ringwald             case OOB:
159565a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1596688a08f9SMatthias Ringwald                 break;
15977bbeb3adSMilanka Ringwald             default:
15987bbeb3adSMilanka Ringwald                 btstack_assert(false);
15997bbeb3adSMilanka Ringwald                 break;
1600688a08f9SMatthias Ringwald         }
1601688a08f9SMatthias Ringwald     }
1602688a08f9SMatthias Ringwald }
1603688a08f9SMatthias Ringwald 
1604aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1605688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1606688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1607688a08f9SMatthias Ringwald 
1608c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1609c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1610a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1611c59d0c92SMatthias Ringwald         return;
1612c59d0c92SMatthias Ringwald     }
1613c59d0c92SMatthias Ringwald 
1614bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1615bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16166857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16172bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1618b4f65634SMatthias Ringwald #endif
1619bd57ffebSMatthias Ringwald 
1620bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1621aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16226535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1623bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1624aec94140SMatthias Ringwald             break;
1625688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1626688a08f9SMatthias Ringwald             // check
1627688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1628bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1629688a08f9SMatthias Ringwald                 break;
1630688a08f9SMatthias Ringwald             }
1631bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1632688a08f9SMatthias Ringwald             break;
1633901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1634901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1635901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1636901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1637901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1638019005a0SMatthias Ringwald             break;
1639019005a0SMatthias Ringwald         }
16400346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16416535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1642bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16430346c37cSMatthias Ringwald             break;
16440346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16456535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1646bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16470346c37cSMatthias Ringwald             break;
16480346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1649b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1650b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1651b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1652b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16536535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16546535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1655893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1656bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1657019005a0SMatthias Ringwald             break;
1658901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16596535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
166042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1661901c000fSMatthias Ringwald                 // responder
1662901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1663901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1664901c000fSMatthias Ringwald                 } else {
1665901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1666901c000fSMatthias Ringwald                 }
1667901c000fSMatthias Ringwald             } else {
1668901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1669901c000fSMatthias Ringwald             }
1670901c000fSMatthias Ringwald             break;
1671901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1672901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1673901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1674aec94140SMatthias Ringwald                 break;
1675aec94140SMatthias Ringwald             }
167642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1677901c000fSMatthias Ringwald                 // responder
1678901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1679901c000fSMatthias Ringwald             } else {
1680901c000fSMatthias Ringwald                 // initiator
1681901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1682bd57ffebSMatthias Ringwald             }
1683901c000fSMatthias Ringwald             break;
16846857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
168557132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16866535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168757132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16882bacf595SMatthias Ringwald             break;
168957132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16902bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16912bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16922bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16938974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
169455160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16958974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16962bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16972bacf595SMatthias Ringwald             } else {
16982bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16992bacf595SMatthias Ringwald             }
17000ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17012bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17022bacf595SMatthias Ringwald             break;
1703bdb14b0eSMatthias Ringwald #endif
1704bd57ffebSMatthias Ringwald         default:
1705bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1706bd57ffebSMatthias Ringwald             break;
1707bd57ffebSMatthias Ringwald     }
170870b44dd4SMatthias Ringwald     sm_trigger_run();
1709aec94140SMatthias Ringwald }
1710aec94140SMatthias Ringwald 
1711688a08f9SMatthias 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){
1712dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1713aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17146535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17156535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1716aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1717aec94140SMatthias Ringwald     log_info("f4 key");
1718aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1719aec94140SMatthias Ringwald     log_info("f4 message");
1720dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1721d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1722aec94140SMatthias Ringwald }
1723aec94140SMatthias Ringwald 
17240346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17250346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17260346c37cSMatthias Ringwald 
17270346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17288334d3d8SMatthias Ringwald 
17298334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17308334d3d8SMatthias Ringwald 
173140c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17320346c37cSMatthias Ringwald     // calculate salt for f5
17330346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17340346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17356535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1736d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17370346c37cSMatthias Ringwald }
17380346c37cSMatthias Ringwald 
17390346c37cSMatthias 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){
17400346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17410346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17420346c37cSMatthias Ringwald 
17430346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17440346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17456535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17466535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17476535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17486535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17496535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17506535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17510346c37cSMatthias Ringwald     log_info("f5 key");
17520346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17530346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17540346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1755d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17560346c37cSMatthias Ringwald }
17570346c37cSMatthias Ringwald 
17580346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17590346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17600346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17610346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17626535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17636535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
176442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17650346c37cSMatthias Ringwald         // responder
17660346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17670346c37cSMatthias Ringwald     } else {
17680346c37cSMatthias Ringwald         // initiator
17690346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17700346c37cSMatthias Ringwald     }
17710346c37cSMatthias Ringwald }
17720346c37cSMatthias Ringwald 
17730346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17740346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17750346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17760346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17770346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17780346c37cSMatthias Ringwald     // 1..52 setup before
17790346c37cSMatthias Ringwald     log_info("f5 key");
17800346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17810346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17820346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1783d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17840346c37cSMatthias Ringwald }
1785f92edc8eSMatthias Ringwald 
17860346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17870346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17880346c37cSMatthias Ringwald }
17890346c37cSMatthias Ringwald 
179031f061fbSMatthias 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){
17916535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17926535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17936535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17946535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
17956535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
17966535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
179731f061fbSMatthias Ringwald }
179831f061fbSMatthias Ringwald 
179931f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180031f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180131f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1802dc300847SMatthias Ringwald     log_info("f6 key");
1803dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1804dc300847SMatthias Ringwald     log_info("f6 message");
1805dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1806d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1807dc300847SMatthias Ringwald }
1808dc300847SMatthias Ringwald 
1809f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1810f92edc8eSMatthias Ringwald // - U is 256 bits
1811f92edc8eSMatthias Ringwald // - V is 256 bits
1812f92edc8eSMatthias Ringwald // - X is 128 bits
1813f92edc8eSMatthias Ringwald // - Y is 128 bits
1814bd57ffebSMatthias 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){
1815bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1816bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18176535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18186535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18196535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1820f92edc8eSMatthias Ringwald     log_info("g2 key");
1821f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1822f92edc8eSMatthias Ringwald     log_info("g2 message");
18232bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1824d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1825f92edc8eSMatthias Ringwald }
1826f92edc8eSMatthias Ringwald 
1827b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1828f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
182942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1830f92edc8eSMatthias Ringwald         // responder
1831fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1832f92edc8eSMatthias Ringwald     } else {
1833f92edc8eSMatthias Ringwald         // initiator
1834fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1835f92edc8eSMatthias Ringwald     }
1836f92edc8eSMatthias Ringwald }
1837f92edc8eSMatthias Ringwald 
1838945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18399af0f475SMatthias Ringwald     uint8_t z = 0;
184040c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18419af0f475SMatthias Ringwald         // some form of passkey
18429af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18434ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18449af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18459af0f475SMatthias Ringwald     }
1846fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18479af0f475SMatthias Ringwald }
1848688a08f9SMatthias Ringwald 
1849688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1850a680ba6bSMatthias Ringwald     // OOB
1851a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18524acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18534acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18544acf7b7bSMatthias Ringwald         } else {
18554acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18564acf7b7bSMatthias Ringwald         }
1857a680ba6bSMatthias Ringwald         return;
1858a680ba6bSMatthias Ringwald     }
1859a680ba6bSMatthias Ringwald 
1860688a08f9SMatthias Ringwald     uint8_t z = 0;
186140c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1862688a08f9SMatthias Ringwald         // some form of passkey
1863688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1864688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18654ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1866688a08f9SMatthias Ringwald     }
1867fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1868688a08f9SMatthias Ringwald }
1869688a08f9SMatthias Ringwald 
18700346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1871505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18723cf37b8cSMatthias Ringwald 
18733cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18743cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18753cf37b8cSMatthias Ringwald         return;
18763cf37b8cSMatthias Ringwald     } else {
18773cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18783cf37b8cSMatthias Ringwald     }
1879d1a1f6a4SMatthias Ringwald }
18803cf37b8cSMatthias Ringwald 
1881d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1882f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1883f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1884f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1885f3582630SMatthias Ringwald 
1886d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1887d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1888d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1889d1a1f6a4SMatthias Ringwald     // trigger next step
1890d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1891d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1892d1a1f6a4SMatthias Ringwald     }
189370b44dd4SMatthias Ringwald     sm_trigger_run();
1894dc300847SMatthias Ringwald }
1895dc300847SMatthias Ringwald 
1896dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1897dc300847SMatthias Ringwald     // calculate DHKCheck
1898dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1899dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1900dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19016535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19026535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1903dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1904dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1905dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1906dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1907dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1908dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1909dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1910dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1912dc300847SMatthias Ringwald         // responder
191331f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
191431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1915dc300847SMatthias Ringwald     } else {
1916dc300847SMatthias Ringwald         // initiator
191731f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
191831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1919dc300847SMatthias Ringwald     }
1920dc300847SMatthias Ringwald }
1921dc300847SMatthias Ringwald 
1922019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1923019005a0SMatthias Ringwald     // validate E = f6()
1924019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1925019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1926019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19276535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19286535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1929019005a0SMatthias Ringwald 
1930019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1931019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1932019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1933019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1934019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1935019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1936019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1937019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
193842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1939019005a0SMatthias Ringwald         // responder
194031f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1942019005a0SMatthias Ringwald     } else {
1943019005a0SMatthias Ringwald         // initiator
194431f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
194531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1946019005a0SMatthias Ringwald     }
1947019005a0SMatthias Ringwald }
19482bacf595SMatthias Ringwald 
194955c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19502bacf595SMatthias Ringwald 
19512bacf595SMatthias Ringwald //
19522bacf595SMatthias Ringwald // Link Key Conversion Function h6
19532bacf595SMatthias Ringwald //
195457132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19552bacf595SMatthias Ringwald // - W is 128 bits
19562bacf595SMatthias Ringwald // - keyID is 32 bits
19572bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19582bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19592bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19602bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19612bacf595SMatthias Ringwald     log_info("h6 key");
19622bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19632bacf595SMatthias Ringwald     log_info("h6 message");
19642bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1965d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19662bacf595SMatthias Ringwald }
196757132f12SMatthias Ringwald //
196857132f12SMatthias Ringwald // Link Key Conversion Function h7
196957132f12SMatthias Ringwald //
197057132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197157132f12SMatthias Ringwald // - SALT is 128 bits
197257132f12SMatthias Ringwald // - W    is 128 bits
197357132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
197457132f12SMatthias Ringwald 	const uint16_t message_len = 16;
197557132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
197657132f12SMatthias Ringwald 	log_info("h7 key");
197757132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
197857132f12SMatthias Ringwald 	log_info("h7 message");
197957132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198057132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198157132f12SMatthias Ringwald }
19822bacf595SMatthias Ringwald 
1983b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1984b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1985b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1986b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
198757132f12SMatthias Ringwald 
19882bacf595SMatthias Ringwald static void h6_calculate_ilk(sm_connection_t * sm_conn){
1989b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19902bacf595SMatthias Ringwald }
19912bacf595SMatthias Ringwald 
19922bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
19932bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
19942bacf595SMatthias Ringwald }
19952bacf595SMatthias Ringwald 
199657132f12SMatthias Ringwald static void h7_calculate_ilk(sm_connection_t * sm_conn){
199757132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
199857132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
199957132f12SMatthias Ringwald }
20009af0f475SMatthias Ringwald #endif
20019af0f475SMatthias Ringwald 
200255c62cf5SMatthias Ringwald #endif
200355c62cf5SMatthias Ringwald 
2004613da3deSMatthias Ringwald // key management legacy connections:
2005613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2006613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2007613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2008613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2009613da3deSMatthias Ringwald 
2010613da3deSMatthias Ringwald // key management secure connections:
2011613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2012613da3deSMatthias Ringwald 
201342134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20145829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20155829ebe2SMatthias Ringwald     int encryption_key_size;
20165829ebe2SMatthias Ringwald     int authenticated;
20175829ebe2SMatthias Ringwald     int authorized;
20183dc3a67dSMatthias Ringwald     int secure_connection;
20195829ebe2SMatthias Ringwald 
20205829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20215829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20223dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20233dc3a67dSMatthias 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);
20245829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20255829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20265829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20273dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20285829ebe2SMatthias Ringwald }
202942134bc6SMatthias Ringwald #endif
2030bd57ffebSMatthias Ringwald 
203142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
203259066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20336535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
203459066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
203559066796SMatthias Ringwald     // re-establish used key encryption size
203659066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20374ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
203859066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20394ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20403dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20413dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
204259066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
204359066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
204459066796SMatthias Ringwald }
204542134bc6SMatthias Ringwald #endif
204659066796SMatthias Ringwald 
20473deb3ec6SMatthias Ringwald // distributed key generation
2048d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20493deb3ec6SMatthias Ringwald     switch (dkg_state){
20503deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20513deb3ec6SMatthias Ringwald             // already busy?
20523deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2053d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20543deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2055d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2056d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2057d1a1f6a4SMatthias 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);
2058d7f1c72eSMatthias Ringwald                 return true;
20593deb3ec6SMatthias Ringwald             }
20603deb3ec6SMatthias Ringwald             break;
20613deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20623deb3ec6SMatthias Ringwald             // already busy?
20633deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2064d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20653deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2066d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2067d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2068d1a1f6a4SMatthias 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);
2069d7f1c72eSMatthias Ringwald                 return true;
20703deb3ec6SMatthias Ringwald             }
20713deb3ec6SMatthias Ringwald             break;
20723deb3ec6SMatthias Ringwald         default:
20733deb3ec6SMatthias Ringwald             break;
20743deb3ec6SMatthias Ringwald     }
2075d7f1c72eSMatthias Ringwald     return false;
2076d7f1c72eSMatthias Ringwald }
20773deb3ec6SMatthias Ringwald 
20783deb3ec6SMatthias Ringwald // random address updates
2079d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
20803deb3ec6SMatthias Ringwald     switch (rau_state){
2081fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2082fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
20835b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2084d7f1c72eSMatthias Ringwald             return true;
20853deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
20863deb3ec6SMatthias Ringwald             // already busy?
20873deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2088d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2089d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2090d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2091d7f1c72eSMatthias Ringwald                 return true;
20923deb3ec6SMatthias Ringwald             }
20933deb3ec6SMatthias Ringwald             break;
20943deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
20953deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
20963deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
20973deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2098d7f1c72eSMatthias Ringwald             return true;
20993deb3ec6SMatthias Ringwald         default:
21003deb3ec6SMatthias Ringwald             break;
21013deb3ec6SMatthias Ringwald     }
2102d7f1c72eSMatthias Ringwald     return false;
2103d7f1c72eSMatthias Ringwald }
21043deb3ec6SMatthias Ringwald 
21053deb3ec6SMatthias Ringwald // CSRK Lookup
2106d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2107d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2108d7f1c72eSMatthias Ringwald 
21093deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21103deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21113deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2112665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2113665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21143deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21153deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21163deb3ec6SMatthias Ringwald                 // and start lookup
21173deb3ec6SMatthias 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);
21183deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21193deb3ec6SMatthias Ringwald                 break;
21203deb3ec6SMatthias Ringwald             }
21213deb3ec6SMatthias Ringwald         }
21223deb3ec6SMatthias Ringwald     }
21233deb3ec6SMatthias Ringwald 
21243deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21253deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2126665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21273deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2128665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21293deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21303deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21313deb3ec6SMatthias Ringwald         }
21323deb3ec6SMatthias Ringwald     }
21333deb3ec6SMatthias Ringwald 
21343deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21353deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2136092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2137092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2138adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21393deb3ec6SMatthias Ringwald             bd_addr_t addr;
21403deb3ec6SMatthias Ringwald             sm_key_t irk;
21413deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21423deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21433deb3ec6SMatthias Ringwald 
2144adf5eaa9SMatthias Ringwald             // skip unused entries
2145adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2146adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2147adf5eaa9SMatthias Ringwald                 continue;
2148adf5eaa9SMatthias Ringwald             }
2149adf5eaa9SMatthias Ringwald 
21505df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21513deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2152a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21533deb3ec6SMatthias Ringwald                 break;
21543deb3ec6SMatthias Ringwald             }
21553deb3ec6SMatthias Ringwald 
2156a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2157a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21583deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21593deb3ec6SMatthias Ringwald                 continue;
21603deb3ec6SMatthias Ringwald             }
21613deb3ec6SMatthias Ringwald 
21623deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21633deb3ec6SMatthias Ringwald 
21643deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21658314c363SMatthias Ringwald             log_info_key("IRK", irk);
21663deb3ec6SMatthias Ringwald 
21676535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2168d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21693deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2170d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2171d1a1f6a4SMatthias 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);
2172d7f1c72eSMatthias Ringwald             return true;
21733deb3ec6SMatthias Ringwald         }
21743deb3ec6SMatthias Ringwald 
2175092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
21763deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
21773deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
21783deb3ec6SMatthias Ringwald         }
21793deb3ec6SMatthias Ringwald     }
2180d7f1c72eSMatthias Ringwald     return false;
2181d7f1c72eSMatthias Ringwald }
21823deb3ec6SMatthias Ringwald 
2183d7f1c72eSMatthias Ringwald // SC OOB
2184d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2185c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2186c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2187c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2188c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2189c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2190c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2191d7f1c72eSMatthias Ringwald             return true;
2192c59d0c92SMatthias Ringwald         default:
2193c59d0c92SMatthias Ringwald             break;
2194c59d0c92SMatthias Ringwald     }
2195c59d0c92SMatthias Ringwald #endif
2196d7f1c72eSMatthias Ringwald     return false;
2197d7f1c72eSMatthias Ringwald }
2198275aafe8SMatthias Ringwald 
2199687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2200687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2201687a03c8SMatthias Ringwald }
2202687a03c8SMatthias Ringwald 
220341d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2204d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2205d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
220641d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2207e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
220841d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
220941d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
221041d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2211f4935286SMatthias Ringwald 
2212f4935286SMatthias Ringwald             // general
2213f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2214f4935286SMatthias Ringwald                 uint8_t buffer[2];
2215f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2216f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2217f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2218687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2219f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2220f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2221f4935286SMatthias Ringwald                 break;
2222f4935286SMatthias Ringwald             }
2223f4935286SMatthias Ringwald 
222441d32297SMatthias Ringwald             // responder side
222541d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
222641d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
222741d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2228d7f1c72eSMatthias Ringwald                 return true;
22294b8b5afeSMatthias Ringwald 
22304b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22314b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22324b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22334b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2234e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22354b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22364b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2237d7f1c72eSMatthias Ringwald                         return true;
22384b8b5afeSMatthias Ringwald                     default:
22394b8b5afeSMatthias Ringwald                         break;
22404b8b5afeSMatthias Ringwald                 }
22414b8b5afeSMatthias Ringwald                 break;
22424b8b5afeSMatthias Ringwald #endif
224341d32297SMatthias Ringwald             default:
224441d32297SMatthias Ringwald                 break;
224541d32297SMatthias Ringwald         }
224641d32297SMatthias Ringwald     }
2247d7f1c72eSMatthias Ringwald     return false;
2248d7f1c72eSMatthias Ringwald }
22493deb3ec6SMatthias Ringwald 
2250d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22513deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2252d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22533deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22547149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2255665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22563deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22573deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22581979f09cSMatthias Ringwald         bool done = true;
22593deb3ec6SMatthias Ringwald         int err;
226042134bc6SMatthias Ringwald         UNUSED(err);
226134b6528fSMatthias Ringwald 
226234b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
226334b6528fSMatthias Ringwald         // assert ec key is ready
2264505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2265178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2266178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
226734b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
226834b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
226934b6528fSMatthias Ringwald             }
227034b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
227134b6528fSMatthias Ringwald                 continue;
227234b6528fSMatthias Ringwald             }
227334b6528fSMatthias Ringwald         }
227434b6528fSMatthias Ringwald #endif
227534b6528fSMatthias Ringwald 
22763deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
227742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
22783deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
22793deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
228042134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2281549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
228206cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
228387014f74SMatthias Ringwald #endif
228487014f74SMatthias Ringwald #endif
228534c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
22865567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
228734c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2288549ad5d2SMatthias Ringwald #endif
228987014f74SMatthias Ringwald 				// just lock context
229087014f74SMatthias Ringwald 				break;
22913deb3ec6SMatthias Ringwald             default:
22921979f09cSMatthias Ringwald                 done = false;
22933deb3ec6SMatthias Ringwald                 break;
22943deb3ec6SMatthias Ringwald         }
22953deb3ec6SMatthias Ringwald         if (done){
22967149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
22977149bde5SMatthias 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);
22983deb3ec6SMatthias Ringwald         }
22993deb3ec6SMatthias Ringwald     }
2300d7f1c72eSMatthias Ringwald }
2301d7f1c72eSMatthias Ringwald 
2302403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2303403280b9SMatthias Ringwald     int i;
2304403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2305403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2306403280b9SMatthias Ringwald     uint8_t action = 0;
2307403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2308403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2309403280b9SMatthias Ringwald             bool clear_flag = true;
2310403280b9SMatthias Ringwald             switch (i){
2311403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2312403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2313403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2314403280b9SMatthias Ringwald                 default:
2315403280b9SMatthias Ringwald                     break;
2316403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2317403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2318403280b9SMatthias Ringwald                     num_actions--;
2319403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2320403280b9SMatthias Ringwald                     break;
2321403280b9SMatthias Ringwald             }
2322403280b9SMatthias Ringwald             if (clear_flag){
2323403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2324403280b9SMatthias Ringwald             }
2325403280b9SMatthias Ringwald             action = i;
2326403280b9SMatthias Ringwald             break;
2327403280b9SMatthias Ringwald         }
2328403280b9SMatthias Ringwald     }
2329403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2330403280b9SMatthias Ringwald 
2331403280b9SMatthias Ringwald     // send keypress notification
2332403280b9SMatthias Ringwald     uint8_t buffer[2];
2333403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2334403280b9SMatthias Ringwald     buffer[1] = action;
2335687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2336403280b9SMatthias Ringwald 
2337403280b9SMatthias Ringwald     // try
2338403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2339403280b9SMatthias Ringwald }
2340403280b9SMatthias Ringwald 
2341403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2342403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2343403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2344403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2345403280b9SMatthias Ringwald         uint8_t buffer[17];
2346403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2347403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2348687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2349403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2350403280b9SMatthias Ringwald         return;
2351403280b9SMatthias Ringwald     }
2352403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2353403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2354403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2355403280b9SMatthias Ringwald         uint8_t buffer[11];
2356403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2357403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2358403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2359687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2360403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2361403280b9SMatthias Ringwald         return;
2362403280b9SMatthias Ringwald     }
2363403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2364403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2365403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2366403280b9SMatthias Ringwald         uint8_t buffer[17];
2367403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2368403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2369687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2370403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2371403280b9SMatthias Ringwald         return;
2372403280b9SMatthias Ringwald     }
2373403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2374403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2375403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2376403280b9SMatthias Ringwald         bd_addr_t local_address;
2377403280b9SMatthias Ringwald         uint8_t buffer[8];
2378403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2379403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2380403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2381403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2382403280b9SMatthias Ringwald                 // public or static random
2383403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2384403280b9SMatthias Ringwald                 break;
2385403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2386403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2387403280b9SMatthias Ringwald                 // fallback to public
2388403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2389403280b9SMatthias Ringwald                 buffer[1] = 0;
2390403280b9SMatthias Ringwald                 break;
2391403280b9SMatthias Ringwald             default:
2392403280b9SMatthias Ringwald                 btstack_assert(false);
2393403280b9SMatthias Ringwald                 break;
2394403280b9SMatthias Ringwald         }
2395403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2396687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2397403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2398403280b9SMatthias Ringwald         return;
2399403280b9SMatthias Ringwald     }
2400403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2401403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2402403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2403403280b9SMatthias Ringwald 
2404403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2405403280b9SMatthias Ringwald         // hack to reproduce test runs
2406403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2407403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2408403280b9SMatthias Ringwald                     }
2409403280b9SMatthias Ringwald 
2410403280b9SMatthias Ringwald                     // store local CSRK
2411403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2412403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2413403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2414403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2415403280b9SMatthias Ringwald                     }
2416403280b9SMatthias Ringwald #endif
2417403280b9SMatthias Ringwald 
2418403280b9SMatthias Ringwald         uint8_t buffer[17];
2419403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2420403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2421687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2422403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2423403280b9SMatthias Ringwald         return;
2424403280b9SMatthias Ringwald     }
2425403280b9SMatthias Ringwald     btstack_assert(false);
2426403280b9SMatthias Ringwald }
2427403280b9SMatthias Ringwald 
2428bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2429bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2430bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2431bbd73538SMatthias Ringwald     // - use secure connections
2432bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2433bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2434bbd73538SMatthias 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;
2435bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2436bbd73538SMatthias Ringwald     // - need identity address / public addr
2437bbd73538SMatthias 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);
2438bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2439bbd73538SMatthias 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)
2440bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2441bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2442bbd73538SMatthias 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.
2443bbd73538SMatthias Ringwald     uint8_t link_key[16];
2444bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2445bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2446bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2447bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2448bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2449bbd73538SMatthias Ringwald         return false;
2450bbd73538SMatthias Ringwald     }
2451bbd73538SMatthias Ringwald     // get started (all of the above are true)
2452bbd73538SMatthias Ringwald     return true;
2453bbd73538SMatthias Ringwald #else
2454bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2455bbd73538SMatthias Ringwald 	return false;
2456bbd73538SMatthias Ringwald #endif
2457bbd73538SMatthias Ringwald }
2458bbd73538SMatthias Ringwald 
24596f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24606f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24616f7422f1SMatthias 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;
24626f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24636f7422f1SMatthias Ringwald     } else {
24646f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24656f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24666f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24676f7422f1SMatthias Ringwald     }
24686f7422f1SMatthias Ringwald }
24696f7422f1SMatthias Ringwald 
2470af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2471af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2472af7ef9d1SMatthias 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;
2473af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2474af7ef9d1SMatthias Ringwald     } else {
2475af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2476af7ef9d1SMatthias Ringwald     }
2477af7ef9d1SMatthias Ringwald }
2478af7ef9d1SMatthias Ringwald 
2479d7f1c72eSMatthias Ringwald static void sm_run(void){
2480d7f1c72eSMatthias Ringwald 
2481d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2482d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2483d7f1c72eSMatthias Ringwald 
2484d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2485d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2486d7f1c72eSMatthias Ringwald 
2487d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2488d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2489d7f1c72eSMatthias Ringwald 
2490d7f1c72eSMatthias Ringwald     bool done;
2491d7f1c72eSMatthias Ringwald 
2492d7f1c72eSMatthias Ringwald     //
2493d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2494d7f1c72eSMatthias Ringwald     //
2495d7f1c72eSMatthias Ringwald 
2496d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2497d7f1c72eSMatthias Ringwald     if (done) return;
2498d7f1c72eSMatthias Ringwald 
2499d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2500d7f1c72eSMatthias Ringwald     if (done) return;
2501d7f1c72eSMatthias Ringwald 
2502d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2503d7f1c72eSMatthias Ringwald     if (done) return;
2504d7f1c72eSMatthias Ringwald 
2505d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2506d7f1c72eSMatthias Ringwald     if (done) return;
2507d7f1c72eSMatthias Ringwald 
2508d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2509d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2510d7f1c72eSMatthias Ringwald 
2511d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2512d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2513d7f1c72eSMatthias Ringwald     if (done) return;
2514d7f1c72eSMatthias Ringwald 
2515d7f1c72eSMatthias Ringwald     //
2516d7f1c72eSMatthias Ringwald     // active connection handling
2517d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2518d7f1c72eSMatthias Ringwald 
2519d7f1c72eSMatthias Ringwald     while (true) {
2520d7f1c72eSMatthias Ringwald 
2521d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2522d7f1c72eSMatthias Ringwald 
2523d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25243deb3ec6SMatthias Ringwald 
25253deb3ec6SMatthias Ringwald         //
25263deb3ec6SMatthias Ringwald         // active connection handling
25273deb3ec6SMatthias Ringwald         //
25283deb3ec6SMatthias Ringwald 
25293cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25303cf37b8cSMatthias Ringwald         if (!connection) {
25313cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25323cf37b8cSMatthias Ringwald             return;
25333cf37b8cSMatthias Ringwald         }
25343cf37b8cSMatthias Ringwald 
25353deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25367149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25377149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25387149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2539b170b20fSMatthias Ringwald             return;
2540b170b20fSMatthias Ringwald         }
25413deb3ec6SMatthias Ringwald 
25423d7fe1e9SMatthias Ringwald         // send keypress notifications
2543dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2544403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2545d7471931SMatthias Ringwald             return;
25463d7fe1e9SMatthias Ringwald         }
25473d7fe1e9SMatthias Ringwald 
25483deb3ec6SMatthias Ringwald         int key_distribution_flags;
254942134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2550b6afa23eSMatthias Ringwald 		int err;
2551b6afa23eSMatthias Ringwald 		UNUSED(err);
25529b75de03SMatthias Ringwald         bool have_ltk;
25539b75de03SMatthias Ringwald         uint8_t ltk[16];
25543deb3ec6SMatthias Ringwald 
25553deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2556dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2557dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2558dd4a08fbSMatthias Ringwald         }
25593deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25603deb3ec6SMatthias Ringwald 
2561f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2562aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2563aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2564aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2565aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2566aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2567aec94140SMatthias Ringwald                 break;
2568688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2569688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2570688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2571688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2572688a08f9SMatthias Ringwald                 break;
2573dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2574dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2575dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2576dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2577dc300847SMatthias Ringwald                 break;
2578019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2579b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2580019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
25810346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
25820346c37cSMatthias Ringwald                 break;
25830346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2584b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25850346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
25860346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
25870346c37cSMatthias Ringwald                 break;
25880346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2589b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25900346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
25910346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
25920346c37cSMatthias Ringwald                 break;
25930346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2594b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25950346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
25960346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2597019005a0SMatthias Ringwald                 break;
2598bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2599b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2600bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2601b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2602bd57ffebSMatthias Ringwald                 break;
26036857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
260457132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
26052bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
260657132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
26072bacf595SMatthias Ringwald                 h6_calculate_ilk(connection);
26082bacf595SMatthias Ringwald                 break;
260957132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
26102bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
261157132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
26122bacf595SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
26132bacf595SMatthias Ringwald                 break;
261457132f12SMatthias Ringwald 			case SM_SC_W2_CALCULATE_ILK_USING_H7:
261557132f12SMatthias Ringwald 				if (!sm_cmac_ready()) break;
261657132f12SMatthias Ringwald 				connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
261757132f12SMatthias Ringwald 				h7_calculate_ilk(connection);
261857132f12SMatthias Ringwald 				break;
2619aec94140SMatthias Ringwald #endif
2620a756d52bSMatthias Ringwald #endif
262141d32297SMatthias Ringwald 
262242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26233deb3ec6SMatthias Ringwald             // initiator side
2624f32b7a88SMatthias Ringwald 
26255567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2626f32b7a88SMatthias Ringwald 				sm_reset_setup();
2627f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2628daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2629f32b7a88SMatthias Ringwald 
26303deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26319c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26325567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26333deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2634c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2635c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26363deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26373deb3ec6SMatthias Ringwald                 return;
26383deb3ec6SMatthias Ringwald             }
26393deb3ec6SMatthias Ringwald 
2640b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2641b26f445fSMatthias Ringwald 				sm_reset_setup();
2642b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2643b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2644d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2645b26f445fSMatthias Ringwald 
26461ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26473deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2648687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26493deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26503deb3ec6SMatthias Ringwald                 break;
265142134bc6SMatthias Ringwald #endif
26523deb3ec6SMatthias Ringwald 
265327c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
265441d32297SMatthias Ringwald 
2655c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26561979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26571979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
265827c32905SMatthias Ringwald                 uint8_t buffer[65];
265927c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
266027c32905SMatthias Ringwald                 //
2661fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2662fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2663e53be891SMatthias Ringwald 
2664349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2665349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2666349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2667349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2668349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2669349d0adbSMatthias Ringwald                 }
2670349d0adbSMatthias Ringwald #endif
2671349d0adbSMatthias Ringwald 
267245a61d50SMatthias Ringwald                 // stk generation method
267345a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
267445a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
267545a61d50SMatthias Ringwald                     case JUST_WORKS:
267647fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
267742134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
267807036a04SMatthias Ringwald                             // responder
26791979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2680b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
268127c32905SMatthias Ringwald                         } else {
268207036a04SMatthias Ringwald                             // initiator
2683c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
268427c32905SMatthias Ringwald                         }
268545a61d50SMatthias Ringwald                         break;
268645a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
268745a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
268847fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
268907036a04SMatthias Ringwald                         // use random TK for display
26906535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
26916535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
269245a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
269307036a04SMatthias Ringwald 
269442134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269545a61d50SMatthias Ringwald                             // responder
2696c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
269745a61d50SMatthias Ringwald                         } else {
269845a61d50SMatthias Ringwald                             // initiator
2699c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270045a61d50SMatthias Ringwald                         }
27011979f09cSMatthias Ringwald                         trigger_user_response = true;
270245a61d50SMatthias Ringwald                         break;
270345a61d50SMatthias Ringwald                     case OOB:
270465a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
270565a9a04eSMatthias Ringwald                             // responder
270665a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
270765a9a04eSMatthias Ringwald                         } else {
270865a9a04eSMatthias Ringwald                             // initiator
270965a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271065a9a04eSMatthias Ringwald                         }
271145a61d50SMatthias Ringwald                         break;
27127bbeb3adSMilanka Ringwald                     default:
27137bbeb3adSMilanka Ringwald                         btstack_assert(false);
27147bbeb3adSMilanka Ringwald                         break;
271545a61d50SMatthias Ringwald                 }
271645a61d50SMatthias Ringwald 
2717687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
271827c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2719644c6a1dSMatthias Ringwald 
2720b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2721644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2722644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2723644c6a1dSMatthias Ringwald                 }
2724b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2725b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2726b90c4e75SMatthias Ringwald                 }
272727c32905SMatthias Ringwald                 break;
272827c32905SMatthias Ringwald             }
2729c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2730e53be891SMatthias Ringwald                 uint8_t buffer[17];
2731e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27329af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
273342134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2734c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2735e53be891SMatthias Ringwald                 } else {
2736c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2737e53be891SMatthias Ringwald                 }
2738687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2739e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2740e53be891SMatthias Ringwald                 break;
2741e53be891SMatthias Ringwald             }
2742c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2743e53be891SMatthias Ringwald                 uint8_t buffer[17];
2744e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2745e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27469d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27474ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
274840c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
274942134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
275045a61d50SMatthias Ringwald                         // responder
2751c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
275245a61d50SMatthias Ringwald                     } else {
275345a61d50SMatthias Ringwald                         // initiator
2754c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
275545a61d50SMatthias Ringwald                     }
275645a61d50SMatthias Ringwald                 } else {
275740c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
275842134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2759e53be891SMatthias Ringwald                         // responder
276047fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
276140c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2762901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27632886623dSMatthias Ringwald                         } else {
276440c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27652886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2766446a8c36SMatthias Ringwald                         }
2767e53be891SMatthias Ringwald                     } else {
2768136d331aSMatthias Ringwald                         // initiator
2769c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2770e53be891SMatthias Ringwald                     }
277145a61d50SMatthias Ringwald                 }
2772687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2773e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2774e53be891SMatthias Ringwald                 break;
2775e53be891SMatthias Ringwald             }
2776c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2777e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2778e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2779e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2780dc300847SMatthias Ringwald 
278142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2782c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2783e53be891SMatthias Ringwald                 } else {
2784c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2785e53be891SMatthias Ringwald                 }
2786e083ca23SMatthias Ringwald 
2787687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2788e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2789e53be891SMatthias Ringwald                 break;
2790e53be891SMatthias Ringwald             }
2791e53be891SMatthias Ringwald 
2792e53be891SMatthias Ringwald #endif
279342134bc6SMatthias Ringwald 
279442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2795dd12a62bSMatthias Ringwald 
279687014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
279787014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
279887014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2799687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2800c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
280187014f74SMatthias Ringwald 				break;
280287014f74SMatthias Ringwald 			}
280387014f74SMatthias Ringwald 
280438196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
280538196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
280638196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
280738196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
280838196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
280938196718SMatthias Ringwald 						// start using context by loading security info
281038196718SMatthias Ringwald 						sm_reset_setup();
281138196718SMatthias Ringwald 						sm_load_security_info(connection);
281238196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
281338196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
281438196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
281542646f38SMatthias Ringwald                             sm_reencryption_started(connection);
281638196718SMatthias Ringwald                             sm_trigger_run();
281738196718SMatthias Ringwald 							break;
281838196718SMatthias Ringwald 						}
281938196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
282038196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
282138196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
282238196718SMatthias Ringwald 						return;
282338196718SMatthias Ringwald 					default:
282438196718SMatthias Ringwald 						// just wait until IRK lookup is completed
282538196718SMatthias Ringwald 						break;
282638196718SMatthias Ringwald 				}
282738196718SMatthias Ringwald 				break;
282838196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
282938196718SMatthias Ringwald 
2830b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2831b6afa23eSMatthias Ringwald                 sm_reset_setup();
28329b75de03SMatthias Ringwald 
28339b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28349b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28359b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28369b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28379b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28389b75de03SMatthias Ringwald                         if (have_ltk){
28399b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
284019a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28419b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28429b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28439b75de03SMatthias Ringwald                         }
28449b75de03SMatthias Ringwald                         break;
28459b75de03SMatthias Ringwald                     default:
28469b75de03SMatthias Ringwald                         break;
28479b75de03SMatthias Ringwald                 }
28489b75de03SMatthias Ringwald 
2849b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2850d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
285139543d07SMatthias Ringwald 
2852b6afa23eSMatthias Ringwald 				// recover pairing request
2853b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2854b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2855b6afa23eSMatthias Ringwald 
2856b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2857b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2858b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2859b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2860b6afa23eSMatthias Ringwald                     }
2861b6afa23eSMatthias Ringwald #endif
28629305033eSMatthias Ringwald 				if (err != 0){
2863f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2864b6afa23eSMatthias Ringwald 					sm_trigger_run();
2865b6afa23eSMatthias Ringwald 					break;
2866b6afa23eSMatthias Ringwald 				}
2867b6afa23eSMatthias Ringwald 
2868b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2869b6afa23eSMatthias Ringwald 
2870b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2871b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2872b6afa23eSMatthias 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);
2873b6afa23eSMatthias Ringwald 					break;
2874b6afa23eSMatthias Ringwald 				}
2875b6afa23eSMatthias Ringwald 
2876b6afa23eSMatthias Ringwald 				/* fall through */
2877b6afa23eSMatthias Ringwald 
28783deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28791ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2880f55bd529SMatthias Ringwald 
2881f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28823deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28831ad129beSMatthias Ringwald 
2884f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2885f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2886f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2887f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2888f55bd529SMatthias Ringwald                 }
2889f55bd529SMatthias Ringwald #endif
2890f55bd529SMatthias Ringwald                 // setup in response
2891f55bd529SMatthias 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);
2892f55bd529SMatthias 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);
2893f55bd529SMatthias Ringwald 
2894f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
2895*9a90d41aSMatthias 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));
2896f55bd529SMatthias Ringwald 
289727c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2898c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
28990b8af2a5SMatthias Ringwald                 } else {
29000b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
290127c32905SMatthias Ringwald                 }
29020b8af2a5SMatthias Ringwald 
2903687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29043deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2905446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2906c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29073deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2908446a8c36SMatthias Ringwald                 }
29093deb3ec6SMatthias Ringwald                 return;
291042134bc6SMatthias Ringwald #endif
29113deb3ec6SMatthias Ringwald 
29123deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29133deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29143deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29159c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
291642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29173deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29183deb3ec6SMatthias Ringwald                 } else {
29193deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29203deb3ec6SMatthias Ringwald                 }
2921687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29223deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29233deb3ec6SMatthias Ringwald                 break;
29243deb3ec6SMatthias Ringwald             }
29253deb3ec6SMatthias Ringwald 
2926d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29273deb3ec6SMatthias Ringwald                 // already busy?
29283deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2929d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2930d1a1f6a4SMatthias 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);
2931d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2932d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2933f3582630SMatthias 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);
29343deb3ec6SMatthias Ringwald                 break;
29353deb3ec6SMatthias Ringwald 
29363deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29373deb3ec6SMatthias Ringwald                 // already busy?
29383deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29393deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2940d1a1f6a4SMatthias 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);
2941d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2942d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2943f3582630SMatthias 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);
29443deb3ec6SMatthias Ringwald                 break;
2945d1a1f6a4SMatthias Ringwald 
29463deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29473deb3ec6SMatthias Ringwald                 // already busy?
29483deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29493deb3ec6SMatthias Ringwald                 // calculate STK
295042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2951d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29523deb3ec6SMatthias Ringwald                 } else {
2953d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29543deb3ec6SMatthias Ringwald                 }
2955d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2956d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2957f3582630SMatthias 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);
29583deb3ec6SMatthias Ringwald                 break;
2959d1a1f6a4SMatthias Ringwald 
29603deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29613deb3ec6SMatthias Ringwald                 // already busy?
29623deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29633deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29649ad0dd7cSMatthias Ringwald 
29659ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29669ad0dd7cSMatthias Ringwald                 // r' = padding || r
29679ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29689ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29696535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29709ad0dd7cSMatthias Ringwald 
29713deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2972d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2973d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2974f3582630SMatthias 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);
2975d1a1f6a4SMatthias Ringwald                 break;
2976d1a1f6a4SMatthias Ringwald 
29773deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29783deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29793deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29809c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
298142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29823deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29833deb3ec6SMatthias Ringwald                 } else {
29843deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
29853deb3ec6SMatthias Ringwald                 }
2986687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29873deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29883deb3ec6SMatthias Ringwald                 return;
29893deb3ec6SMatthias Ringwald             }
299042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
29913deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
29923deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
29939c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
29943deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
29953deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
29963deb3ec6SMatthias Ringwald                 return;
29973deb3ec6SMatthias Ringwald             }
2998d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
29993deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30009c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30015567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30023deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30033deb3ec6SMatthias Ringwald                 return;
30043deb3ec6SMatthias Ringwald             }
3005dd12a62bSMatthias Ringwald 
3006dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30073deb3ec6SMatthias Ringwald                 // already busy?
30083deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30093deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3010c61cfe5aSMatthias Ringwald 
3011dd12a62bSMatthias Ringwald 				sm_reset_setup();
3012dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3013dd12a62bSMatthias Ringwald 
301442646f38SMatthias Ringwald 				sm_reencryption_started(connection);
301542646f38SMatthias Ringwald 
3016c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3017c61cfe5aSMatthias Ringwald                 // r' = padding || r
3018c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3019c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30206535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3021c61cfe5aSMatthias Ringwald 
30223deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3023d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3024d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3025f3582630SMatthias 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);
30263deb3ec6SMatthias Ringwald                 return;
302742134bc6SMatthias Ringwald #endif
302842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
302942134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
303042134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
303142134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
303242134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
303342134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
303442134bc6SMatthias Ringwald                 return;
303542134bc6SMatthias Ringwald             }
303642134bc6SMatthias Ringwald #endif
30373deb3ec6SMatthias Ringwald 
30383deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3039403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3040403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30413deb3ec6SMatthias Ringwald                     return;
30423deb3ec6SMatthias Ringwald                 }
30433deb3ec6SMatthias Ringwald 
30443deb3ec6SMatthias Ringwald                 // keys are sent
304542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30463deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
30473deb3ec6SMatthias Ringwald                     if (sm_key_distribution_all_received(connection)){
30483deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3049f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3050f5020412SMatthias Ringwald                         // start CTKD right away
3051f5020412SMatthias Ringwald                         continue;
30523deb3ec6SMatthias Ringwald                     } else {
30533deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30543deb3ec6SMatthias Ringwald                     }
30553deb3ec6SMatthias Ringwald                 } else {
30561dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30573deb3ec6SMatthias Ringwald                 }
30583deb3ec6SMatthias Ringwald                 break;
30593deb3ec6SMatthias Ringwald 
30603deb3ec6SMatthias Ringwald             default:
30613deb3ec6SMatthias Ringwald                 break;
30623deb3ec6SMatthias Ringwald         }
30633deb3ec6SMatthias Ringwald 
30643deb3ec6SMatthias Ringwald         // check again if active connection was released
30657149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
30663deb3ec6SMatthias Ringwald     }
30673deb3ec6SMatthias Ringwald }
30683deb3ec6SMatthias Ringwald 
3069d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3070d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3071f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
307204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
307304678764SMatthias Ringwald 
3074f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3075f3582630SMatthias Ringwald     if (connection == NULL) return;
3076f3582630SMatthias Ringwald 
3077d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
307804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3079f3582630SMatthias 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);
3080d1a1f6a4SMatthias Ringwald }
30813deb3ec6SMatthias Ringwald 
3082d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3083f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
308404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
308504678764SMatthias Ringwald 
3086f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3087f3582630SMatthias Ringwald     if (connection == NULL) return;
3088f3582630SMatthias Ringwald 
30898314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
30903deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
309170b44dd4SMatthias Ringwald     sm_trigger_run();
3092d1a1f6a4SMatthias Ringwald }
3093d1a1f6a4SMatthias Ringwald 
3094d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3095d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3096f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
309704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
309804678764SMatthias Ringwald 
3099f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3100f3582630SMatthias Ringwald     if (connection == NULL) return;
3101f3582630SMatthias Ringwald 
3102d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
310304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3104f3582630SMatthias 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);
3105d1a1f6a4SMatthias Ringwald }
3106d1a1f6a4SMatthias Ringwald 
3107d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3108f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
310904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
311004678764SMatthias Ringwald 
3111f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3112f3582630SMatthias Ringwald     if (connection == NULL) return;
3113f3582630SMatthias Ringwald 
3114d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3115d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3116f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
311770b44dd4SMatthias Ringwald         sm_trigger_run();
31183deb3ec6SMatthias Ringwald         return;
31193deb3ec6SMatthias Ringwald     }
312042134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31213deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
312270b44dd4SMatthias Ringwald         sm_trigger_run();
31233deb3ec6SMatthias Ringwald     } else {
3124d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3125d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3126f3582630SMatthias 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);
31273deb3ec6SMatthias Ringwald     }
31283deb3ec6SMatthias Ringwald }
3129d1a1f6a4SMatthias Ringwald 
3130d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
313104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3132f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
313304678764SMatthias Ringwald 
3134f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3135f3582630SMatthias Ringwald     if (connection == NULL) return;
3136f3582630SMatthias Ringwald 
31373deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
31388314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
313942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31403deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
31413deb3ec6SMatthias Ringwald     } else {
31423deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
31433deb3ec6SMatthias Ringwald     }
314470b44dd4SMatthias Ringwald     sm_trigger_run();
3145d1a1f6a4SMatthias Ringwald }
3146d1a1f6a4SMatthias Ringwald 
3147d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3148d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3149f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
315004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
315104678764SMatthias Ringwald 
3152f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3153f3582630SMatthias Ringwald     if (connection == NULL) return;
3154f3582630SMatthias Ringwald 
3155d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31563deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31573deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
31583deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
31593deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31603deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31613deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3162d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
316304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3164f3582630SMatthias 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);
31653deb3ec6SMatthias Ringwald }
3166d1a1f6a4SMatthias Ringwald 
31672a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3168d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3169d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
317004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3171f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
317204678764SMatthias Ringwald 
3173f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3174f3582630SMatthias Ringwald     if (connection == NULL) return;
3175f3582630SMatthias Ringwald 
3176d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31773deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31783deb3ec6SMatthias Ringwald 
31793deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
31803deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
31813deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31823deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31833deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3184d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
318504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3186f3582630SMatthias Ringwald     btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph4_ltk, (void *)(uintptr_t) connection->sm_handle);
31873deb3ec6SMatthias Ringwald }
31882a526f21SMatthias Ringwald #endif
3189d1a1f6a4SMatthias Ringwald 
3190d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3191d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3192f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
319304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
319404678764SMatthias Ringwald 
3195f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3196f3582630SMatthias Ringwald     if (connection == NULL) return;
3197f3582630SMatthias Ringwald 
31988314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
31993deb3ec6SMatthias Ringwald     // calc CSRK next
3200d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
320104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3202f3582630SMatthias 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);
3203d1a1f6a4SMatthias Ringwald }
3204d1a1f6a4SMatthias Ringwald 
3205d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3206f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
320704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
320804678764SMatthias Ringwald 
3209f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3210f3582630SMatthias Ringwald     if (connection == NULL) return;
3211f3582630SMatthias Ringwald 
3212d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
32138314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
32143deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
32153deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
32163deb3ec6SMatthias Ringwald     } else {
32173deb3ec6SMatthias Ringwald         // no keys to send, just continue
321842134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3219c5a72e35SMatthias Ringwald             if (sm_key_distribution_all_received(connection)){
3220c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3221c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3222c5a72e35SMatthias Ringwald             } else {
32233deb3ec6SMatthias Ringwald                 // slave -> receive master keys
32243deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3225c5a72e35SMatthias Ringwald             }
32263deb3ec6SMatthias Ringwald         } else {
3227af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
32283deb3ec6SMatthias Ringwald         }
32292bacf595SMatthias Ringwald     }
323070b44dd4SMatthias Ringwald     sm_trigger_run();
3231d1a1f6a4SMatthias Ringwald }
3232d1a1f6a4SMatthias Ringwald 
323342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3234d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3235f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323704678764SMatthias Ringwald 
3238f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3239f3582630SMatthias Ringwald     if (connection == NULL) return;
3240f3582630SMatthias Ringwald 
32413deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32428314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3243d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
324470b44dd4SMatthias Ringwald     sm_trigger_run();
3245d1a1f6a4SMatthias Ringwald }
3246d1a1f6a4SMatthias Ringwald #endif
3247d1a1f6a4SMatthias Ringwald 
3248d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3249d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3250d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325104678764SMatthias Ringwald 
3252d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3253d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3254d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3255d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3256d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3257a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
325870b44dd4SMatthias Ringwald         sm_trigger_run();
32593deb3ec6SMatthias Ringwald         return;
32603deb3ec6SMatthias Ringwald     }
3261d1a1f6a4SMatthias Ringwald     // no match, try next
3262d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
326370b44dd4SMatthias Ringwald     sm_trigger_run();
32643deb3ec6SMatthias Ringwald }
32653deb3ec6SMatthias Ringwald 
3266d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3267d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3268d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326904678764SMatthias Ringwald 
3270d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3271d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
327270b44dd4SMatthias Ringwald     sm_trigger_run();
32737df18c15SMatthias Ringwald }
3274d1a1f6a4SMatthias Ringwald 
3275d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3276d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3277d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327804678764SMatthias Ringwald 
3279d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3280d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
328170b44dd4SMatthias Ringwald     sm_trigger_run();
32827df18c15SMatthias Ringwald }
3283d1a1f6a4SMatthias Ringwald 
3284d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3285d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3286d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
328704678764SMatthias Ringwald 
32886535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3289d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
329070b44dd4SMatthias Ringwald     sm_trigger_run();
329151fa0b28SMatthias Ringwald }
32927df18c15SMatthias Ringwald 
3293d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3294d1a1f6a4SMatthias Ringwald     UNUSED(arg);
32953deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
32963deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
32973deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
32983deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
32993deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
33004ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33014ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
33023deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
33033deb3ec6SMatthias Ringwald             break;
33043deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
33053deb3ec6SMatthias Ringwald         default:
33063deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
33074ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33083deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
33093deb3ec6SMatthias Ringwald             break;
33103deb3ec6SMatthias Ringwald     }
331170b44dd4SMatthias Ringwald     sm_trigger_run();
33123deb3ec6SMatthias Ringwald }
33133deb3ec6SMatthias Ringwald 
3314c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
33156ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3316f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3317f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3318f3582630SMatthias Ringwald     if (connection == NULL) return;
3319c59d0c92SMatthias Ringwald 
332065a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
332170b44dd4SMatthias Ringwald     sm_trigger_run();
332265a9a04eSMatthias Ringwald }
3323d1a1f6a4SMatthias Ringwald 
33246ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
33256ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
33266ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
33276ca80073SMatthias Ringwald     if (connection == NULL) return;
33286ca80073SMatthias Ringwald 
3329b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
333070b44dd4SMatthias Ringwald     sm_trigger_run();
3331d1a1f6a4SMatthias Ringwald }
3332f1c1783eSMatthias Ringwald #endif
3333f1c1783eSMatthias Ringwald 
3334d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3335f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3336f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3337f3582630SMatthias Ringwald     if (connection == NULL) return;
3338f3582630SMatthias Ringwald 
3339d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
334070b44dd4SMatthias Ringwald     sm_trigger_run();
3341d1a1f6a4SMatthias Ringwald }
3342d1a1f6a4SMatthias Ringwald 
3343d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3344f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3345f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3346f3582630SMatthias Ringwald     if (connection == NULL) return;
3347f3582630SMatthias Ringwald 
3348caf15bf3SMatthias Ringwald     sm_reset_tk();
3349caf15bf3SMatthias Ringwald     uint32_t tk;
33505ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
33513deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3352d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
33533deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
33544ea43905SMatthias Ringwald         if (tk >= 999999u){
33554ea43905SMatthias Ringwald             tk = tk - 999999u;
33563deb3ec6SMatthias Ringwald         }
3357caf15bf3SMatthias Ringwald     } else {
3358caf15bf3SMatthias Ringwald         // override with pre-defined passkey
33594b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3360caf15bf3SMatthias Ringwald     }
3361f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
336242134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33633deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
33643deb3ec6SMatthias Ringwald     } else {
3365b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3366b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3367b41539d5SMatthias Ringwald         } else {
33683deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
33693deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
33703deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
33713deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3372f3582630SMatthias 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);
33733deb3ec6SMatthias Ringwald             }
33743deb3ec6SMatthias Ringwald         }
3375b41539d5SMatthias Ringwald     }
337670b44dd4SMatthias Ringwald     sm_trigger_run();
33773deb3ec6SMatthias Ringwald }
3378d1a1f6a4SMatthias Ringwald 
3379d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3380f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3381f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3382f3582630SMatthias Ringwald     if (connection == NULL) return;
3383f3582630SMatthias Ringwald 
3384d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3385d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3386d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3387d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
338870b44dd4SMatthias Ringwald     sm_trigger_run();
3389d1a1f6a4SMatthias Ringwald }
3390d1a1f6a4SMatthias Ringwald 
3391d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3392f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3393f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3394f3582630SMatthias Ringwald     if (connection == NULL) return;
3395f3582630SMatthias Ringwald 
3396d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
33973deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
33984ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
33993deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
34004ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
34018b3ffec5SMatthias 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);
34023deb3ec6SMatthias Ringwald }
3403899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3404899e6e02SMatthias Ringwald     // warn about default ER/IR
34051979f09cSMatthias Ringwald     bool warning = false;
3406899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
34071979f09cSMatthias Ringwald         warning = true;
3408899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3409899e6e02SMatthias Ringwald     }
3410899e6e02SMatthias Ringwald     if (sm_er_is_default()){
34111979f09cSMatthias Ringwald         warning = true;
3412899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3413899e6e02SMatthias Ringwald     }
341421045273SMatthias Ringwald     if (warning) {
3415899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3416899e6e02SMatthias Ringwald     }
341721045273SMatthias Ringwald }
3418899e6e02SMatthias Ringwald 
3419899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
34201979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34219305033eSMatthias Ringwald     if (arg != NULL){
3422899e6e02SMatthias Ringwald         // key generated, store in tlv
34234ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3424899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3425e0d13a19SMilanka Ringwald         UNUSED(status);
3426899e6e02SMatthias Ringwald     }
3427899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
34288d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3429841468bbSMatthias Ringwald 
3430841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3431841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3432841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3433841468bbSMatthias Ringwald     }
3434841468bbSMatthias Ringwald 
343570b44dd4SMatthias Ringwald     sm_trigger_run();
3436899e6e02SMatthias Ringwald }
3437899e6e02SMatthias Ringwald 
3438899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
34391979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34409305033eSMatthias Ringwald     if (arg != 0){
3441899e6e02SMatthias Ringwald         // key generated, store in tlv
34424ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3443899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3444e0d13a19SMilanka Ringwald         UNUSED(status);
3445899e6e02SMatthias Ringwald     }
3446899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3447899e6e02SMatthias Ringwald 
3448899e6e02SMatthias Ringwald     // try load ir
34494ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3450899e6e02SMatthias Ringwald     if (key_size == 16){
3451899e6e02SMatthias Ringwald         // ok, let's continue
3452899e6e02SMatthias Ringwald         log_info("IR from TLV");
3453899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3454899e6e02SMatthias Ringwald     } else {
3455899e6e02SMatthias Ringwald         // invalid, generate new random one
34561979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3457899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3458899e6e02SMatthias Ringwald     }
3459899e6e02SMatthias Ringwald }
34603deb3ec6SMatthias Ringwald 
3461f664b5e8SMatthias 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){
3462f664b5e8SMatthias Ringwald 
3463f664b5e8SMatthias Ringwald     // connection info
3464f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3465f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3466f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3467f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3468f664b5e8SMatthias Ringwald 
3469f664b5e8SMatthias Ringwald     // security properties
3470f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3471f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3472f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3473f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3474f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3475f664b5e8SMatthias Ringwald 
3476f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3477f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3478f664b5e8SMatthias Ringwald 
3479f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3480f664b5e8SMatthias Ringwald }
3481f664b5e8SMatthias Ringwald 
3482d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
34833deb3ec6SMatthias Ringwald 
3484cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3485cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
34869ec2630cSMatthias Ringwald 
34873deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3488711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3489fbe050beSMatthias Ringwald     uint8_t           status;
3490f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3491f664b5e8SMatthias Ringwald 
34923deb3ec6SMatthias Ringwald     switch (packet_type) {
34933deb3ec6SMatthias Ringwald 
34943deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
34950e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
34963deb3ec6SMatthias Ringwald 
34973deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
34983deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3499be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
35003deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3501899e6e02SMatthias Ringwald 
3502899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3503899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
35049305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
35054ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3506899e6e02SMatthias Ringwald                             if (key_size == 16){
3507899e6e02SMatthias Ringwald                                 // ok, let's continue
3508899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3509899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3510899e6e02SMatthias Ringwald                             } else {
3511899e6e02SMatthias Ringwald                                 // invalid, generate random one
35121979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3513899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3514899e6e02SMatthias Ringwald                             }
3515899e6e02SMatthias Ringwald                         } else {
3516899e6e02SMatthias Ringwald                             sm_validate_er_ir();
35178d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3518841468bbSMatthias Ringwald 
3519841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3520841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3521841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3522841468bbSMatthias Ringwald                             }
3523899e6e02SMatthias Ringwald                         }
35241bf086daSMatthias Ringwald 
35251bf086daSMatthias Ringwald                         // restart random address updates after power cycle
35261bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
35273deb3ec6SMatthias Ringwald 					}
35283deb3ec6SMatthias Ringwald 					break;
35292d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
35302d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
35312d095694SMatthias Ringwald 			        // ignore if connection failed
35322d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
35333deb3ec6SMatthias Ringwald 
35342d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
35352d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
35362d095694SMatthias Ringwald 			        if (!sm_conn) break;
35372d095694SMatthias Ringwald 
35382d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
35392d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
35402d095694SMatthias Ringwald                                        con_handle,
35412d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3542f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
35432d095694SMatthias Ringwald                                        addr);
35442d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
35452d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
35462d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
35472d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
35482d095694SMatthias Ringwald 			        break;
35492d095694SMatthias Ringwald #endif
35503deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
35513deb3ec6SMatthias Ringwald                     switch (packet[2]) {
35523deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3553f664b5e8SMatthias Ringwald                             // ignore if connection failed
3554f664b5e8SMatthias Ringwald                             if (packet[3]) return;
35553deb3ec6SMatthias Ringwald 
3556711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3557711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35583deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35593deb3ec6SMatthias Ringwald 
3560f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3561f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3562f664b5e8SMatthias Ringwald                                                con_handle,
3563f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3564f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3565f664b5e8SMatthias Ringwald                                                addr);
3566687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3567f664b5e8SMatthias Ringwald 
3568f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3569f664b5e8SMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet)){
3570ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3571ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3572f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3573ba9fc867SMatthias Ringwald                             } else {
3574ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3575ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
35763deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
35773deb3ec6SMatthias Ringwald                             }
35783deb3ec6SMatthias Ringwald                             break;
35793deb3ec6SMatthias Ringwald 
35803deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3581711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3582711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35833deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35843deb3ec6SMatthias Ringwald 
35853deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
35863deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
35873deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
35883deb3ec6SMatthias Ringwald                                 break;
35893deb3ec6SMatthias Ringwald                             }
3590c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3591778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3592778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3593e53be891SMatthias Ringwald                                 break;
3594e53be891SMatthias Ringwald                             }
35953deb3ec6SMatthias Ringwald 
35963deb3ec6SMatthias Ringwald                             // store rand and ediv
35979c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3598f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3599549ad5d2SMatthias Ringwald 
3600549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3601549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
36024ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
36036c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
360406cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3605549ad5d2SMatthias Ringwald                                     break;
3606549ad5d2SMatthias Ringwald                                 }
36076c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
36086c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
36096c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
36106c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
36116c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
36126c39055aSMatthias Ringwald                                         break;
36136c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
36146c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
36156c39055aSMatthias Ringwald                                         break;
36166c39055aSMatthias Ringwald                                     default:
36176c39055aSMatthias Ringwald                                         // wait for irk look doen
36186c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
36196c39055aSMatthias Ringwald                                         break;
36206c39055aSMatthias Ringwald                                 }
36216c39055aSMatthias Ringwald                                 break;
36226c39055aSMatthias Ringwald                             }
3623549ad5d2SMatthias Ringwald 
3624549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
362506cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3626549ad5d2SMatthias Ringwald #else
3627549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3628549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3629549ad5d2SMatthias Ringwald #endif
36303deb3ec6SMatthias Ringwald                             break;
3631804d3e67SMatthias Ringwald 
36323deb3ec6SMatthias Ringwald                         default:
36333deb3ec6SMatthias Ringwald                             break;
36343deb3ec6SMatthias Ringwald                     }
36353deb3ec6SMatthias Ringwald                     break;
36363deb3ec6SMatthias Ringwald 
36373deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
36383b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3639711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36403deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36413deb3ec6SMatthias Ringwald 
36423b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
36433deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
36443deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
36453deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
364603a9359aSMatthias Ringwald 
3647fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3648fbe050beSMatthias Ringwald 
36495567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
365003a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3651fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3652fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
36538d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
36548d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36558d4eef95SMatthias Ringwald                                 } else {
365603a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36578d4eef95SMatthias Ringwald                                 }
3658fbe050beSMatthias Ringwald                             } else {
3659e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3660cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
36613b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3662cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
36633b7fd749SMatthias Ringwald                             }
3664fbe050beSMatthias Ringwald 
3665fbe050beSMatthias Ringwald                             // emit re-encryption complete
366673102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3667fbe050beSMatthias Ringwald 
3668c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3669c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3670c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
36710ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
367203a9359aSMatthias Ringwald                             }
367303a9359aSMatthias Ringwald 
36743deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
36753deb3ec6SMatthias Ringwald                             break;
3676fbe050beSMatthias Ringwald 
36773deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3678fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3679dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
368042134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
36813deb3ec6SMatthias Ringwald                                 // slave
3682bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3683bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3684bbf8db22SMatthias Ringwald                                 } else {
3685f3582630SMatthias 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);
3686bbf8db22SMatthias Ringwald                                 }
36873deb3ec6SMatthias Ringwald                             } else {
36883deb3ec6SMatthias Ringwald                                 // master
36893deb3ec6SMatthias Ringwald                                 if (sm_key_distribution_all_received(sm_conn)){
36903deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
36913deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3692f3582630SMatthias 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);
36933deb3ec6SMatthias Ringwald                                 } else {
36943deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
36953deb3ec6SMatthias Ringwald                                 }
36963deb3ec6SMatthias Ringwald                             }
36973deb3ec6SMatthias Ringwald                             break;
36983deb3ec6SMatthias Ringwald                         default:
36993deb3ec6SMatthias Ringwald                             break;
37003deb3ec6SMatthias Ringwald                     }
37013deb3ec6SMatthias Ringwald                     break;
37023deb3ec6SMatthias Ringwald 
37033deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3704711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3705711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37063deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37073deb3ec6SMatthias Ringwald 
37083deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
37093deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
37103deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
37113deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37125567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
37135567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
37145567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
37155567aa60SMatthias Ringwald                             } else {
37163deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37175567aa60SMatthias Ringwald                             }
37183deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
37193deb3ec6SMatthias Ringwald                             break;
37203deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
372142134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
37223deb3ec6SMatthias Ringwald                                 // slave
3723f3582630SMatthias 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);
37243deb3ec6SMatthias Ringwald                             } else {
37253deb3ec6SMatthias Ringwald                                 // master
37263deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
37273deb3ec6SMatthias Ringwald                             }
37283deb3ec6SMatthias Ringwald                             break;
37293deb3ec6SMatthias Ringwald                         default:
37303deb3ec6SMatthias Ringwald                             break;
37313deb3ec6SMatthias Ringwald                     }
37323deb3ec6SMatthias Ringwald                     break;
37333deb3ec6SMatthias Ringwald 
37343deb3ec6SMatthias Ringwald 
37353deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3736711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3737711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3738711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37393deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37403deb3ec6SMatthias Ringwald 
374103f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
37427f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37437f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
37447f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
37457f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
37467f3f442dSMatthias Ringwald                             break;
37477f3f442dSMatthias Ringwald                         default:
374868a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37490ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
37507f3f442dSMatthias Ringwald                             break;
375103f736b1SMatthias Ringwald                     }
3752accbde80SMatthias Ringwald 
37533deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
37543deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
37553deb3ec6SMatthias Ringwald                     break;
37563deb3ec6SMatthias Ringwald 
37573deb3ec6SMatthias Ringwald 				case HCI_EVENT_COMMAND_COMPLETE:
375833373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
37599091c5f5SMatthias Ringwald                         // set local addr for le device db
376033373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
37610c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
376233373e40SMatthias Ringwald                     }
376365b44ffdSMatthias Ringwald                     break;
376465b44ffdSMatthias Ringwald                 default:
376565b44ffdSMatthias Ringwald                     break;
37663deb3ec6SMatthias Ringwald 			}
376765b44ffdSMatthias Ringwald             break;
376865b44ffdSMatthias Ringwald         default:
376965b44ffdSMatthias Ringwald             break;
37703deb3ec6SMatthias Ringwald 	}
37713deb3ec6SMatthias Ringwald 
37723deb3ec6SMatthias Ringwald     sm_run();
37733deb3ec6SMatthias Ringwald }
37743deb3ec6SMatthias Ringwald 
37753deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
37763deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
37773deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
37783deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
37793deb3ec6SMatthias Ringwald }
37803deb3ec6SMatthias Ringwald 
3781945888f5SMatthias Ringwald 
378231c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3783945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3784945888f5SMatthias Ringwald     switch (method){
3785945888f5SMatthias Ringwald         case JUST_WORKS:
378647fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3787945888f5SMatthias Ringwald             return 1;
3788945888f5SMatthias Ringwald         default:
3789945888f5SMatthias Ringwald             return 0;
3790945888f5SMatthias Ringwald     }
3791945888f5SMatthias Ringwald }
379207036a04SMatthias Ringwald // responder
3793945888f5SMatthias Ringwald 
3794688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3795688a08f9SMatthias Ringwald     switch (method){
3796688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3797688a08f9SMatthias Ringwald             return 1;
3798688a08f9SMatthias Ringwald         default:
3799688a08f9SMatthias Ringwald             return 0;
3800688a08f9SMatthias Ringwald     }
3801688a08f9SMatthias Ringwald }
380240c5d850SMatthias Ringwald 
380340c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
380440c5d850SMatthias Ringwald     switch (method){
380540c5d850SMatthias Ringwald         case PK_RESP_INPUT:
380640c5d850SMatthias Ringwald         case PK_INIT_INPUT:
380747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
380840c5d850SMatthias Ringwald             return 1;
380940c5d850SMatthias Ringwald         default:
381040c5d850SMatthias Ringwald             return 0;
381140c5d850SMatthias Ringwald     }
381240c5d850SMatthias Ringwald }
381340c5d850SMatthias Ringwald 
381431c09488SMatthias Ringwald #endif
3815688a08f9SMatthias Ringwald 
38163deb3ec6SMatthias Ringwald /**
38173deb3ec6SMatthias Ringwald  * @return ok
38183deb3ec6SMatthias Ringwald  */
38193deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
38203deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
38213deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
38223deb3ec6SMatthias Ringwald         case JUST_WORKS:
38234ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
38243deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
38253deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
382647fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
38274ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
38283deb3ec6SMatthias Ringwald         case OOB:
38294ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
383047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
38314ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
38323deb3ec6SMatthias Ringwald         default:
38333deb3ec6SMatthias Ringwald             return 0;
38343deb3ec6SMatthias Ringwald     }
38353deb3ec6SMatthias Ringwald }
38363deb3ec6SMatthias Ringwald 
38378334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
38388334d3d8SMatthias Ringwald 
38394c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
38404c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
38414c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
38424c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
38434c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
38444c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
38454c1d1092SMatthias Ringwald             17, // 0x04 pairing random
38464c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
38474c1d1092SMatthias Ringwald             17, // 0x06 encryption information
38487a2e6387SMatthias Ringwald             11, // 0x07 master identification
38494c1d1092SMatthias Ringwald             17, // 0x08 identification information
38504c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
38514c1d1092SMatthias Ringwald             17, // 0x0a signing information
38524c1d1092SMatthias Ringwald             2,  // 0x0b security request
38534c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
38544c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
38554c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
38564c1d1092SMatthias Ringwald     };
38573deb3ec6SMatthias Ringwald 
3858c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3859b170b20fSMatthias Ringwald         sm_run();
3860b170b20fSMatthias Ringwald     }
3861b170b20fSMatthias Ringwald 
38623deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
38634ea43905SMatthias Ringwald     if (size == 0u) return;
38644c1d1092SMatthias Ringwald 
38654c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
38664c1d1092SMatthias Ringwald 
38674c1d1092SMatthias Ringwald     // validate pdu size
38684c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
38697a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
38703deb3ec6SMatthias Ringwald 
3871711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
38723deb3ec6SMatthias Ringwald     if (!sm_conn) return;
38733deb3ec6SMatthias Ringwald 
38744c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
387568a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
38760ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3877accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
38783deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
38793deb3ec6SMatthias Ringwald         return;
38803deb3ec6SMatthias Ringwald     }
38813deb3ec6SMatthias Ringwald 
38824c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
38833deb3ec6SMatthias Ringwald 
38843deb3ec6SMatthias Ringwald     int err;
388542134bc6SMatthias Ringwald     UNUSED(err);
38863deb3ec6SMatthias Ringwald 
38874c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
38883d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
38893d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
38903d7fe1e9SMatthias Ringwald         buffer[1] = 3;
38913d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
38923d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
38933d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
38943d7fe1e9SMatthias Ringwald         return;
38953d7fe1e9SMatthias Ringwald     }
38963d7fe1e9SMatthias Ringwald 
3897a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
3898212d735eSMatthias Ringwald     int have_ltk;
3899212d735eSMatthias Ringwald     uint8_t ltk[16];
3900a6ca6916SDavid Lechner #endif
3901212d735eSMatthias Ringwald 
39023deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
39033deb3ec6SMatthias Ringwald 
3904c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
39053deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
39063deb3ec6SMatthias Ringwald             return;
39073deb3ec6SMatthias Ringwald 
390842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
390942134bc6SMatthias Ringwald 
39103deb3ec6SMatthias Ringwald         // Initiator
39113deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
39124c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
39133deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39143deb3ec6SMatthias Ringwald                 break;
39153deb3ec6SMatthias Ringwald             }
391634c39fbdSMatthias Ringwald 
39172c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
39182c041b42SMatthias Ringwald             if (sm_sc_only_mode){
39192c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
39202c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
3921f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
39222c041b42SMatthias Ringwald                     break;
39232c041b42SMatthias Ringwald                 }
39242c041b42SMatthias Ringwald             }
39252c041b42SMatthias Ringwald #endif
39262c041b42SMatthias Ringwald 
392734c39fbdSMatthias Ringwald             // IRK complete?
392834c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
392934c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
3930dc8ca372SMatthias Ringwald                     // start pairing
39313deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
39323deb3ec6SMatthias Ringwald                     break;
3933e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
3934e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3935e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
39368549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
39378549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
39388549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
39395567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
3940e061bbd4SMatthias Ringwald                     } else {
3941dc8ca372SMatthias Ringwald                         // start pairing
3942e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3943e061bbd4SMatthias Ringwald                     }
3944e061bbd4SMatthias Ringwald                     break;
394534c39fbdSMatthias Ringwald                 default:
39463deb3ec6SMatthias Ringwald                     // otherwise, store security request
39473deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
39483deb3ec6SMatthias Ringwald                     break;
3949dc8ca372SMatthias Ringwald             }
3950dc8ca372SMatthias Ringwald             break;
39513deb3ec6SMatthias Ringwald 
39523deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3953aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
3954aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3955aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3956aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3957aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
3958aacfafc3SMatthias Ringwald                 break;
3959aacfafc3SMatthias Ringwald             }
3960aacfafc3SMatthias Ringwald 
3961aacfafc3SMatthias Ringwald             // all other pdus are incorrect
39624c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
39633deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39643deb3ec6SMatthias Ringwald                 break;
39653deb3ec6SMatthias Ringwald             }
39660af429c6SMatthias Ringwald 
39673deb3ec6SMatthias Ringwald             // store pairing request
39686535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
39696535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
39703deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
39710af429c6SMatthias Ringwald 
39720af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
39730af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
39740af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
39750af429c6SMatthias Ringwald                 err = test_pairing_failure;
39760af429c6SMatthias Ringwald             }
39770af429c6SMatthias Ringwald #endif
39780af429c6SMatthias Ringwald 
39799305033eSMatthias Ringwald             if (err != 0){
3980f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
39813deb3ec6SMatthias Ringwald                 break;
39823deb3ec6SMatthias Ringwald             }
3983b41539d5SMatthias Ringwald 
3984b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
3985b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3986f3582630SMatthias 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);
3987b41539d5SMatthias Ringwald                 break;
3988b41539d5SMatthias Ringwald             }
3989b41539d5SMatthias Ringwald 
3990136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3991136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
39928cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
39938cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
3994136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3995136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
3996136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3997c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3998136d331aSMatthias Ringwald                     }
39998cba5ca3SMatthias Ringwald                 } else {
4000c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
40018cba5ca3SMatthias Ringwald                 }
4002136d331aSMatthias Ringwald                 break;
4003136d331aSMatthias Ringwald             }
4004136d331aSMatthias Ringwald #endif
40053deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
40063deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
40073deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
40083deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4009f3582630SMatthias 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);
40103deb3ec6SMatthias Ringwald             }
40113deb3ec6SMatthias Ringwald             break;
40123deb3ec6SMatthias Ringwald 
40133deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
40144c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
40153deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40163deb3ec6SMatthias Ringwald                 break;
40173deb3ec6SMatthias Ringwald             }
40183deb3ec6SMatthias Ringwald 
40193deb3ec6SMatthias Ringwald             // store s_confirm
40209c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4021192365feSMatthias Ringwald 
4022aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4023aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4024aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4025aa9b34e5SMatthias Ringwald                 break;
4026aa9b34e5SMatthias Ringwald             }
4027aa9b34e5SMatthias Ringwald 
4028192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4029192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4030192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4031192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4032192365feSMatthias Ringwald             }
4033192365feSMatthias Ringwald #endif
40343deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
40353deb3ec6SMatthias Ringwald             break;
40363deb3ec6SMatthias Ringwald 
40373deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
40384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
40393deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40403deb3ec6SMatthias Ringwald                 break;;
40413deb3ec6SMatthias Ringwald             }
40423deb3ec6SMatthias Ringwald 
40433deb3ec6SMatthias Ringwald             // received random value
40449c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
40453deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
40463deb3ec6SMatthias Ringwald             break;
404742134bc6SMatthias Ringwald #endif
40483deb3ec6SMatthias Ringwald 
404942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
40503deb3ec6SMatthias Ringwald         // Responder
40513deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
40523deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
40533deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
40544c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
40553deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40563deb3ec6SMatthias Ringwald                 break;;
40573deb3ec6SMatthias Ringwald             }
40583deb3ec6SMatthias Ringwald 
40593deb3ec6SMatthias Ringwald             // store pairing request
4060212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4061212d735eSMatthias Ringwald 
4062212d735eSMatthias Ringwald             // check if IRK completed
4063212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4064212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4065212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
40663deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
40673deb3ec6SMatthias Ringwald                     break;
4068212d735eSMatthias Ringwald                 default:
4069212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4070212d735eSMatthias Ringwald                     break;
4071212d735eSMatthias Ringwald             }
4072212d735eSMatthias Ringwald             break;
407342134bc6SMatthias Ringwald #endif
40743deb3ec6SMatthias Ringwald 
407527c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4076c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
40774c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
407827c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
407927c32905SMatthias Ringwald                 break;
408027c32905SMatthias Ringwald             }
4081bccf5e67SMatthias Ringwald 
4082e53be891SMatthias Ringwald             // store public key for DH Key calculation
4083fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4084fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4085bccf5e67SMatthias Ringwald 
408602658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
408702658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
408802658749SMatthias Ringwald                 log_info("Remote PK matches ours");
408902658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
409002658749SMatthias Ringwald                 break;
409102658749SMatthias Ringwald             }
409202658749SMatthias Ringwald 
4093d1a1f6a4SMatthias Ringwald             // validate public key
4094d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
40959305033eSMatthias Ringwald             if (err != 0){
409602658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4097349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4098bccf5e67SMatthias Ringwald                 break;
4099bccf5e67SMatthias Ringwald             }
4100891bb64aSMatthias Ringwald 
4101d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4102f3582630SMatthias 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);
41033cf37b8cSMatthias Ringwald 
410465a9a04eSMatthias Ringwald 
410565a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
410642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4107136d331aSMatthias Ringwald                 // responder
4108c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4109136d331aSMatthias Ringwald             } else {
4110136d331aSMatthias Ringwald                 // initiator
4111a1e31e9cSMatthias Ringwald                 // stk generation method
4112a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4113a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4114a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
411547fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4116c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4117a1e31e9cSMatthias Ringwald                         break;
4118a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
411907036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
412007036a04SMatthias Ringwald                         break;
412107036a04SMatthias Ringwald                     case PK_INIT_INPUT:
412247fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
412307036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
412407036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
412507036a04SMatthias Ringwald                             break;
412607036a04SMatthias Ringwald                         }
4127b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4128a1e31e9cSMatthias Ringwald                         break;
4129a1e31e9cSMatthias Ringwald                     case OOB:
4130d1a1f6a4SMatthias Ringwald                         // generate Nx
41314acf7b7bSMatthias Ringwald                         log_info("Generate Na");
41326ca80073SMatthias 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);
4133a1e31e9cSMatthias Ringwald                         break;
41347bbeb3adSMilanka Ringwald                     default:
41357bbeb3adSMilanka Ringwald                         btstack_assert(false);
41367bbeb3adSMilanka Ringwald                         break;
4137a1e31e9cSMatthias Ringwald                 }
4138136d331aSMatthias Ringwald             }
413927c32905SMatthias Ringwald             break;
4140e53be891SMatthias Ringwald 
4141c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
41424c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
414345a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
414445a61d50SMatthias Ringwald                 break;
414545a61d50SMatthias Ringwald             }
414645a61d50SMatthias Ringwald             // received confirm value
414745a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
414845a61d50SMatthias Ringwald 
4149192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4150192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4151192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4152192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4153192365feSMatthias Ringwald             }
4154192365feSMatthias Ringwald #endif
415542134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
415645a61d50SMatthias Ringwald                 // responder
415707036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
415807036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
415907036a04SMatthias Ringwald                         // still waiting for passkey
416007036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
416107036a04SMatthias Ringwald                         break;
416207036a04SMatthias Ringwald                     }
416307036a04SMatthias Ringwald                 }
4164b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
416545a61d50SMatthias Ringwald             } else {
416645a61d50SMatthias Ringwald                 // initiator
4167945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
41686ca80073SMatthias 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);
4169f1c1783eSMatthias Ringwald                 } else {
4170c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
417145a61d50SMatthias Ringwald                 }
4172f1c1783eSMatthias Ringwald             }
417345a61d50SMatthias Ringwald             break;
417445a61d50SMatthias Ringwald 
4175c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
41764c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4177e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4178136d331aSMatthias Ringwald                 break;
4179e53be891SMatthias Ringwald             }
4180e53be891SMatthias Ringwald 
4181e53be891SMatthias Ringwald             // received random value
4182e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4183e53be891SMatthias Ringwald 
41845a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4185ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4186d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4187d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4188d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
418965a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4190d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4191688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4192ae451ec5SMatthias Ringwald                  break;
41935a293e6eSMatthias Ringwald             }
41946f52a196SMatthias Ringwald 
41954acf7b7bSMatthias Ringwald             // OOB
41964acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
41974acf7b7bSMatthias Ringwald 
41984acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
41994acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
42004acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
42014ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
42024acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
42034acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
42044acf7b7bSMatthias Ringwald                     } else {
42056535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
42064acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
42074acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
42084acf7b7bSMatthias Ringwald                     }
42094acf7b7bSMatthias Ringwald                 }  else {
42104ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
42114acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
42124acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
42134acf7b7bSMatthias Ringwald                     } else {
42146535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
42154acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
42164acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
42174acf7b7bSMatthias Ringwald                     }
42184acf7b7bSMatthias Ringwald                 }
42194acf7b7bSMatthias Ringwald 
4220a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
42214acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4222a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4223a680ba6bSMatthias Ringwald                      break;
4224a680ba6bSMatthias Ringwald                 }
42254acf7b7bSMatthias Ringwald             }
4226a680ba6bSMatthias Ringwald 
4227a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4228688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4229e53be891SMatthias Ringwald             break;
4230e53be891SMatthias Ringwald 
4231901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4232901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
42333cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4234901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4235901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4236901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4237901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4238901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4239901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4240901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4241c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4242901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4243d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
42444c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4245e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4246e53be891SMatthias Ringwald                 break;
4247e53be891SMatthias Ringwald             }
4248e53be891SMatthias Ringwald             // store DHKey Check
4249901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4250e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4251446a8c36SMatthias Ringwald 
4252901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4253901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4254019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4255bd57ffebSMatthias Ringwald             }
4256bd57ffebSMatthias Ringwald             break;
425727c32905SMatthias Ringwald #endif
425827c32905SMatthias Ringwald 
425942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42603deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
42614c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42623deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
426327c32905SMatthias Ringwald                 break;
42643deb3ec6SMatthias Ringwald             }
42653deb3ec6SMatthias Ringwald 
42663deb3ec6SMatthias Ringwald             // received confirm value
42679c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
42683deb3ec6SMatthias Ringwald 
4269192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4270192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4271192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4272192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4273192365feSMatthias Ringwald             }
4274192365feSMatthias Ringwald #endif
42753deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
42763deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
42775611a760SMatthias 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);
42783deb3ec6SMatthias Ringwald             }
42793deb3ec6SMatthias Ringwald 
42803deb3ec6SMatthias Ringwald             // handle user cancel pairing?
42813deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4282f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
42833deb3ec6SMatthias Ringwald                 break;
42843deb3ec6SMatthias Ringwald             }
42853deb3ec6SMatthias Ringwald 
42863deb3ec6SMatthias Ringwald             // wait for user action?
42873deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
42883deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42893deb3ec6SMatthias Ringwald                 break;
42903deb3ec6SMatthias Ringwald             }
42913deb3ec6SMatthias Ringwald 
42923deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4293f3582630SMatthias 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);
42943deb3ec6SMatthias Ringwald             break;
42953deb3ec6SMatthias Ringwald 
42963deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
42974c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42983deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42993deb3ec6SMatthias Ringwald                 break;;
43003deb3ec6SMatthias Ringwald             }
43013deb3ec6SMatthias Ringwald 
43023deb3ec6SMatthias Ringwald             // received random value
43039c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
43043deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
43053deb3ec6SMatthias Ringwald             break;
430642134bc6SMatthias Ringwald #endif
43073deb3ec6SMatthias Ringwald 
43083deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
43094c1d1092SMatthias Ringwald             switch(sm_pdu_code){
43103deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
43113deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
43129c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
43133deb3ec6SMatthias Ringwald                     break;
43143deb3ec6SMatthias Ringwald 
43153deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
43163deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4317f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
43189c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
43193deb3ec6SMatthias Ringwald                     break;
43203deb3ec6SMatthias Ringwald 
43213deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
43223deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
43239c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
43243deb3ec6SMatthias Ringwald                     break;
43253deb3ec6SMatthias Ringwald 
43263deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
43273deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
43283deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4329724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
43303deb3ec6SMatthias Ringwald                     break;
43313deb3ec6SMatthias Ringwald 
43323deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
43333deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
43349c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
43353deb3ec6SMatthias Ringwald                     break;
43363deb3ec6SMatthias Ringwald                 default:
43373deb3ec6SMatthias Ringwald                     // Unexpected PDU
43383deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
43393deb3ec6SMatthias Ringwald                     break;
43403deb3ec6SMatthias Ringwald             }
43413deb3ec6SMatthias Ringwald             // done with key distribution?
43423deb3ec6SMatthias Ringwald             if (sm_key_distribution_all_received(sm_conn)){
43433deb3ec6SMatthias Ringwald 
43443deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
43453deb3ec6SMatthias Ringwald 
434642134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43476f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
43483deb3ec6SMatthias Ringwald                 } else {
4349625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4350625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4351bbf8db22SMatthias Ringwald                     } else {
4352f3582630SMatthias 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);
4353625f00b2SMatthias Ringwald                     }
43543deb3ec6SMatthias Ringwald                 }
43553deb3ec6SMatthias Ringwald             }
43563deb3ec6SMatthias Ringwald             break;
43573deb3ec6SMatthias Ringwald         default:
43583deb3ec6SMatthias Ringwald             // Unexpected PDU
43593deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
43602d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
43613deb3ec6SMatthias Ringwald             break;
43623deb3ec6SMatthias Ringwald     }
43633deb3ec6SMatthias Ringwald 
436470b44dd4SMatthias Ringwald     // try to send next pdu
436570b44dd4SMatthias Ringwald     sm_trigger_run();
43663deb3ec6SMatthias Ringwald }
43673deb3ec6SMatthias Ringwald 
43683deb3ec6SMatthias Ringwald // Security Manager Client API
4369a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
43703deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
43713deb3ec6SMatthias Ringwald }
43723deb3ec6SMatthias Ringwald 
43734acf7b7bSMatthias 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)){
4374a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4375a680ba6bSMatthias Ringwald }
4376a680ba6bSMatthias Ringwald 
437789a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
437889a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
437989a78d34SMatthias Ringwald }
438089a78d34SMatthias Ringwald 
43813deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
43823deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
43833deb3ec6SMatthias Ringwald }
43843deb3ec6SMatthias Ringwald 
43853deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
43863deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
43873deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
43883deb3ec6SMatthias Ringwald }
43893deb3ec6SMatthias Ringwald 
43903deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
439198d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
439298d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
439398d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
439498d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
439598d95509SMatthias Ringwald     }
439698d95509SMatthias Ringwald #endif
43973deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
43983deb3ec6SMatthias Ringwald }
43993deb3ec6SMatthias Ringwald 
44003deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
44013deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
44023deb3ec6SMatthias Ringwald }
44033deb3ec6SMatthias Ringwald 
440442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44053deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
44063deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
44073deb3ec6SMatthias Ringwald }
440842134bc6SMatthias Ringwald #endif
44093deb3ec6SMatthias Ringwald 
44103deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
44116535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
44123deb3ec6SMatthias Ringwald }
44133deb3ec6SMatthias Ringwald 
44143deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
44156535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
44163deb3ec6SMatthias Ringwald }
44173deb3ec6SMatthias Ringwald 
44183deb3ec6SMatthias Ringwald // Testing support only
44193deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
44206535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4421103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4422841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
44233deb3ec6SMatthias Ringwald }
44243deb3ec6SMatthias Ringwald 
44253deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4426841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
44273deb3ec6SMatthias Ringwald }
44283deb3ec6SMatthias Ringwald 
4429d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4430d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4431d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4432d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
443334b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
443470b44dd4SMatthias Ringwald     sm_trigger_run();
4435d1a1f6a4SMatthias Ringwald }
4436674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
443734b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4438674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4439674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4440674e5b4aSMatthias Ringwald }
4441d1a1f6a4SMatthias Ringwald #endif
4442d1a1f6a4SMatthias Ringwald 
4443192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4444192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4445192365feSMatthias Ringwald     test_pairing_failure = reason;
4446192365feSMatthias Ringwald }
4447192365feSMatthias Ringwald #endif
4448192365feSMatthias Ringwald 
44493deb3ec6SMatthias Ringwald void sm_init(void){
44502d2d4d3cSMatthias Ringwald 
44512d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
44522d2d4d3cSMatthias Ringwald 
4453899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4454899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4455899e6e02SMatthias Ringwald 
44563deb3ec6SMatthias Ringwald     // defaults
44573deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
44583deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4459b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4460b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4461b4343428SMatthias Ringwald 
44623deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
44633deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
44643deb3ec6SMatthias Ringwald 
44655ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
44661979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4467caf15bf3SMatthias Ringwald 
4468d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4469d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
44707a766ebfSMatthias Ringwald #endif
44718d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4472fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
44733deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
44743deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
44753deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
44763deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
44773deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
44783deb3ec6SMatthias Ringwald 
44793deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
44807149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
44813deb3ec6SMatthias Ringwald 
4482841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
44833deb3ec6SMatthias Ringwald 
448484c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
448584c0c5c7SMatthias Ringwald 
4486e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4487e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4488e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4489e03e489aSMatthias Ringwald 
4490d1a1f6a4SMatthias Ringwald     //
4491d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4492d1a1f6a4SMatthias Ringwald 
449351bd74d1SMatthias Ringwald     // init le_device_db
449451bd74d1SMatthias Ringwald     le_device_db_init();
449551bd74d1SMatthias Ringwald 
4496b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4497e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
449827c32905SMatthias Ringwald 
449909e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4500674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4501a3aba2f9SMatthias Ringwald #endif
45022d2d4d3cSMatthias Ringwald 
45032d2d4d3cSMatthias Ringwald     sm_initialized = true;
45043deb3ec6SMatthias Ringwald }
45053deb3ec6SMatthias Ringwald 
450615537ea4SMatthias Ringwald void sm_deinit(void){
450715537ea4SMatthias Ringwald     sm_initialized = false;
450815537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
450915537ea4SMatthias Ringwald }
451015537ea4SMatthias Ringwald 
45114b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
45124b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4513caf15bf3SMatthias Ringwald }
4514caf15bf3SMatthias Ringwald 
45156c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
45161979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
45176c39055aSMatthias Ringwald }
45186c39055aSMatthias Ringwald 
4519711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4520711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
45213deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
45223deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
45233deb3ec6SMatthias Ringwald }
45243deb3ec6SMatthias Ringwald 
45256bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4526711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4527711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45283deb3ec6SMatthias Ringwald     if (!sm_conn) return;
45296bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
45306bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
45313deb3ec6SMatthias Ringwald }
45323deb3ec6SMatthias Ringwald 
45333deb3ec6SMatthias Ringwald // request pairing
4534711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4535711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45363deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45373deb3ec6SMatthias Ringwald 
45387af5dcd5SMatthias Ringwald     bool have_ltk;
45397af5dcd5SMatthias Ringwald     uint8_t ltk[16];
45403deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
454142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
454224c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
454324c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
454424c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
45457af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45467af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45477af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
45487af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
45497af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
45507af5dcd5SMatthias Ringwald                         if (have_ltk){
45517af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
455224c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45537af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
45547af5dcd5SMatthias Ringwald                             break;
45557af5dcd5SMatthias Ringwald                         }
45567af5dcd5SMatthias Ringwald                         /* fall through */
45577af5dcd5SMatthias Ringwald 
45587af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45597af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45607af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45617af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
45627af5dcd5SMatthias Ringwald                         break;
45637af5dcd5SMatthias Ringwald                     default:
45647af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
45657af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45667af5dcd5SMatthias Ringwald                         break;
45677af5dcd5SMatthias Ringwald                 }
456824c20dc4SMatthias Ringwald                 break;
456924c20dc4SMatthias Ringwald             default:
457024c20dc4SMatthias Ringwald                 break;
457124c20dc4SMatthias Ringwald         }
45723deb3ec6SMatthias Ringwald     } else {
45733deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4574175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4575175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
45763deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45773deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45783dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4579f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4580f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4581f53ec649SMatthias Ringwald                         if (have_ltk){
4582c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
45835567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4584c245ca32SMatthias Ringwald                             break;
4585f53ec649SMatthias Ringwald                         }
4586cf373d3aSMatthias Ringwald                         /* fall through */
4587c245ca32SMatthias Ringwald 
458834c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45893deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
45903deb3ec6SMatthias Ringwald                         break;
45913deb3ec6SMatthias Ringwald                     default:
4592d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
459309ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45943deb3ec6SMatthias Ringwald                         break;
45953deb3ec6SMatthias Ringwald                 }
4596175b7faaSMatthias Ringwald                 break;
4597cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4598cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4599cb6d7eb0SMatthias Ringwald                 break;
4600175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
460109ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4602175b7faaSMatthias Ringwald                 break;
4603175b7faaSMatthias Ringwald             default:
4604175b7faaSMatthias Ringwald                 break;
46053deb3ec6SMatthias Ringwald         }
46063deb3ec6SMatthias Ringwald     }
460770b44dd4SMatthias Ringwald     sm_trigger_run();
46083deb3ec6SMatthias Ringwald }
46093deb3ec6SMatthias Ringwald 
46103deb3ec6SMatthias Ringwald // called by client app on authorization request
4611711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4612711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46133deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46143deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4615589f5a99SMatthias 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);
46163deb3ec6SMatthias Ringwald }
46173deb3ec6SMatthias Ringwald 
4618711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4619711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46203deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46213deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4622589f5a99SMatthias 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);
46233deb3ec6SMatthias Ringwald }
46243deb3ec6SMatthias Ringwald 
46253deb3ec6SMatthias Ringwald // GAP Bonding API
46263deb3ec6SMatthias Ringwald 
4627711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4628711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46293deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46303deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
46310af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
46320af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
46330af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46340af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
46350af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
46360af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
46370af429c6SMatthias Ringwald #endif
46380af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4639de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4640de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4641de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
464247fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
46430af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4644de2fd182SMatthias Ringwald                     break;
464547fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4646de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4647de2fd182SMatthias Ringwald                     break;
4648de2fd182SMatthias Ringwald                 case JUST_WORKS:
4649de2fd182SMatthias Ringwald                 case OOB:
4650de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4651de2fd182SMatthias Ringwald                     break;
46527bbeb3adSMilanka Ringwald                 default:
46537bbeb3adSMilanka Ringwald                     btstack_assert(false);
46547bbeb3adSMilanka Ringwald                     break;
4655de2fd182SMatthias Ringwald             }
46560af429c6SMatthias Ringwald             break;
46570af429c6SMatthias Ringwald         default:
46580af429c6SMatthias Ringwald             break;
46593deb3ec6SMatthias Ringwald     }
466070b44dd4SMatthias Ringwald     sm_trigger_run();
46613deb3ec6SMatthias Ringwald }
46623deb3ec6SMatthias Ringwald 
4663711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4664711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46653deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46663deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
46673deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4668136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4669c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4670bbf8db22SMatthias Ringwald         } else {
4671f3582630SMatthias 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);
4672136d331aSMatthias Ringwald         }
46733deb3ec6SMatthias Ringwald     }
46740346c37cSMatthias Ringwald 
46750346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4676c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4677dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4678446a8c36SMatthias Ringwald     }
46790346c37cSMatthias Ringwald #endif
46800346c37cSMatthias Ringwald 
468170b44dd4SMatthias Ringwald     sm_trigger_run();
46823deb3ec6SMatthias Ringwald }
46833deb3ec6SMatthias Ringwald 
4684c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4685c8c46d51SMatthias Ringwald     // for now, it's the same
4686c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4687c8c46d51SMatthias Ringwald }
4688c8c46d51SMatthias Ringwald 
4689711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4690711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46913deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46923deb3ec6SMatthias Ringwald     sm_reset_tk();
4693f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
46943deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
46953deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4696f3582630SMatthias 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);
46973deb3ec6SMatthias Ringwald     }
46981c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46996535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
47006535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
470107036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
470207036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
470307036a04SMatthias Ringwald     }
47041c516d8fSMatthias Ringwald #endif
470570b44dd4SMatthias Ringwald     sm_trigger_run();
47063deb3ec6SMatthias Ringwald }
47073deb3ec6SMatthias Ringwald 
47083d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
47093d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47103d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
47113d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4712dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
47134ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4714dd4a08fbSMatthias Ringwald     switch (action){
4715dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4716dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
47174ea43905SMatthias Ringwald             flags |= (1u << action);
4718dd4a08fbSMatthias Ringwald             break;
4719dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4720dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
47214ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4722dd4a08fbSMatthias Ringwald             break;
4723dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
47244ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4725dd4a08fbSMatthias Ringwald                 // erase actions queued
4726dd4a08fbSMatthias Ringwald                 num_actions--;
47274ea43905SMatthias Ringwald                 if (num_actions == 0u){
4728dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47294ea43905SMatthias Ringwald                     flags &= 0x19u;
4730dd4a08fbSMatthias Ringwald                 }
4731dd4a08fbSMatthias Ringwald                 break;
4732dd4a08fbSMatthias Ringwald             }
4733dd4a08fbSMatthias Ringwald             num_actions++;
47344ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4735dd4a08fbSMatthias Ringwald             break;
4736dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
47374ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4738dd4a08fbSMatthias Ringwald                 // enter actions queued
4739dd4a08fbSMatthias Ringwald                 num_actions--;
47404ea43905SMatthias Ringwald                 if (num_actions == 0u){
4741dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47424ea43905SMatthias Ringwald                     flags &= 0x19u;
4743dd4a08fbSMatthias Ringwald                 }
4744dd4a08fbSMatthias Ringwald                 break;
4745dd4a08fbSMatthias Ringwald             }
4746dd4a08fbSMatthias Ringwald             num_actions++;
47474ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4748dd4a08fbSMatthias Ringwald             break;
4749dd4a08fbSMatthias Ringwald         default:
4750dd4a08fbSMatthias Ringwald             break;
4751dd4a08fbSMatthias Ringwald     }
4752dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
475370b44dd4SMatthias Ringwald     sm_trigger_run();
47543d7fe1e9SMatthias Ringwald }
47553d7fe1e9SMatthias Ringwald 
4756c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4757d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
4758d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4759d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
476070b44dd4SMatthias Ringwald     sm_trigger_run();
4761d1a1f6a4SMatthias Ringwald }
4762c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
47638334d3d8SMatthias Ringwald 
47648334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
47658334d3d8SMatthias Ringwald 
4766c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4767c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
4768d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4769d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4770c59d0c92SMatthias Ringwald     return 0;
4771c59d0c92SMatthias Ringwald }
4772c59d0c92SMatthias Ringwald #endif
4773c59d0c92SMatthias Ringwald 
47743deb3ec6SMatthias Ringwald /**
4775ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
4776ba394633SMatthias Ringwald  * @param con_handle
4777ba394633SMatthias Ringwald  * @return irk_lookup_state_t
4778ba394633SMatthias Ringwald  */
4779ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4780ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4781ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
4782ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
4783ba394633SMatthias Ringwald }
4784ba394633SMatthias Ringwald 
4785ba394633SMatthias Ringwald /**
47863deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
47873deb3ec6SMatthias Ringwald  * @param handle
47883deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
47893deb3ec6SMatthias Ringwald  */
4790711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
4791711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47923deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
47933deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
47943deb3ec6SMatthias Ringwald }
47953deb3ec6SMatthias Ringwald 
47968f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
479747ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
479847ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
479947ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
480047ba4de1SMatthias Ringwald             return 0;
480147ba4de1SMatthias Ringwald         default:
48028f57b085SMatthias Ringwald             return 1;
48038f57b085SMatthias Ringwald     }
480447ba4de1SMatthias Ringwald }
4805d70217a2SMatthias Ringwald 
480633373e40SMatthias Ringwald static uint8_t own_address_type(void){
4807b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
4808b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4809b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
4810b95a5a35SMatthias Ringwald         default:
4811b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
4812b95a5a35SMatthias Ringwald     }
481333373e40SMatthias Ringwald }
48148f57b085SMatthias Ringwald 
48153deb3ec6SMatthias Ringwald // GAP LE API
48163deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
48173deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48183deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
4819b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
48208f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48213deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48223deb3ec6SMatthias Ringwald     gap_random_address_trigger();
48233deb3ec6SMatthias Ringwald }
48243deb3ec6SMatthias Ringwald 
48253deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
48263deb3ec6SMatthias Ringwald     return gap_random_adress_type;
48273deb3ec6SMatthias Ringwald }
48283deb3ec6SMatthias Ringwald 
48293deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
48303deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
48318f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48323deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48333deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48343deb3ec6SMatthias Ringwald }
48353deb3ec6SMatthias Ringwald 
4836667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
48378f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
48386535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
48397e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
484070b44dd4SMatthias Ringwald     sm_trigger_run();
48417e252622SMatthias Ringwald }
48427e252622SMatthias Ringwald 
4843d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48443deb3ec6SMatthias Ringwald /*
48453deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
48463deb3ec6SMatthias Ringwald  * @param adv_int_min
48473deb3ec6SMatthias Ringwald  * @param adv_int_max
48483deb3ec6SMatthias Ringwald  * @param adv_type
48493deb3ec6SMatthias Ringwald  * @param direct_address_type
48503deb3ec6SMatthias Ringwald  * @param direct_address
48513deb3ec6SMatthias Ringwald  * @param channel_map
48523deb3ec6SMatthias Ringwald  * @param filter_policy
48533deb3ec6SMatthias Ringwald  *
48543deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
48553deb3ec6SMatthias Ringwald  */
48563deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
48573deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4858b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
48593deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
48603deb3ec6SMatthias Ringwald }
4861d70217a2SMatthias Ringwald #endif
4862dcd6c9b5SMatthias Ringwald 
4863dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4864dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4865dcd6c9b5SMatthias Ringwald      // wrong connection
4866dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
4867dcd6c9b5SMatthias Ringwald     // already encrypted
4868dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
4869dcd6c9b5SMatthias Ringwald     // irk status?
4870dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
4871dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
4872dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
4873dcd6c9b5SMatthias Ringwald             return 0;
4874dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
4875dcd6c9b5SMatthias Ringwald             break;
4876dcd6c9b5SMatthias Ringwald         default:
4877dcd6c9b5SMatthias Ringwald             // IR Lookup pending
4878dcd6c9b5SMatthias Ringwald             return 1;
4879dcd6c9b5SMatthias Ringwald     }
4880f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
4881f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
4882b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
4883b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
4884b15d5ceaSMatthias Ringwald     } else {
4885dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4886dcd6c9b5SMatthias Ringwald     }
4887b15d5ceaSMatthias Ringwald }
48883cdbe9dbSMatthias Ringwald 
48893cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
48903cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
48913cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
48923cdbe9dbSMatthias Ringwald #else
48933cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
48943cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
48953cdbe9dbSMatthias Ringwald #endif
48963cdbe9dbSMatthias Ringwald }
4897052bbdc5SMatthias Ringwald 
4898052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
4899052bbdc5SMatthias Ringwald     return sm_persistent_irk;
4900052bbdc5SMatthias Ringwald }
49014f384501SMatthias Ringwald 
49024f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
49034f384501SMatthias Ringwald     uint16_t i;
49044f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
49054f384501SMatthias Ringwald         bd_addr_t entry_address;
49064f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
49074f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
49084f384501SMatthias Ringwald         // skip unused entries
49094f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
49104f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
49114f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
49124f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
49134f384501SMatthias Ringwald #endif
49144f384501SMatthias Ringwald             le_device_db_remove(i);
49154f384501SMatthias Ringwald             break;
49164f384501SMatthias Ringwald         }
49174f384501SMatthias Ringwald     }
49184f384501SMatthias Ringwald }
4919