xref: /btstack/src/ble/sm.c (revision f72f7944f5bd2fa080b337737fa30c2685f34cdb)
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;
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3123deb3ec6SMatthias Ringwald 
3133deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3143deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3153deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
316a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
31727c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3183deb3ec6SMatthias Ringwald 
3193deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3203deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3213deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3233deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3263deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3273deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3283deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3293deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3303deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3313deb3ec6SMatthias Ringwald 
33268437d83SMatthias Ringwald     uint8_t   sm_state_vars;
333e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
334fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
335446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
336446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
337d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
338e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
339e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
340446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
341446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3422bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
343a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3447df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
345e53be891SMatthias Ringwald #endif
34627c32905SMatthias Ringwald 
3473deb3ec6SMatthias Ringwald     // Phase 3
3483deb3ec6SMatthias Ringwald 
3493deb3ec6SMatthias Ringwald     // key distribution, we generate
3503deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3513deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3523deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3533deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3543deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3553deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3563deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3573deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3583deb3ec6SMatthias Ringwald 
3593deb3ec6SMatthias Ringwald     // key distribution, received from peer
3603deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3613deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3623deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3633deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3643deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3653deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3663deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3673deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3683deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
369715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
370715a43d1SMatthias Ringwald     int       sm_le_device_index;
371715a43d1SMatthias Ringwald #endif
3723deb3ec6SMatthias Ringwald } sm_setup_context_t;
3733deb3ec6SMatthias Ringwald 
3743deb3ec6SMatthias Ringwald //
3753deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3763deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3773deb3ec6SMatthias Ringwald 
3783deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3797149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3803deb3ec6SMatthias Ringwald 
3813deb3ec6SMatthias Ringwald // @returns 1 if oob data is available
3823deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3833deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3844acf7b7bSMatthias 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);
3853deb3ec6SMatthias Ringwald 
3863deb3ec6SMatthias Ringwald static void sm_run(void);
387711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
388711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
3893deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3903deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
391d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
392d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
393d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
394d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
395d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
396d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
397d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
398d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4012a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4042a526f21SMatthias Ringwald #endif
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
409d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4106d80b495SMatthias 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));
41134b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4126ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4136ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4142a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
415d1a1f6a4SMatthias Ringwald #endif
4160ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4173deb3ec6SMatthias Ringwald 
4183deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4193deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4203deb3ec6SMatthias Ringwald }
4213deb3ec6SMatthias Ringwald 
4221fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4231fbd72c5SMatthias Ringwald //     return packet[0];
4241fbd72c5SMatthias Ringwald // }
4251fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4261fbd72c5SMatthias Ringwald     return packet[1];
4271fbd72c5SMatthias Ringwald }
4281fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4291fbd72c5SMatthias Ringwald     return packet[2];
4301fbd72c5SMatthias Ringwald }
4311fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4321fbd72c5SMatthias Ringwald     return packet[3];
4331fbd72c5SMatthias Ringwald }
4341fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4351fbd72c5SMatthias Ringwald     return packet[4];
4361fbd72c5SMatthias Ringwald }
4371fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4381fbd72c5SMatthias Ringwald     return packet[5];
4391fbd72c5SMatthias Ringwald }
4401fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4411fbd72c5SMatthias Ringwald     return packet[6];
4421fbd72c5SMatthias Ringwald }
4431fbd72c5SMatthias Ringwald 
4441fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4451fbd72c5SMatthias Ringwald     packet[0] = code;
4461fbd72c5SMatthias Ringwald }
4471fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4481fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4491fbd72c5SMatthias Ringwald }
4501fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4511fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4521fbd72c5SMatthias Ringwald }
4531fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4541fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4551fbd72c5SMatthias Ringwald }
4561fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4571fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4581fbd72c5SMatthias Ringwald }
4591fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4601fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4611fbd72c5SMatthias Ringwald }
4621fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4631fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4641fbd72c5SMatthias Ringwald }
4651fbd72c5SMatthias Ringwald 
4663deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4671979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4683deb3ec6SMatthias Ringwald     int i;
4693764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47084c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4711979f09cSMatthias Ringwald             return false;
47284c0c5c7SMatthias Ringwald         }
4733deb3ec6SMatthias Ringwald     }
4741979f09cSMatthias Ringwald     return true;
4753deb3ec6SMatthias Ringwald }
4763deb3ec6SMatthias Ringwald 
4771979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4783764b551SMatthias Ringwald     return sm_is_null(random, 8);
4793764b551SMatthias Ringwald }
4803764b551SMatthias Ringwald 
4811979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4823764b551SMatthias Ringwald     return sm_is_null(key, 16);
4833764b551SMatthias Ringwald }
4843764b551SMatthias Ringwald 
48570b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
48670b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
48770b44dd4SMatthias Ringwald 	UNUSED(ts);
48870b44dd4SMatthias Ringwald 	sm_run();
48970b44dd4SMatthias Ringwald }
49070b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4912d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49284c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49370b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49470b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49570b44dd4SMatthias Ringwald }
49670b44dd4SMatthias Ringwald 
4973deb3ec6SMatthias Ringwald // Key utils
4983deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
4993deb3ec6SMatthias Ringwald     int i;
5003deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5013deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5023deb3ec6SMatthias Ringwald     }
5033deb3ec6SMatthias Ringwald }
5043deb3ec6SMatthias Ringwald 
5053deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5063deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5073deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5083deb3ec6SMatthias Ringwald     int i;
5093deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5103deb3ec6SMatthias Ringwald         key[15-i] = 0;
5113deb3ec6SMatthias Ringwald     }
5123deb3ec6SMatthias Ringwald }
5133deb3ec6SMatthias Ringwald 
514899e6e02SMatthias Ringwald // ER / IR checks
51521045273SMatthias Ringwald static void sm_er_ir_set_default(void){
516899e6e02SMatthias Ringwald     int i;
517899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
518899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
519899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
520899e6e02SMatthias Ringwald     }
521899e6e02SMatthias Ringwald }
522899e6e02SMatthias Ringwald 
523899e6e02SMatthias Ringwald static int sm_er_is_default(void){
524899e6e02SMatthias Ringwald     int i;
525899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
526899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
527899e6e02SMatthias Ringwald     }
528899e6e02SMatthias Ringwald     return 1;
529899e6e02SMatthias Ringwald }
530899e6e02SMatthias Ringwald 
531899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
532899e6e02SMatthias Ringwald     int i;
533899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
534899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
535899e6e02SMatthias Ringwald     }
536899e6e02SMatthias Ringwald     return 1;
537899e6e02SMatthias Ringwald }
538899e6e02SMatthias Ringwald 
53973102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54073102768SMatthias Ringwald     UNUSED(channel);
54173102768SMatthias Ringwald 
54273102768SMatthias Ringwald     // log event
54373102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54473102768SMatthias Ringwald     // dispatch to all event handlers
54573102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
54673102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
54773102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
54873102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
54973102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55073102768SMatthias Ringwald     }
55173102768SMatthias Ringwald }
55273102768SMatthias Ringwald 
55373102768SMatthias 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){
55473102768SMatthias Ringwald     event[0] = type;
55573102768SMatthias Ringwald     event[1] = event_size - 2;
55673102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
55773102768SMatthias Ringwald     event[4] = addr_type;
55873102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
55973102768SMatthias Ringwald }
56073102768SMatthias Ringwald 
56173102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56273102768SMatthias Ringwald     uint8_t event[11];
56373102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56473102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56573102768SMatthias Ringwald }
56673102768SMatthias Ringwald 
56773102768SMatthias 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){
56873102768SMatthias Ringwald     uint8_t event[15];
56973102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57073102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57173102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57273102768SMatthias Ringwald }
57373102768SMatthias Ringwald 
57473102768SMatthias 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){
57573102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57673102768SMatthias Ringwald     bd_addr_t identity_address;
57773102768SMatthias Ringwald     int identity_address_type;
57873102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
57973102768SMatthias Ringwald 
58073102768SMatthias Ringwald     uint8_t event[20];
58173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58273102768SMatthias Ringwald     event[11] = identity_address_type;
58373102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58473102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58673102768SMatthias Ringwald }
58773102768SMatthias Ringwald 
58873102768SMatthias 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){
58973102768SMatthias Ringwald     uint8_t event[12];
59073102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59173102768SMatthias Ringwald     event[11] = status;
59273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59373102768SMatthias Ringwald }
59473102768SMatthias Ringwald 
59573102768SMatthias Ringwald 
59673102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
59773102768SMatthias Ringwald 
5983ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
5993ab61f77SMatthias Ringwald 
6007b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60173102768SMatthias Ringwald 
60273102768SMatthias Ringwald     int       identity_addr_type;
60373102768SMatthias Ringwald     bd_addr_t identity_addr;
6043c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6053c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60673102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6073c0e26deSMatthias Ringwald     } else {
6083c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6093c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6103c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6113c0e26deSMatthias Ringwald     }
61273102768SMatthias Ringwald 
61373102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61473102768SMatthias Ringwald }
61573102768SMatthias Ringwald 
61673102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
61773102768SMatthias Ringwald 
61860be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
61960be5b21SMatthias Ringwald 
6207b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62173102768SMatthias Ringwald 
62273102768SMatthias Ringwald     int       identity_addr_type;
62373102768SMatthias Ringwald     bd_addr_t identity_addr;
6243c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6253c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62673102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6273c0e26deSMatthias Ringwald     } else {
6283c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6293c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6303c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6313c0e26deSMatthias Ringwald     }
63273102768SMatthias Ringwald 
63373102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63473102768SMatthias Ringwald }
63573102768SMatthias Ringwald 
636d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
637d3c12277SMatthias Ringwald 
638d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
639d3c12277SMatthias Ringwald 
640d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
641d3c12277SMatthias Ringwald 
642d3c12277SMatthias Ringwald     uint8_t event[11];
643d3c12277SMatthias 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);
644d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
645d3c12277SMatthias Ringwald }
646d3c12277SMatthias Ringwald 
6470ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
648f61072f5SMatthias Ringwald 
649d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
650d77906ffSMatthias Ringwald 
65169f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65269f82ad8SMatthias Ringwald 
6530ccf6c9cSMatthias Ringwald     uint8_t event[13];
6540ccf6c9cSMatthias 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);
6550ccf6c9cSMatthias Ringwald     event[11] = status;
6560ccf6c9cSMatthias Ringwald     event[12] = reason;
6570ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6580ccf6c9cSMatthias Ringwald }
6590ccf6c9cSMatthias Ringwald 
6603deb3ec6SMatthias Ringwald // SMP Timeout implementation
6613deb3ec6SMatthias Ringwald 
6623deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6633deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6643deb3ec6SMatthias Ringwald //
6653deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6663deb3ec6SMatthias Ringwald //
6673deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6683deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6693deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6703deb3ec6SMatthias Ringwald // established.
6713deb3ec6SMatthias Ringwald 
672ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6733deb3ec6SMatthias Ringwald     log_info("SM timeout");
674c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6753deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67668a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6770ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6783deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6793deb3ec6SMatthias Ringwald 
6803deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6813deb3ec6SMatthias Ringwald     sm_run();
6823deb3ec6SMatthias Ringwald }
6833deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
684528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68591a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
686528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
687528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
688528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6893deb3ec6SMatthias Ringwald }
6903deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
691528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6923deb3ec6SMatthias Ringwald }
6933deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6943deb3ec6SMatthias Ringwald     sm_timeout_stop();
6953deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6963deb3ec6SMatthias Ringwald }
6973deb3ec6SMatthias Ringwald 
6983deb3ec6SMatthias Ringwald // end of sm timeout
6993deb3ec6SMatthias Ringwald 
7003deb3ec6SMatthias Ringwald // GAP Random Address updates
7013deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
702ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7033deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7043deb3ec6SMatthias Ringwald 
7053deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
706899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
707d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
708fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
70970b44dd4SMatthias Ringwald     sm_trigger_run();
7103deb3ec6SMatthias Ringwald }
7113deb3ec6SMatthias Ringwald 
712ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7139ec2630cSMatthias Ringwald     UNUSED(timer);
7149ec2630cSMatthias Ringwald 
7153deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
716528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
717528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7183deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7193deb3ec6SMatthias Ringwald }
7203deb3ec6SMatthias Ringwald 
7213deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
722528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
723528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
724528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7253deb3ec6SMatthias Ringwald }
7263deb3ec6SMatthias Ringwald 
7273deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
728528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7293deb3ec6SMatthias Ringwald }
7303deb3ec6SMatthias Ringwald 
7313deb3ec6SMatthias Ringwald // ah(k,r) helper
7323deb3ec6SMatthias Ringwald // r = padding || r
7333deb3ec6SMatthias Ringwald // r - 24 bit value
7344a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7353deb3ec6SMatthias Ringwald     // r'= padding || r
7363deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7376535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7383deb3ec6SMatthias Ringwald }
7393deb3ec6SMatthias Ringwald 
7403deb3ec6SMatthias Ringwald // d1 helper
7413deb3ec6SMatthias Ringwald // d' = padding || r || d
7423deb3ec6SMatthias Ringwald // d,r - 16 bit values
7434a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7443deb3ec6SMatthias Ringwald     // d'= padding || r || d
7453deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
746f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
747f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7483deb3ec6SMatthias Ringwald }
7493deb3ec6SMatthias Ringwald 
7503deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7514a6806f3SMatthias 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){
7523deb3ec6SMatthias Ringwald 
7533deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7543deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7553deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7563deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7573deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7583deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7593deb3ec6SMatthias Ringwald 
7603deb3ec6SMatthias Ringwald     sm_key_t p1;
7619c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7629c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7633deb3ec6SMatthias Ringwald     p1[14] = rat;
7643deb3ec6SMatthias Ringwald     p1[15] = iat;
7658314c363SMatthias Ringwald     log_info_key("p1", p1);
7668314c363SMatthias Ringwald     log_info_key("r", r);
7673deb3ec6SMatthias Ringwald 
7683deb3ec6SMatthias Ringwald     // t1 = r xor p1
7693deb3ec6SMatthias Ringwald     int i;
7703deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7713deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7723deb3ec6SMatthias Ringwald     }
7738314c363SMatthias Ringwald     log_info_key("t1", t1);
7743deb3ec6SMatthias Ringwald }
7753deb3ec6SMatthias Ringwald 
7763deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7774a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7783deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7793deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7803deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7813deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7823deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7833deb3ec6SMatthias Ringwald 
7843deb3ec6SMatthias Ringwald     sm_key_t p2;
7853deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7866535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7876535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7888314c363SMatthias Ringwald     log_info_key("p2", p2);
7893deb3ec6SMatthias Ringwald 
7903deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7913deb3ec6SMatthias Ringwald     int i;
7923deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7933deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7943deb3ec6SMatthias Ringwald     }
7958314c363SMatthias Ringwald     log_info_key("t3", t3);
7963deb3ec6SMatthias Ringwald }
7973deb3ec6SMatthias Ringwald 
7984a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
7998314c363SMatthias Ringwald     log_info_key("r1", r1);
8008314c363SMatthias Ringwald     log_info_key("r2", r2);
8016535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8026535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8033deb3ec6SMatthias Ringwald }
8043deb3ec6SMatthias Ringwald 
805fbe050beSMatthias Ringwald 
8063deb3ec6SMatthias Ringwald // decide on stk generation based on
8073deb3ec6SMatthias Ringwald // - pairing request
8083deb3ec6SMatthias Ringwald // - io capabilities
8093deb3ec6SMatthias Ringwald // - OOB data availability
8103deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8113deb3ec6SMatthias Ringwald 
8128334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8138334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8148334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8158334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8168334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8178334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8188334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8198334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8208334d3d8SMatthias Ringwald     };
8218334d3d8SMatthias Ringwald 
8228334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8238334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8248334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8258334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8278334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8288334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8298334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8308334d3d8SMatthias Ringwald     };
8318334d3d8SMatthias Ringwald #endif
8328334d3d8SMatthias Ringwald 
8333deb3ec6SMatthias Ringwald     // default: just works
8343deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8353deb3ec6SMatthias Ringwald 
83627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83727c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83827c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8394ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84027c32905SMatthias Ringwald #else
84127c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84227c32905SMatthias Ringwald #endif
84398d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84427c32905SMatthias Ringwald 
84565a9a04eSMatthias Ringwald 
84665a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8471979f09cSMatthias Ringwald     bool use_oob;
84865a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
84965a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85065a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8511979f09cSMatthias 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;
85265a9a04eSMatthias Ringwald     } else {
85365a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85465a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8551979f09cSMatthias 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;
85665a9a04eSMatthias Ringwald     }
85765a9a04eSMatthias Ringwald     if (use_oob){
85865a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
85965a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86065a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86165a9a04eSMatthias Ringwald         return;
86265a9a04eSMatthias Ringwald     }
86365a9a04eSMatthias Ringwald 
86427c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86527c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86627c32905SMatthias Ringwald     // model shall be used.
8674ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8684ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
86927c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87027c32905SMatthias Ringwald         return;
87127c32905SMatthias Ringwald     }
87227c32905SMatthias Ringwald 
8733deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8743deb3ec6SMatthias Ringwald     sm_reset_tk();
8753deb3ec6SMatthias Ringwald 
8763deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8778da2e96dSMatthias 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)){
8783deb3ec6SMatthias Ringwald         return;
8793deb3ec6SMatthias Ringwald     }
8803deb3ec6SMatthias Ringwald 
8813deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8823deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88327c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88427c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88527c32905SMatthias Ringwald 
88627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
887c6b7cbd9SMatthias Ringwald     // table not define by default
88827c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
88927c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89027c32905SMatthias Ringwald     }
89127c32905SMatthias Ringwald #endif
89227c32905SMatthias 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)];
89327c32905SMatthias Ringwald 
8943deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8951ad129beSMatthias 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);
8963deb3ec6SMatthias Ringwald }
8973deb3ec6SMatthias Ringwald 
8983deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
8993deb3ec6SMatthias Ringwald     int flags = 0;
9003deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9013deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9023deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9033deb3ec6SMatthias Ringwald     }
9043deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9053deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9073deb3ec6SMatthias Ringwald     }
9083deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9103deb3ec6SMatthias Ringwald     }
9113deb3ec6SMatthias Ringwald     return flags;
9123deb3ec6SMatthias Ringwald }
9133deb3ec6SMatthias Ringwald 
9143deb3ec6SMatthias Ringwald static void sm_setup_key_distribution(uint8_t key_set){
9153deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9163deb3ec6SMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(key_set);
917715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9189790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
919715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9209790be5fSMatthias Ringwald #endif
9213deb3ec6SMatthias Ringwald }
9223deb3ec6SMatthias Ringwald 
9233deb3ec6SMatthias Ringwald // CSRK Key Lookup
9243deb3ec6SMatthias Ringwald 
9253deb3ec6SMatthias Ringwald 
9263deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9273deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9283deb3ec6SMatthias Ringwald }
9293deb3ec6SMatthias Ringwald 
930711e6c80SMatthias 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){
9316535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9323deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9333deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9343deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9353deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
936711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9373deb3ec6SMatthias Ringwald }
9383deb3ec6SMatthias Ringwald 
9393deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9403deb3ec6SMatthias Ringwald     // check if already in list
941665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9423deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
943665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
944665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
945665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9463deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9473deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9483deb3ec6SMatthias Ringwald         // already in list
9493deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9503deb3ec6SMatthias Ringwald     }
9513deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9523deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9533deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9546535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
955665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
95670b44dd4SMatthias Ringwald     sm_trigger_run();
9573deb3ec6SMatthias Ringwald     return 0;
9583deb3ec6SMatthias Ringwald }
9593deb3ec6SMatthias Ringwald 
960d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
961d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
962514d35fcSMatthias Ringwald 
963d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
964d1a1f6a4SMatthias Ringwald     UNUSED(arg);
965d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
966d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
96770b44dd4SMatthias Ringwald     sm_trigger_run();
9683deb3ec6SMatthias Ringwald }
969514d35fcSMatthias Ringwald 
9704dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9714ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9723deb3ec6SMatthias Ringwald }
9736d80b495SMatthias Ringwald #endif
9743deb3ec6SMatthias Ringwald 
9756d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
976514d35fcSMatthias Ringwald // generic cmac calculation
977d1a1f6a4SMatthias 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)){
978d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
979d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
980d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9813deb3ec6SMatthias Ringwald }
9827a766ebfSMatthias Ringwald #endif
9833deb3ec6SMatthias Ringwald 
984514d35fcSMatthias Ringwald // cmac for ATT Message signing
9857a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
986d1a1f6a4SMatthias Ringwald 
987d1a1f6a4SMatthias 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)){
988d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
989d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
990d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
991d1a1f6a4SMatthias Ringwald }
992d1a1f6a4SMatthias Ringwald 
9934dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
994d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
995d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
9964dfd504aSMatthias Ringwald         return 0;
9974dfd504aSMatthias Ringwald     }
9984dfd504aSMatthias Ringwald 
999d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10004dfd504aSMatthias Ringwald 
1001d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10024dfd504aSMatthias Ringwald     if (offset < 3){
1003d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10044dfd504aSMatthias Ringwald     }
1005d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10064dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1007d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10084dfd504aSMatthias Ringwald     }
1009d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10104dfd504aSMatthias Ringwald }
10114dfd504aSMatthias Ringwald 
10124dfd504aSMatthias 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)){
1013514d35fcSMatthias Ringwald     // ATT Message Signing
1014d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1015d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1016d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1017514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1018d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1019d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1020d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10213deb3ec6SMatthias Ringwald }
10227a766ebfSMatthias Ringwald #endif
10233deb3ec6SMatthias Ringwald 
10243deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1025446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10263deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1027d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10283deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10293deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10313deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10325611a760SMatthias 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);
10333deb3ec6SMatthias Ringwald             } else {
1034c9b8fdd9SMatthias 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));
10353deb3ec6SMatthias Ringwald             }
10363deb3ec6SMatthias Ringwald             break;
10373deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
103842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1039c9b8fdd9SMatthias 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));
10403deb3ec6SMatthias Ringwald             } else {
10413deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10425611a760SMatthias 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);
10433deb3ec6SMatthias Ringwald             }
10443deb3ec6SMatthias Ringwald             break;
104547fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10463deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10475611a760SMatthias 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);
10483deb3ec6SMatthias Ringwald             break;
104947fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1050446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1051c8c46d51SMatthias 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));
105227c32905SMatthias Ringwald             break;
10533deb3ec6SMatthias Ringwald         case JUST_WORKS:
10543deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10555611a760SMatthias 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);
10563deb3ec6SMatthias Ringwald             break;
10573deb3ec6SMatthias Ringwald         case OOB:
10583deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10593deb3ec6SMatthias Ringwald             break;
10607bbeb3adSMilanka Ringwald         default:
10617bbeb3adSMilanka Ringwald             btstack_assert(false);
10627bbeb3adSMilanka Ringwald             break;
10633deb3ec6SMatthias Ringwald     }
10643deb3ec6SMatthias Ringwald }
10653deb3ec6SMatthias Ringwald 
10663deb3ec6SMatthias Ringwald static int sm_key_distribution_all_received(sm_connection_t * sm_conn){
10673deb3ec6SMatthias Ringwald     int recv_flags;
106842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
106952f9cf63SMatthias Ringwald         // slave / responder
10701ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres));
10713deb3ec6SMatthias Ringwald     } else {
10723deb3ec6SMatthias Ringwald         // master / initiator
10731ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
10743deb3ec6SMatthias Ringwald     }
1075eddc894fSMatthias Ringwald 
1076eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1077eddc894fSMatthias Ringwald     // LTK (= encyrption information & master identification) only used exchanged for LE Legacy Connection
1078eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1079eddc894fSMatthias Ringwald         recv_flags &= ~(SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION | SM_KEYDIST_FLAG_MASTER_IDENTIFICATION);
1080eddc894fSMatthias Ringwald     }
1081eddc894fSMatthias Ringwald #endif
1082eddc894fSMatthias Ringwald 
10833deb3ec6SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, recv_flags);
108444263cccSMatthias Ringwald     return (setup->sm_key_distribution_received_set & recv_flags) == recv_flags;
10853deb3ec6SMatthias Ringwald }
10863deb3ec6SMatthias Ringwald 
1087711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10887149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10893deb3ec6SMatthias Ringwald         sm_timeout_stop();
10907149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1091711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1092c085d9ffSMatthias Ringwald 
1093c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1094c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1095c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1096c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1097c085d9ffSMatthias Ringwald         }
1098c085d9ffSMatthias Ringwald #endif
10993deb3ec6SMatthias Ringwald     }
11003deb3ec6SMatthias Ringwald }
11013deb3ec6SMatthias Ringwald 
11027d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11031dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11040ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11051dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11061dca9d8aSMatthias Ringwald }
11071dca9d8aSMatthias Ringwald 
11083deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1109bb09604fSMatthias Ringwald 
1110bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11113deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1112bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1114bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1115bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1116bb09604fSMatthias Ringwald #endif
11177ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11187ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11197ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11207ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11217ece0eaaSMatthias Ringwald         }
11227ece0eaaSMatthias Ringwald #endif
11233deb3ec6SMatthias Ringwald     }
11243deb3ec6SMatthias Ringwald     return flags;
11253deb3ec6SMatthias Ringwald }
11263deb3ec6SMatthias Ringwald 
1127d7471931SMatthias Ringwald static void sm_reset_setup(void){
11283deb3ec6SMatthias Ringwald     // fill in sm setup
1129901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1130dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
11313deb3ec6SMatthias Ringwald     sm_reset_tk();
1132d7471931SMatthias Ringwald }
1133d7471931SMatthias Ringwald 
1134d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1135d7471931SMatthias Ringwald 
1136d7471931SMatthias Ringwald     // fill in sm setup
11373deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11386535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11393deb3ec6SMatthias Ringwald 
1140a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
1141a680ba6bSMatthias Ringwald     setup->sm_have_oob_data = 0;
11429305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1143a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11443deb3ec6SMatthias Ringwald     }
11453deb3ec6SMatthias Ringwald 
1146a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1147a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11484acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11494acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1150a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11519305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11524acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1153a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1154a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1155a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1156a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11574acf7b7bSMatthias Ringwald                     setup->sm_ra);
11584acf7b7bSMatthias Ringwald             } else {
11594acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11604acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11614acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11624acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11634acf7b7bSMatthias Ringwald                     setup->sm_rb);
11644acf7b7bSMatthias Ringwald             }
1165a680ba6bSMatthias Ringwald         } else {
1166a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1167a680ba6bSMatthias Ringwald         }
1168a680ba6bSMatthias Ringwald     }
1169a680ba6bSMatthias Ringwald #endif
1170a680ba6bSMatthias Ringwald 
11713deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11733deb3ec6SMatthias Ringwald         // slave
11743deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11753deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1176d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11776535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1178d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11793deb3ec6SMatthias Ringwald     } else {
11803deb3ec6SMatthias Ringwald         // master
11813deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11823deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1183d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11846535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1185d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11863deb3ec6SMatthias Ringwald 
11873deb3ec6SMatthias Ringwald         int key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11881ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11891ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11903deb3ec6SMatthias Ringwald     }
11913deb3ec6SMatthias Ringwald 
119257132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
11932c041b42SMatthias Ringwald     uint8_t max_encryptinon_key_size = sm_max_encryption_key_size;
11942c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11952c041b42SMatthias Ringwald     // enable SC for SC only mode
11962c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11972c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
11982c041b42SMatthias Ringwald         max_encryptinon_key_size = 16;
11992c041b42SMatthias Ringwald     }
12002c041b42SMatthias Ringwald #endif
120157132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120257132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120357132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120457132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120557132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120657132f12SMatthias Ringwald 	}
120757132f12SMatthias Ringwald #endif
12081ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1209a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1210df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
12112c041b42SMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryptinon_key_size);
12123deb3ec6SMatthias Ringwald }
12133deb3ec6SMatthias Ringwald 
12143deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12153deb3ec6SMatthias Ringwald 
12163deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12173deb3ec6SMatthias Ringwald     int                   remote_key_request;
121842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121952f9cf63SMatthias Ringwald         // slave / responder
12203deb3ec6SMatthias Ringwald         remote_packet      = &setup->sm_m_preq;
12211ad129beSMatthias Ringwald         remote_key_request = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12223deb3ec6SMatthias Ringwald     } else {
12233deb3ec6SMatthias Ringwald         // master / initiator
12243deb3ec6SMatthias Ringwald         remote_packet      = &setup->sm_s_pres;
12251ad129beSMatthias Ringwald         remote_key_request = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12263deb3ec6SMatthias Ringwald     }
12273deb3ec6SMatthias Ringwald 
12283deb3ec6SMatthias Ringwald     // check key size
12292c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12302c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12312c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12322c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12332c041b42SMatthias Ringwald     }
12342c041b42SMatthias Ringwald #endif
12351ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12364ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12373deb3ec6SMatthias Ringwald 
1238eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12393deb3ec6SMatthias Ringwald     sm_setup_tk();
12403deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12413deb3ec6SMatthias Ringwald 
12423deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12433deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12443deb3ec6SMatthias Ringwald 
1245eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12462c041b42SMatthias Ringwald     // Check LE SC Only mode
12473cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12483cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12493cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12503cdbe9dbSMatthias Ringwald     }
12513cdbe9dbSMatthias Ringwald 
1252eddc894fSMatthias Ringwald     // LTK (= encyrption information & master identification) only used exchanged for LE Legacy Connection
1253eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1254eddc894fSMatthias Ringwald         remote_key_request &= ~SM_KEYDIST_ENC_KEY;
1255eddc894fSMatthias Ringwald     }
1256eddc894fSMatthias Ringwald #endif
1257eddc894fSMatthias Ringwald 
125852f9cf63SMatthias Ringwald     // identical to responder
125952f9cf63SMatthias Ringwald     sm_setup_key_distribution(remote_key_request);
126052f9cf63SMatthias Ringwald 
12613deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1262c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12633deb3ec6SMatthias Ringwald 
12643deb3ec6SMatthias Ringwald     return 0;
12653deb3ec6SMatthias Ringwald }
12663deb3ec6SMatthias Ringwald 
12673deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12683deb3ec6SMatthias Ringwald 
12693deb3ec6SMatthias Ringwald     // cache and reset context
12703deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12713deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12723deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12733deb3ec6SMatthias Ringwald 
12743deb3ec6SMatthias Ringwald     // reset context
12753deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12763deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12773deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1278711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12793deb3ec6SMatthias Ringwald 
12803deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1281d2e90122SMatthias Ringwald     sm_key_t ltk;
12821979f09cSMatthias Ringwald     bool have_ltk;
12836c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12841979f09cSMatthias Ringwald     bool trigger_pairing;
128542134bc6SMatthias Ringwald #endif
12863deb3ec6SMatthias Ringwald     switch (mode){
12873deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12883deb3ec6SMatthias Ringwald             break;
12893deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12903deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1291711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12926c44b759SMatthias Ringwald 
12936c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12946c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12956c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12966c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12976c44b759SMatthias Ringwald 
12983deb3ec6SMatthias Ringwald             switch (event){
1299a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13003deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13013deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1302a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13036c44b759SMatthias Ringwald 
13046c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13056c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13066c44b759SMatthias Ringwald 
13076c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13086c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1309212d735eSMatthias Ringwald                         // IRK required before, continue
13106c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13116c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13126c39055aSMatthias Ringwald                             break;
13136c39055aSMatthias Ringwald                         }
1314212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1315212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1316212d735eSMatthias Ringwald                             break;
1317212d735eSMatthias Ringwald                         }
13187af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13197af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13206c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13217af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13227af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13236c44b759SMatthias Ringwald #endif
13247af5dcd5SMatthias Ringwald 
13257af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13261979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13277af5dcd5SMatthias Ringwald 
13287af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13297af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13307af5dcd5SMatthias Ringwald                             if (have_ltk){
13317af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13327af5dcd5SMatthias Ringwald                             } else {
13337af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13347af5dcd5SMatthias Ringwald                             }
13357af5dcd5SMatthias Ringwald                             sm_trigger_run();
13366c44b759SMatthias Ringwald                         }
13376c44b759SMatthias Ringwald #endif
13386c44b759SMatthias Ringwald                     } else {
13396c44b759SMatthias Ringwald 
134042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13416c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13426c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13436c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13441979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13453deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134609ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134732bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1348c245ca32SMatthias Ringwald 
1349d4af1595SMatthias Ringwald                         if (have_ltk){
13506a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1351b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135232bc5d65SMatthias Ringwald #else
135332bc5d65SMatthias Ringwald                             if (trigger_pairing){
135432bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135532bc5d65SMatthias Ringwald                             } else {
135632bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135732bc5d65SMatthias Ringwald                             }
135832bc5d65SMatthias Ringwald #endif
135932bc5d65SMatthias Ringwald                         }
136032bc5d65SMatthias Ringwald 
136132bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13626c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13635567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1364d4af1595SMatthias Ringwald                             break;
1365d4af1595SMatthias Ringwald                         }
13666c44b759SMatthias Ringwald 
13676c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13686c44b759SMatthias Ringwald                         if (trigger_pairing){
13693deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1370d4af1595SMatthias Ringwald                             break;
13713deb3ec6SMatthias Ringwald                         }
137242134bc6SMatthias Ringwald #endif
1373298ab52bSMatthias Ringwald                     }
13743deb3ec6SMatthias Ringwald                     break;
13753deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13763deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13776c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13787af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13796c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13806c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13816c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13826c39055aSMatthias Ringwald                         }
13837af5dcd5SMatthias Ringwald                         // send security request if requested
13847af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13857af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13867af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13877af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13887af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13897af5dcd5SMatthias Ringwald                         }
13906c39055aSMatthias Ringwald                         break;
13917af5dcd5SMatthias Ringwald #endif
13926c39055aSMatthias Ringwald                     }
139342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139409ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13953deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139609ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13973deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139842134bc6SMatthias Ringwald #endif
13993deb3ec6SMatthias Ringwald                     break;
14007bbeb3adSMilanka Ringwald 
14017bbeb3adSMilanka Ringwald                 default:
14027bbeb3adSMilanka Ringwald                     btstack_assert(false);
14037bbeb3adSMilanka Ringwald                     break;
14043deb3ec6SMatthias Ringwald             }
14053deb3ec6SMatthias Ringwald             break;
14063deb3ec6SMatthias Ringwald         default:
14073deb3ec6SMatthias Ringwald             break;
14083deb3ec6SMatthias Ringwald     }
14093deb3ec6SMatthias Ringwald 
14103deb3ec6SMatthias Ringwald     switch (event){
1411a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1412711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14133deb3ec6SMatthias Ringwald             break;
14143deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1415711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14163deb3ec6SMatthias Ringwald             break;
14177bbeb3adSMilanka Ringwald         default:
14187bbeb3adSMilanka Ringwald             btstack_assert(false);
14197bbeb3adSMilanka Ringwald             break;
14203deb3ec6SMatthias Ringwald     }
14213deb3ec6SMatthias Ringwald }
14223deb3ec6SMatthias Ringwald 
14233deb3ec6SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
14243deb3ec6SMatthias Ringwald 
14253deb3ec6SMatthias Ringwald     int le_db_index = -1;
14263deb3ec6SMatthias Ringwald 
142727ef8bc8SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
14281979f09cSMatthias Ringwald     bool bonding_enabed = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
142927ef8bc8SMatthias Ringwald                          & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
14304ea43905SMatthias Ringwald                          & SM_AUTHREQ_BONDING ) != 0u;
143127ef8bc8SMatthias Ringwald 
143227ef8bc8SMatthias Ringwald     if (bonding_enabed){
143327ef8bc8SMatthias Ringwald 
14343deb3ec6SMatthias Ringwald         // lookup device based on IRK
14353deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14363deb3ec6SMatthias Ringwald             int i;
1437092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14383deb3ec6SMatthias Ringwald                 sm_key_t irk;
14393deb3ec6SMatthias Ringwald                 bd_addr_t address;
1440c7e2c1a5SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14413deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, irk);
1442adf5eaa9SMatthias Ringwald                 // skip unused entries
1443c7e2c1a5SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1444c7e2c1a5SMatthias Ringwald                 // compare IRK
1445c7e2c1a5SMatthias Ringwald                 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1446c7e2c1a5SMatthias Ringwald 
14473deb3ec6SMatthias Ringwald                 log_info("sm: device found for IRK, updating");
14483deb3ec6SMatthias Ringwald                 le_db_index = i;
14493deb3ec6SMatthias Ringwald                 break;
14503deb3ec6SMatthias Ringwald             }
1451c7e2c1a5SMatthias Ringwald         } else {
1452c7e2c1a5SMatthias Ringwald             // assert IRK is set to zero
1453c7e2c1a5SMatthias Ringwald             memset(setup->sm_peer_irk, 0, 16);
14543deb3ec6SMatthias Ringwald         }
14553deb3ec6SMatthias Ringwald 
14563deb3ec6SMatthias Ringwald         // if not found, lookup via public address if possible
14573deb3ec6SMatthias Ringwald         log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1458c1ab6cc1SMatthias Ringwald         if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14593deb3ec6SMatthias Ringwald             int i;
1460092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14613deb3ec6SMatthias Ringwald                 bd_addr_t address;
1462adf5eaa9SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14633deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, NULL);
1464adf5eaa9SMatthias Ringwald                 // skip unused entries
1465adf5eaa9SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14663deb3ec6SMatthias Ringwald                 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14675df9dc78SMatthias Ringwald                 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14683deb3ec6SMatthias Ringwald                     log_info("sm: device found for public address, updating");
14693deb3ec6SMatthias Ringwald                     le_db_index = i;
14703deb3ec6SMatthias Ringwald                     break;
14713deb3ec6SMatthias Ringwald                 }
14723deb3ec6SMatthias Ringwald             }
14733deb3ec6SMatthias Ringwald         }
14743deb3ec6SMatthias Ringwald 
14753deb3ec6SMatthias Ringwald         // if not found, add to db
147602b02cffSMatthias Ringwald         bool new_to_le_device_db = false;
14773deb3ec6SMatthias Ringwald         if (le_db_index < 0) {
14783deb3ec6SMatthias Ringwald             le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147902b02cffSMatthias Ringwald 			new_to_le_device_db = true;
14803deb3ec6SMatthias Ringwald         }
14813deb3ec6SMatthias Ringwald 
14823deb3ec6SMatthias Ringwald         if (le_db_index >= 0){
14833deb3ec6SMatthias Ringwald 
148402b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148502b02cffSMatthias Ringwald         	if (!new_to_le_device_db){
148602b02cffSMatthias Ringwald 				hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148702b02cffSMatthias Ringwald         	}
148802b02cffSMatthias Ringwald 			hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148902b02cffSMatthias Ringwald #else
149002b02cffSMatthias Ringwald 			UNUSED(new_to_le_device_db);
149102b02cffSMatthias Ringwald #endif
149202b02cffSMatthias Ringwald 
149348163929SMatthias 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);
1494e1086030SMatthias Ringwald             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14957710ebd2SMatthias Ringwald             sm_conn->sm_le_db_index = le_db_index;
149648163929SMatthias Ringwald 
1497eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14983deb3ec6SMatthias Ringwald             // store local CSRK
1499715a43d1SMatthias Ringwald             setup->sm_le_device_index = le_db_index;
1500715a43d1SMatthias Ringwald             if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15013deb3ec6SMatthias Ringwald                 log_info("sm: store local CSRK");
15023deb3ec6SMatthias Ringwald                 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15033deb3ec6SMatthias Ringwald                 le_device_db_local_counter_set(le_db_index, 0);
15043deb3ec6SMatthias Ringwald             }
15053deb3ec6SMatthias Ringwald 
15063deb3ec6SMatthias Ringwald             // store remote CSRK
15073deb3ec6SMatthias Ringwald             if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15083deb3ec6SMatthias Ringwald                 log_info("sm: store remote CSRK");
15093deb3ec6SMatthias Ringwald                 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15103deb3ec6SMatthias Ringwald                 le_device_db_remote_counter_set(le_db_index, 0);
15113deb3ec6SMatthias Ringwald             }
1512eda85fbfSMatthias Ringwald #endif
151378f44163SMatthias Ringwald             // store encryption information for secure connections: LTK generated by ECDH
151478f44163SMatthias Ringwald             if (setup->sm_use_secure_connections){
1515e6343eb6SMatthias Ringwald                 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151678f44163SMatthias Ringwald                 uint8_t zero_rand[8];
151778f44163SMatthias Ringwald                 memset(zero_rand, 0, 8);
151878f44163SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15193dc3a67dSMatthias Ringwald                     sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
152078f44163SMatthias Ringwald             }
152178f44163SMatthias Ringwald 
1522e6343eb6SMatthias Ringwald             // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152378f44163SMatthias Ringwald             else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
152478f44163SMatthias Ringwald                    && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1525e6343eb6SMatthias Ringwald                 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15263deb3ec6SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15273dc3a67dSMatthias Ringwald                     sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152878f44163SMatthias Ringwald 
15293deb3ec6SMatthias Ringwald             }
15303deb3ec6SMatthias Ringwald         }
153127ef8bc8SMatthias Ringwald     } else {
153227ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153327ef8bc8SMatthias Ringwald     }
15343deb3ec6SMatthias Ringwald }
15353deb3ec6SMatthias Ringwald 
1536688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1537f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1538688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1539688a08f9SMatthias Ringwald }
1540688a08f9SMatthias Ringwald 
1541688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1542688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1543688a08f9SMatthias Ringwald }
1544688a08f9SMatthias Ringwald 
15459af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1546688a08f9SMatthias Ringwald 
1547dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1548945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1549f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1550dc300847SMatthias Ringwald 
1551b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1552b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15531f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1554b90c4e75SMatthias Ringwald     } else {
1555b90c4e75SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_w2_cmac_for_confirmation, (void *)(uintptr_t) sm_conn->sm_handle);
1556b35a3de2SMatthias Ringwald     }
1557b35a3de2SMatthias Ringwald }
1558b35a3de2SMatthias Ringwald 
1559688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
156042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1561688a08f9SMatthias Ringwald         // Responder
15624acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15634acf7b7bSMatthias Ringwald             // generate Nb
15644acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15656ca80073SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_send_pairing_random, (void *)(uintptr_t) sm_conn->sm_handle);
15664acf7b7bSMatthias Ringwald         } else {
1567688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15684acf7b7bSMatthias Ringwald         }
1569688a08f9SMatthias Ringwald     } else {
1570688a08f9SMatthias Ringwald         // Initiator role
1571688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1572688a08f9SMatthias Ringwald             case JUST_WORKS:
1573dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1574688a08f9SMatthias Ringwald                 break;
1575688a08f9SMatthias Ringwald 
157647fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1577bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1578688a08f9SMatthias Ringwald                 break;
1579688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1580688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158147fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15824ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1583b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1584688a08f9SMatthias Ringwald                 } else {
1585dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1586688a08f9SMatthias Ringwald                 }
1587688a08f9SMatthias Ringwald                 break;
1588688a08f9SMatthias Ringwald             case OOB:
158965a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1590688a08f9SMatthias Ringwald                 break;
15917bbeb3adSMilanka Ringwald             default:
15927bbeb3adSMilanka Ringwald                 btstack_assert(false);
15937bbeb3adSMilanka Ringwald                 break;
1594688a08f9SMatthias Ringwald         }
1595688a08f9SMatthias Ringwald     }
1596688a08f9SMatthias Ringwald }
1597688a08f9SMatthias Ringwald 
1598aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1599688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1600688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1601688a08f9SMatthias Ringwald 
1602c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1603c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1604a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1605c59d0c92SMatthias Ringwald         return;
1606c59d0c92SMatthias Ringwald     }
1607c59d0c92SMatthias Ringwald 
1608bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1609bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16106857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16112bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1612b4f65634SMatthias Ringwald #endif
1613bd57ffebSMatthias Ringwald 
1614bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1615aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16166535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1617bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1618aec94140SMatthias Ringwald             break;
1619688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1620688a08f9SMatthias Ringwald             // check
1621688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1622bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1623688a08f9SMatthias Ringwald                 break;
1624688a08f9SMatthias Ringwald             }
1625bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1626688a08f9SMatthias Ringwald             break;
1627901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1628901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1629901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1630901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1631901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1632019005a0SMatthias Ringwald             break;
1633019005a0SMatthias Ringwald         }
16340346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16356535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1636bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16370346c37cSMatthias Ringwald             break;
16380346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16396535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1640bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16410346c37cSMatthias Ringwald             break;
16420346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1643b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1644b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1645b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1646b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16476535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16486535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1649893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1650bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1651019005a0SMatthias Ringwald             break;
1652901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16536535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1655901c000fSMatthias Ringwald                 // responder
1656901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1657901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1658901c000fSMatthias Ringwald                 } else {
1659901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1660901c000fSMatthias Ringwald                 }
1661901c000fSMatthias Ringwald             } else {
1662901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1663901c000fSMatthias Ringwald             }
1664901c000fSMatthias Ringwald             break;
1665901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1666901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1667901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1668aec94140SMatthias Ringwald                 break;
1669aec94140SMatthias Ringwald             }
167042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1671901c000fSMatthias Ringwald                 // responder
1672901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1673901c000fSMatthias Ringwald             } else {
1674901c000fSMatthias Ringwald                 // initiator
1675901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1676bd57ffebSMatthias Ringwald             }
1677901c000fSMatthias Ringwald             break;
16786857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
167957132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16806535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168157132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16822bacf595SMatthias Ringwald             break;
168357132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16842bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16852bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16862bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16878974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168855160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16898974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16902bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16912bacf595SMatthias Ringwald             } else {
16922bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16932bacf595SMatthias Ringwald             }
16940ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16952bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16962bacf595SMatthias Ringwald             break;
1697bdb14b0eSMatthias Ringwald #endif
1698bd57ffebSMatthias Ringwald         default:
1699bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1700bd57ffebSMatthias Ringwald             break;
1701bd57ffebSMatthias Ringwald     }
170270b44dd4SMatthias Ringwald     sm_trigger_run();
1703aec94140SMatthias Ringwald }
1704aec94140SMatthias Ringwald 
1705688a08f9SMatthias 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){
1706dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1707aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17086535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17096535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1710aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1711aec94140SMatthias Ringwald     log_info("f4 key");
1712aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1713aec94140SMatthias Ringwald     log_info("f4 message");
1714dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1715d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1716aec94140SMatthias Ringwald }
1717aec94140SMatthias Ringwald 
17180346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17190346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17200346c37cSMatthias Ringwald 
17210346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17228334d3d8SMatthias Ringwald 
17238334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17248334d3d8SMatthias Ringwald 
172540c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17260346c37cSMatthias Ringwald     // calculate salt for f5
17270346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17280346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17296535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1730d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17310346c37cSMatthias Ringwald }
17320346c37cSMatthias Ringwald 
17330346c37cSMatthias 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){
17340346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17350346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17360346c37cSMatthias Ringwald 
17370346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17380346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17396535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17406535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17416535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17426535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17436535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17446535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17450346c37cSMatthias Ringwald     log_info("f5 key");
17460346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17470346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17480346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1749d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17500346c37cSMatthias Ringwald }
17510346c37cSMatthias Ringwald 
17520346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17530346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17540346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17550346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17566535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17576535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
175842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17590346c37cSMatthias Ringwald         // responder
17600346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17610346c37cSMatthias Ringwald     } else {
17620346c37cSMatthias Ringwald         // initiator
17630346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17640346c37cSMatthias Ringwald     }
17650346c37cSMatthias Ringwald }
17660346c37cSMatthias Ringwald 
17670346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17680346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17690346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17700346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17710346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17720346c37cSMatthias Ringwald     // 1..52 setup before
17730346c37cSMatthias Ringwald     log_info("f5 key");
17740346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17750346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17760346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1777d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17780346c37cSMatthias Ringwald }
1779f92edc8eSMatthias Ringwald 
17800346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17810346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17820346c37cSMatthias Ringwald }
17830346c37cSMatthias Ringwald 
178431f061fbSMatthias 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){
17856535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17866535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17876535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17886535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
17896535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
17906535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
179131f061fbSMatthias Ringwald }
179231f061fbSMatthias Ringwald 
179331f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
179431f061fbSMatthias Ringwald     const uint16_t message_len = 65;
179531f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1796dc300847SMatthias Ringwald     log_info("f6 key");
1797dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1798dc300847SMatthias Ringwald     log_info("f6 message");
1799dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1800d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1801dc300847SMatthias Ringwald }
1802dc300847SMatthias Ringwald 
1803f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1804f92edc8eSMatthias Ringwald // - U is 256 bits
1805f92edc8eSMatthias Ringwald // - V is 256 bits
1806f92edc8eSMatthias Ringwald // - X is 128 bits
1807f92edc8eSMatthias Ringwald // - Y is 128 bits
1808bd57ffebSMatthias 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){
1809bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1810bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18126535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18136535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1814f92edc8eSMatthias Ringwald     log_info("g2 key");
1815f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1816f92edc8eSMatthias Ringwald     log_info("g2 message");
18172bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1818d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1819f92edc8eSMatthias Ringwald }
1820f92edc8eSMatthias Ringwald 
1821b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1822f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
182342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1824f92edc8eSMatthias Ringwald         // responder
1825fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1826f92edc8eSMatthias Ringwald     } else {
1827f92edc8eSMatthias Ringwald         // initiator
1828fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1829f92edc8eSMatthias Ringwald     }
1830f92edc8eSMatthias Ringwald }
1831f92edc8eSMatthias Ringwald 
1832945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18339af0f475SMatthias Ringwald     uint8_t z = 0;
183440c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18359af0f475SMatthias Ringwald         // some form of passkey
18369af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18374ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18389af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18399af0f475SMatthias Ringwald     }
1840fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18419af0f475SMatthias Ringwald }
1842688a08f9SMatthias Ringwald 
1843688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1844a680ba6bSMatthias Ringwald     // OOB
1845a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18464acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18474acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18484acf7b7bSMatthias Ringwald         } else {
18494acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18504acf7b7bSMatthias Ringwald         }
1851a680ba6bSMatthias Ringwald         return;
1852a680ba6bSMatthias Ringwald     }
1853a680ba6bSMatthias Ringwald 
1854688a08f9SMatthias Ringwald     uint8_t z = 0;
185540c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1856688a08f9SMatthias Ringwald         // some form of passkey
1857688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1858688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18594ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1860688a08f9SMatthias Ringwald     }
1861fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1862688a08f9SMatthias Ringwald }
1863688a08f9SMatthias Ringwald 
18640346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1865505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18663cf37b8cSMatthias Ringwald 
18673cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18683cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18693cf37b8cSMatthias Ringwald         return;
18703cf37b8cSMatthias Ringwald     } else {
18713cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18723cf37b8cSMatthias Ringwald     }
1873d1a1f6a4SMatthias Ringwald }
18743cf37b8cSMatthias Ringwald 
1875d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1876f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1877f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1878f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1879f3582630SMatthias Ringwald 
1880d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1881d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1882d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1883d1a1f6a4SMatthias Ringwald     // trigger next step
1884d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1885d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1886d1a1f6a4SMatthias Ringwald     }
188770b44dd4SMatthias Ringwald     sm_trigger_run();
1888dc300847SMatthias Ringwald }
1889dc300847SMatthias Ringwald 
1890dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1891dc300847SMatthias Ringwald     // calculate DHKCheck
1892dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1893dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1894dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18956535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18966535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1897dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1898dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1899dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1900dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1901dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1902dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1903dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1904dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
190542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1906dc300847SMatthias Ringwald         // responder
190731f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
190831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1909dc300847SMatthias Ringwald     } else {
1910dc300847SMatthias Ringwald         // initiator
191131f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
191231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1913dc300847SMatthias Ringwald     }
1914dc300847SMatthias Ringwald }
1915dc300847SMatthias Ringwald 
1916019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1917019005a0SMatthias Ringwald     // validate E = f6()
1918019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1919019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1920019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19216535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19226535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1923019005a0SMatthias Ringwald 
1924019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1925019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1926019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1927019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1928019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1929019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1930019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1931019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
193242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1933019005a0SMatthias Ringwald         // responder
193431f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
193531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1936019005a0SMatthias Ringwald     } else {
1937019005a0SMatthias Ringwald         // initiator
193831f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
193931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1940019005a0SMatthias Ringwald     }
1941019005a0SMatthias Ringwald }
19422bacf595SMatthias Ringwald 
194355c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19442bacf595SMatthias Ringwald 
19452bacf595SMatthias Ringwald //
19462bacf595SMatthias Ringwald // Link Key Conversion Function h6
19472bacf595SMatthias Ringwald //
194857132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19492bacf595SMatthias Ringwald // - W is 128 bits
19502bacf595SMatthias Ringwald // - keyID is 32 bits
19512bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19522bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19532bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19542bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19552bacf595SMatthias Ringwald     log_info("h6 key");
19562bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19572bacf595SMatthias Ringwald     log_info("h6 message");
19582bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1959d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19602bacf595SMatthias Ringwald }
196157132f12SMatthias Ringwald //
196257132f12SMatthias Ringwald // Link Key Conversion Function h7
196357132f12SMatthias Ringwald //
196457132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
196557132f12SMatthias Ringwald // - SALT is 128 bits
196657132f12SMatthias Ringwald // - W    is 128 bits
196757132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
196857132f12SMatthias Ringwald 	const uint16_t message_len = 16;
196957132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
197057132f12SMatthias Ringwald 	log_info("h7 key");
197157132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
197257132f12SMatthias Ringwald 	log_info("h7 message");
197357132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
197457132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
197557132f12SMatthias Ringwald }
19762bacf595SMatthias Ringwald 
1977b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1978b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1979b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1980b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
198157132f12SMatthias Ringwald 
19822bacf595SMatthias Ringwald static void h6_calculate_ilk(sm_connection_t * sm_conn){
1983b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19842bacf595SMatthias Ringwald }
19852bacf595SMatthias Ringwald 
19862bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
19872bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
19882bacf595SMatthias Ringwald }
19892bacf595SMatthias Ringwald 
199057132f12SMatthias Ringwald static void h7_calculate_ilk(sm_connection_t * sm_conn){
199157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
199257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
199357132f12SMatthias Ringwald }
19949af0f475SMatthias Ringwald #endif
19959af0f475SMatthias Ringwald 
199655c62cf5SMatthias Ringwald #endif
199755c62cf5SMatthias Ringwald 
1998613da3deSMatthias Ringwald // key management legacy connections:
1999613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2000613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2001613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2002613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2003613da3deSMatthias Ringwald 
2004613da3deSMatthias Ringwald // key management secure connections:
2005613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2006613da3deSMatthias Ringwald 
200742134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20085829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20095829ebe2SMatthias Ringwald     int encryption_key_size;
20105829ebe2SMatthias Ringwald     int authenticated;
20115829ebe2SMatthias Ringwald     int authorized;
20123dc3a67dSMatthias Ringwald     int secure_connection;
20135829ebe2SMatthias Ringwald 
20145829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20155829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20163dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20173dc3a67dSMatthias 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);
20185829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20195829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20205829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20213dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20225829ebe2SMatthias Ringwald }
202342134bc6SMatthias Ringwald #endif
2024bd57ffebSMatthias Ringwald 
202542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
202659066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20276535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
202859066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
202959066796SMatthias Ringwald     // re-establish used key encryption size
203059066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20314ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
203259066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20334ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20343dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20353dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
203659066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
203759066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
203859066796SMatthias Ringwald }
203942134bc6SMatthias Ringwald #endif
204059066796SMatthias Ringwald 
20413deb3ec6SMatthias Ringwald // distributed key generation
2042d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20433deb3ec6SMatthias Ringwald     switch (dkg_state){
20443deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20453deb3ec6SMatthias Ringwald             // already busy?
20463deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2047d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20483deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2049d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2050d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2051d1a1f6a4SMatthias 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);
2052d7f1c72eSMatthias Ringwald                 return true;
20533deb3ec6SMatthias Ringwald             }
20543deb3ec6SMatthias Ringwald             break;
20553deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20563deb3ec6SMatthias Ringwald             // already busy?
20573deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2058d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20593deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2060d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2061d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2062d1a1f6a4SMatthias 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);
2063d7f1c72eSMatthias Ringwald                 return true;
20643deb3ec6SMatthias Ringwald             }
20653deb3ec6SMatthias Ringwald             break;
20663deb3ec6SMatthias Ringwald         default:
20673deb3ec6SMatthias Ringwald             break;
20683deb3ec6SMatthias Ringwald     }
2069d7f1c72eSMatthias Ringwald     return false;
2070d7f1c72eSMatthias Ringwald }
20713deb3ec6SMatthias Ringwald 
20723deb3ec6SMatthias Ringwald // random address updates
2073d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
20743deb3ec6SMatthias Ringwald     switch (rau_state){
2075fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2076fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
20775b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2078d7f1c72eSMatthias Ringwald             return true;
20793deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
20803deb3ec6SMatthias Ringwald             // already busy?
20813deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2082d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2083d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2084d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2085d7f1c72eSMatthias Ringwald                 return true;
20863deb3ec6SMatthias Ringwald             }
20873deb3ec6SMatthias Ringwald             break;
20883deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
20893deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
20903deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
20913deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2092d7f1c72eSMatthias Ringwald             return true;
20933deb3ec6SMatthias Ringwald         default:
20943deb3ec6SMatthias Ringwald             break;
20953deb3ec6SMatthias Ringwald     }
2096d7f1c72eSMatthias Ringwald     return false;
2097d7f1c72eSMatthias Ringwald }
20983deb3ec6SMatthias Ringwald 
20993deb3ec6SMatthias Ringwald // CSRK Lookup
2100d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2101d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2102d7f1c72eSMatthias Ringwald 
21033deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21043deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21053deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2106665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2107665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21083deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21093deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21103deb3ec6SMatthias Ringwald                 // and start lookup
21113deb3ec6SMatthias 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);
21123deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21133deb3ec6SMatthias Ringwald                 break;
21143deb3ec6SMatthias Ringwald             }
21153deb3ec6SMatthias Ringwald         }
21163deb3ec6SMatthias Ringwald     }
21173deb3ec6SMatthias Ringwald 
21183deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21193deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2120665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21213deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2122665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21233deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21243deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21253deb3ec6SMatthias Ringwald         }
21263deb3ec6SMatthias Ringwald     }
21273deb3ec6SMatthias Ringwald 
21283deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21293deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2130092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2131092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2132adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21333deb3ec6SMatthias Ringwald             bd_addr_t addr;
21343deb3ec6SMatthias Ringwald             sm_key_t irk;
21353deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21363deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21373deb3ec6SMatthias Ringwald 
2138adf5eaa9SMatthias Ringwald             // skip unused entries
2139adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2140adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2141adf5eaa9SMatthias Ringwald                 continue;
2142adf5eaa9SMatthias Ringwald             }
2143adf5eaa9SMatthias Ringwald 
21445df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21453deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2146a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21473deb3ec6SMatthias Ringwald                 break;
21483deb3ec6SMatthias Ringwald             }
21493deb3ec6SMatthias Ringwald 
2150a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2151a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21523deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21533deb3ec6SMatthias Ringwald                 continue;
21543deb3ec6SMatthias Ringwald             }
21553deb3ec6SMatthias Ringwald 
21563deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21573deb3ec6SMatthias Ringwald 
21583deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21598314c363SMatthias Ringwald             log_info_key("IRK", irk);
21603deb3ec6SMatthias Ringwald 
21616535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2162d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21633deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2164d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2165d1a1f6a4SMatthias 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);
2166d7f1c72eSMatthias Ringwald             return true;
21673deb3ec6SMatthias Ringwald         }
21683deb3ec6SMatthias Ringwald 
2169092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
21703deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
21713deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
21723deb3ec6SMatthias Ringwald         }
21733deb3ec6SMatthias Ringwald     }
2174d7f1c72eSMatthias Ringwald     return false;
2175d7f1c72eSMatthias Ringwald }
21763deb3ec6SMatthias Ringwald 
2177d7f1c72eSMatthias Ringwald // SC OOB
2178d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2179c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2180c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2181c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2182c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2183c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2184c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2185d7f1c72eSMatthias Ringwald             return true;
2186c59d0c92SMatthias Ringwald         default:
2187c59d0c92SMatthias Ringwald             break;
2188c59d0c92SMatthias Ringwald     }
2189c59d0c92SMatthias Ringwald #endif
2190d7f1c72eSMatthias Ringwald     return false;
2191d7f1c72eSMatthias Ringwald }
2192275aafe8SMatthias Ringwald 
2193687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2194687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2195687a03c8SMatthias Ringwald }
2196687a03c8SMatthias Ringwald 
219741d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2198d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2199d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
220041d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2201e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
220241d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
220341d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
220441d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2205f4935286SMatthias Ringwald 
2206f4935286SMatthias Ringwald             // general
2207f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2208f4935286SMatthias Ringwald                 uint8_t buffer[2];
2209f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2210f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2211f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2212687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2213f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2214f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2215f4935286SMatthias Ringwald                 break;
2216f4935286SMatthias Ringwald             }
2217f4935286SMatthias Ringwald 
221841d32297SMatthias Ringwald             // responder side
221941d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
222041d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
222141d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2222d7f1c72eSMatthias Ringwald                 return true;
22234b8b5afeSMatthias Ringwald 
22244b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22254b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22264b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22274b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2228e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22294b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22304b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2231d7f1c72eSMatthias Ringwald                         return true;
22324b8b5afeSMatthias Ringwald                     default:
22334b8b5afeSMatthias Ringwald                         break;
22344b8b5afeSMatthias Ringwald                 }
22354b8b5afeSMatthias Ringwald                 break;
22364b8b5afeSMatthias Ringwald #endif
223741d32297SMatthias Ringwald             default:
223841d32297SMatthias Ringwald                 break;
223941d32297SMatthias Ringwald         }
224041d32297SMatthias Ringwald     }
2241d7f1c72eSMatthias Ringwald     return false;
2242d7f1c72eSMatthias Ringwald }
22433deb3ec6SMatthias Ringwald 
2244d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22453deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2246d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22473deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22487149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2249665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22503deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22513deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22521979f09cSMatthias Ringwald         bool done = true;
22533deb3ec6SMatthias Ringwald         int err;
225442134bc6SMatthias Ringwald         UNUSED(err);
225534b6528fSMatthias Ringwald 
225634b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
225734b6528fSMatthias Ringwald         // assert ec key is ready
2258505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2259178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2260178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
226134b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
226234b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
226334b6528fSMatthias Ringwald             }
226434b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
226534b6528fSMatthias Ringwald                 continue;
226634b6528fSMatthias Ringwald             }
226734b6528fSMatthias Ringwald         }
226834b6528fSMatthias Ringwald #endif
226934b6528fSMatthias Ringwald 
22703deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
227142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
22723deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
22733deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
227442134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2275549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
227606cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
227787014f74SMatthias Ringwald #endif
227887014f74SMatthias Ringwald #endif
227934c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
22805567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
228134c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2282549ad5d2SMatthias Ringwald #endif
228387014f74SMatthias Ringwald 				// just lock context
228487014f74SMatthias Ringwald 				break;
22853deb3ec6SMatthias Ringwald             default:
22861979f09cSMatthias Ringwald                 done = false;
22873deb3ec6SMatthias Ringwald                 break;
22883deb3ec6SMatthias Ringwald         }
22893deb3ec6SMatthias Ringwald         if (done){
22907149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
22917149bde5SMatthias 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);
22923deb3ec6SMatthias Ringwald         }
22933deb3ec6SMatthias Ringwald     }
2294d7f1c72eSMatthias Ringwald }
2295d7f1c72eSMatthias Ringwald 
2296403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2297403280b9SMatthias Ringwald     int i;
2298403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2299403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2300403280b9SMatthias Ringwald     uint8_t action = 0;
2301403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2302403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2303403280b9SMatthias Ringwald             bool clear_flag = true;
2304403280b9SMatthias Ringwald             switch (i){
2305403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2306403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2307403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2308403280b9SMatthias Ringwald                 default:
2309403280b9SMatthias Ringwald                     break;
2310403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2311403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2312403280b9SMatthias Ringwald                     num_actions--;
2313403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2314403280b9SMatthias Ringwald                     break;
2315403280b9SMatthias Ringwald             }
2316403280b9SMatthias Ringwald             if (clear_flag){
2317403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2318403280b9SMatthias Ringwald             }
2319403280b9SMatthias Ringwald             action = i;
2320403280b9SMatthias Ringwald             break;
2321403280b9SMatthias Ringwald         }
2322403280b9SMatthias Ringwald     }
2323403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2324403280b9SMatthias Ringwald 
2325403280b9SMatthias Ringwald     // send keypress notification
2326403280b9SMatthias Ringwald     uint8_t buffer[2];
2327403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2328403280b9SMatthias Ringwald     buffer[1] = action;
2329687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2330403280b9SMatthias Ringwald 
2331403280b9SMatthias Ringwald     // try
2332403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2333403280b9SMatthias Ringwald }
2334403280b9SMatthias Ringwald 
2335403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2336403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2337403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2338403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2339403280b9SMatthias Ringwald         uint8_t buffer[17];
2340403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2341403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2342687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2343403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2344403280b9SMatthias Ringwald         return;
2345403280b9SMatthias Ringwald     }
2346403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2347403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2348403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2349403280b9SMatthias Ringwald         uint8_t buffer[11];
2350403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2351403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2352403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2353687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2354403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2355403280b9SMatthias Ringwald         return;
2356403280b9SMatthias Ringwald     }
2357403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2358403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2359403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2360403280b9SMatthias Ringwald         uint8_t buffer[17];
2361403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2362403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2363687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2364403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2365403280b9SMatthias Ringwald         return;
2366403280b9SMatthias Ringwald     }
2367403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2368403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2369403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2370403280b9SMatthias Ringwald         bd_addr_t local_address;
2371403280b9SMatthias Ringwald         uint8_t buffer[8];
2372403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2373403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2374403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2375403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2376403280b9SMatthias Ringwald                 // public or static random
2377403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2378403280b9SMatthias Ringwald                 break;
2379403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2380403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2381403280b9SMatthias Ringwald                 // fallback to public
2382403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2383403280b9SMatthias Ringwald                 buffer[1] = 0;
2384403280b9SMatthias Ringwald                 break;
2385403280b9SMatthias Ringwald             default:
2386403280b9SMatthias Ringwald                 btstack_assert(false);
2387403280b9SMatthias Ringwald                 break;
2388403280b9SMatthias Ringwald         }
2389403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2390687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2391403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2392403280b9SMatthias Ringwald         return;
2393403280b9SMatthias Ringwald     }
2394403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2395403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2396403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2397403280b9SMatthias Ringwald 
2398403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2399403280b9SMatthias Ringwald         // hack to reproduce test runs
2400403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2401403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2402403280b9SMatthias Ringwald                     }
2403403280b9SMatthias Ringwald 
2404403280b9SMatthias Ringwald                     // store local CSRK
2405403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2406403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2407403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2408403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2409403280b9SMatthias Ringwald                     }
2410403280b9SMatthias Ringwald #endif
2411403280b9SMatthias Ringwald 
2412403280b9SMatthias Ringwald         uint8_t buffer[17];
2413403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2414403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2415687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2416403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2417403280b9SMatthias Ringwald         return;
2418403280b9SMatthias Ringwald     }
2419403280b9SMatthias Ringwald     btstack_assert(false);
2420403280b9SMatthias Ringwald }
2421403280b9SMatthias Ringwald 
2422bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2423bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2424bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2425bbd73538SMatthias Ringwald     // - use secure connections
2426bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2427bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2428bbd73538SMatthias 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;
2429bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2430bbd73538SMatthias Ringwald     // - need identity address / public addr
2431bbd73538SMatthias 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);
2432bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2433bbd73538SMatthias 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)
2434bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2435bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2436bbd73538SMatthias 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.
2437bbd73538SMatthias Ringwald     uint8_t link_key[16];
2438bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2439bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2440bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2441bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2442bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2443bbd73538SMatthias Ringwald         return false;
2444bbd73538SMatthias Ringwald     }
2445bbd73538SMatthias Ringwald     // get started (all of the above are true)
2446bbd73538SMatthias Ringwald     return true;
2447bbd73538SMatthias Ringwald #else
2448bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2449bbd73538SMatthias Ringwald 	return false;
2450bbd73538SMatthias Ringwald #endif
2451bbd73538SMatthias Ringwald }
2452bbd73538SMatthias Ringwald 
24536f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24546f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24556f7422f1SMatthias 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;
24566f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24576f7422f1SMatthias Ringwald     } else {
24586f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24596f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24606f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24616f7422f1SMatthias Ringwald     }
24626f7422f1SMatthias Ringwald }
24636f7422f1SMatthias Ringwald 
2464af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2465af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2466af7ef9d1SMatthias 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;
2467af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2468af7ef9d1SMatthias Ringwald     } else {
2469af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2470af7ef9d1SMatthias Ringwald     }
2471af7ef9d1SMatthias Ringwald }
2472af7ef9d1SMatthias Ringwald 
2473d7f1c72eSMatthias Ringwald static void sm_run(void){
2474d7f1c72eSMatthias Ringwald 
2475d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2476d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2477d7f1c72eSMatthias Ringwald 
2478d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2479d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2480d7f1c72eSMatthias Ringwald 
2481d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2482d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2483d7f1c72eSMatthias Ringwald 
2484d7f1c72eSMatthias Ringwald     bool done;
2485d7f1c72eSMatthias Ringwald 
2486d7f1c72eSMatthias Ringwald     //
2487d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2488d7f1c72eSMatthias Ringwald     //
2489d7f1c72eSMatthias Ringwald 
2490d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2491d7f1c72eSMatthias Ringwald     if (done) return;
2492d7f1c72eSMatthias Ringwald 
2493d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2494d7f1c72eSMatthias Ringwald     if (done) return;
2495d7f1c72eSMatthias Ringwald 
2496d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2497d7f1c72eSMatthias Ringwald     if (done) return;
2498d7f1c72eSMatthias Ringwald 
2499d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2500d7f1c72eSMatthias Ringwald     if (done) return;
2501d7f1c72eSMatthias Ringwald 
2502d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2503d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2504d7f1c72eSMatthias Ringwald 
2505d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2506d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2507d7f1c72eSMatthias Ringwald     if (done) return;
2508d7f1c72eSMatthias Ringwald 
2509d7f1c72eSMatthias Ringwald     //
2510d7f1c72eSMatthias Ringwald     // active connection handling
2511d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2512d7f1c72eSMatthias Ringwald 
2513d7f1c72eSMatthias Ringwald     while (true) {
2514d7f1c72eSMatthias Ringwald 
2515d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2516d7f1c72eSMatthias Ringwald 
2517d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25183deb3ec6SMatthias Ringwald 
25193deb3ec6SMatthias Ringwald         //
25203deb3ec6SMatthias Ringwald         // active connection handling
25213deb3ec6SMatthias Ringwald         //
25223deb3ec6SMatthias Ringwald 
25233cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25243cf37b8cSMatthias Ringwald         if (!connection) {
25253cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25263cf37b8cSMatthias Ringwald             return;
25273cf37b8cSMatthias Ringwald         }
25283cf37b8cSMatthias Ringwald 
25293deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25307149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25317149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25327149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2533b170b20fSMatthias Ringwald             return;
2534b170b20fSMatthias Ringwald         }
25353deb3ec6SMatthias Ringwald 
25363d7fe1e9SMatthias Ringwald         // send keypress notifications
2537dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2538403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2539d7471931SMatthias Ringwald             return;
25403d7fe1e9SMatthias Ringwald         }
25413d7fe1e9SMatthias Ringwald 
25423deb3ec6SMatthias Ringwald         int key_distribution_flags;
254342134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2544b6afa23eSMatthias Ringwald 		int err;
2545b6afa23eSMatthias Ringwald 		UNUSED(err);
25469b75de03SMatthias Ringwald         bool have_ltk;
25479b75de03SMatthias Ringwald         uint8_t ltk[16];
25483deb3ec6SMatthias Ringwald 
25493deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2550dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2551dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2552dd4a08fbSMatthias Ringwald         }
25533deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25543deb3ec6SMatthias Ringwald 
2555f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2556aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2557aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2558aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2559aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2560aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2561aec94140SMatthias Ringwald                 break;
2562688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2563688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2564688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2565688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2566688a08f9SMatthias Ringwald                 break;
2567dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2568dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2569dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2570dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2571dc300847SMatthias Ringwald                 break;
2572019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2573b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2574019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
25750346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
25760346c37cSMatthias Ringwald                 break;
25770346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2578b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25790346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
25800346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
25810346c37cSMatthias Ringwald                 break;
25820346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2583b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25840346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
25850346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
25860346c37cSMatthias Ringwald                 break;
25870346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2588b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25890346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
25900346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2591019005a0SMatthias Ringwald                 break;
2592bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2593b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2594bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2595b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2596bd57ffebSMatthias Ringwald                 break;
25976857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
259857132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
25992bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
260057132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
26012bacf595SMatthias Ringwald                 h6_calculate_ilk(connection);
26022bacf595SMatthias Ringwald                 break;
260357132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
26042bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
260557132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
26062bacf595SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
26072bacf595SMatthias Ringwald                 break;
260857132f12SMatthias Ringwald 			case SM_SC_W2_CALCULATE_ILK_USING_H7:
260957132f12SMatthias Ringwald 				if (!sm_cmac_ready()) break;
261057132f12SMatthias Ringwald 				connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
261157132f12SMatthias Ringwald 				h7_calculate_ilk(connection);
261257132f12SMatthias Ringwald 				break;
2613aec94140SMatthias Ringwald #endif
2614a756d52bSMatthias Ringwald #endif
261541d32297SMatthias Ringwald 
261642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26173deb3ec6SMatthias Ringwald             // initiator side
2618f32b7a88SMatthias Ringwald 
26195567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2620f32b7a88SMatthias Ringwald 				sm_reset_setup();
2621f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2622daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2623f32b7a88SMatthias Ringwald 
26243deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26259c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26265567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26273deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2628c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2629c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26303deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26313deb3ec6SMatthias Ringwald                 return;
26323deb3ec6SMatthias Ringwald             }
26333deb3ec6SMatthias Ringwald 
2634b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2635b26f445fSMatthias Ringwald 				sm_reset_setup();
2636b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2637b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2638d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2639b26f445fSMatthias Ringwald 
26401ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26413deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2642687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26433deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26443deb3ec6SMatthias Ringwald                 break;
264542134bc6SMatthias Ringwald #endif
26463deb3ec6SMatthias Ringwald 
264727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
264841d32297SMatthias Ringwald 
2649c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26501979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26511979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
265227c32905SMatthias Ringwald                 uint8_t buffer[65];
265327c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
265427c32905SMatthias Ringwald                 //
2655fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2656fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2657e53be891SMatthias Ringwald 
2658349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2659349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2660349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2661349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2662349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2663349d0adbSMatthias Ringwald                 }
2664349d0adbSMatthias Ringwald #endif
2665349d0adbSMatthias Ringwald 
266645a61d50SMatthias Ringwald                 // stk generation method
266745a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
266845a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
266945a61d50SMatthias Ringwald                     case JUST_WORKS:
267047fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
267142134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
267207036a04SMatthias Ringwald                             // responder
26731979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2674b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
267527c32905SMatthias Ringwald                         } else {
267607036a04SMatthias Ringwald                             // initiator
2677c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
267827c32905SMatthias Ringwald                         }
267945a61d50SMatthias Ringwald                         break;
268045a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
268145a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
268247fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
268307036a04SMatthias Ringwald                         // use random TK for display
26846535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
26856535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
268645a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
268707036a04SMatthias Ringwald 
268842134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
268945a61d50SMatthias Ringwald                             // responder
2690c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
269145a61d50SMatthias Ringwald                         } else {
269245a61d50SMatthias Ringwald                             // initiator
2693c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
269445a61d50SMatthias Ringwald                         }
26951979f09cSMatthias Ringwald                         trigger_user_response = true;
269645a61d50SMatthias Ringwald                         break;
269745a61d50SMatthias Ringwald                     case OOB:
269865a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269965a9a04eSMatthias Ringwald                             // responder
270065a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
270165a9a04eSMatthias Ringwald                         } else {
270265a9a04eSMatthias Ringwald                             // initiator
270365a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270465a9a04eSMatthias Ringwald                         }
270545a61d50SMatthias Ringwald                         break;
27067bbeb3adSMilanka Ringwald                     default:
27077bbeb3adSMilanka Ringwald                         btstack_assert(false);
27087bbeb3adSMilanka Ringwald                         break;
270945a61d50SMatthias Ringwald                 }
271045a61d50SMatthias Ringwald 
2711687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
271227c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2713644c6a1dSMatthias Ringwald 
2714b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2715644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2716644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2717644c6a1dSMatthias Ringwald                 }
2718b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2719b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2720b90c4e75SMatthias Ringwald                 }
272127c32905SMatthias Ringwald                 break;
272227c32905SMatthias Ringwald             }
2723c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2724e53be891SMatthias Ringwald                 uint8_t buffer[17];
2725e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27269af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
272742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2728c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2729e53be891SMatthias Ringwald                 } else {
2730c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2731e53be891SMatthias Ringwald                 }
2732687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2733e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2734e53be891SMatthias Ringwald                 break;
2735e53be891SMatthias Ringwald             }
2736c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2737e53be891SMatthias Ringwald                 uint8_t buffer[17];
2738e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2739e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27409d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27414ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
274240c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
274342134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
274445a61d50SMatthias Ringwald                         // responder
2745c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
274645a61d50SMatthias Ringwald                     } else {
274745a61d50SMatthias Ringwald                         // initiator
2748c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
274945a61d50SMatthias Ringwald                     }
275045a61d50SMatthias Ringwald                 } else {
275140c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
275242134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2753e53be891SMatthias Ringwald                         // responder
275447fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
275540c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2756901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27572886623dSMatthias Ringwald                         } else {
275840c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27592886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2760446a8c36SMatthias Ringwald                         }
2761e53be891SMatthias Ringwald                     } else {
2762136d331aSMatthias Ringwald                         // initiator
2763c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2764e53be891SMatthias Ringwald                     }
276545a61d50SMatthias Ringwald                 }
2766687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2767e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2768e53be891SMatthias Ringwald                 break;
2769e53be891SMatthias Ringwald             }
2770c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2771e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2772e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2773e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2774dc300847SMatthias Ringwald 
277542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2776c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2777e53be891SMatthias Ringwald                 } else {
2778c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2779e53be891SMatthias Ringwald                 }
2780e083ca23SMatthias Ringwald 
2781687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2782e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2783e53be891SMatthias Ringwald                 break;
2784e53be891SMatthias Ringwald             }
2785e53be891SMatthias Ringwald 
2786e53be891SMatthias Ringwald #endif
278742134bc6SMatthias Ringwald 
278842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2789dd12a62bSMatthias Ringwald 
279087014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
279187014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
279287014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2793687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2794c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
279587014f74SMatthias Ringwald 				break;
279687014f74SMatthias Ringwald 			}
279787014f74SMatthias Ringwald 
279838196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
279938196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
280038196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
280138196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
280238196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
280338196718SMatthias Ringwald 						// start using context by loading security info
280438196718SMatthias Ringwald 						sm_reset_setup();
280538196718SMatthias Ringwald 						sm_load_security_info(connection);
280638196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
280738196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
280838196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
280942646f38SMatthias Ringwald                             sm_reencryption_started(connection);
281038196718SMatthias Ringwald                             sm_trigger_run();
281138196718SMatthias Ringwald 							break;
281238196718SMatthias Ringwald 						}
281338196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
281438196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
281538196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
281638196718SMatthias Ringwald 						return;
281738196718SMatthias Ringwald 					default:
281838196718SMatthias Ringwald 						// just wait until IRK lookup is completed
281938196718SMatthias Ringwald 						break;
282038196718SMatthias Ringwald 				}
282138196718SMatthias Ringwald 				break;
282238196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
282338196718SMatthias Ringwald 
2824b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2825b6afa23eSMatthias Ringwald                 sm_reset_setup();
28269b75de03SMatthias Ringwald 
28279b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28289b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28299b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28309b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28319b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28329b75de03SMatthias Ringwald                         if (have_ltk){
28339b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
283419a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28359b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28369b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28379b75de03SMatthias Ringwald                         }
28389b75de03SMatthias Ringwald                         break;
28399b75de03SMatthias Ringwald                     default:
28409b75de03SMatthias Ringwald                         break;
28419b75de03SMatthias Ringwald                 }
28429b75de03SMatthias Ringwald 
2843b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2844d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
284539543d07SMatthias Ringwald 
2846b6afa23eSMatthias Ringwald 				// recover pairing request
2847b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2848b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2849b6afa23eSMatthias Ringwald 
2850b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2851b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2852b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2853b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2854b6afa23eSMatthias Ringwald                     }
2855b6afa23eSMatthias Ringwald #endif
28569305033eSMatthias Ringwald 				if (err != 0){
2857f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2858b6afa23eSMatthias Ringwald 					sm_trigger_run();
2859b6afa23eSMatthias Ringwald 					break;
2860b6afa23eSMatthias Ringwald 				}
2861b6afa23eSMatthias Ringwald 
2862b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2863b6afa23eSMatthias Ringwald 
2864b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2865b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2866b6afa23eSMatthias 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);
2867b6afa23eSMatthias Ringwald 					break;
2868b6afa23eSMatthias Ringwald 				}
2869b6afa23eSMatthias Ringwald 
2870b6afa23eSMatthias Ringwald 				/* fall through */
2871b6afa23eSMatthias Ringwald 
28723deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28731ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2874f55bd529SMatthias Ringwald 
2875f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28763deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28771ad129beSMatthias Ringwald 
2878f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2879f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2880f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2881f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2882f55bd529SMatthias Ringwald                 }
2883f55bd529SMatthias Ringwald #endif
2884f55bd529SMatthias Ringwald                 // setup in response
2885f55bd529SMatthias 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);
2886f55bd529SMatthias 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);
2887f55bd529SMatthias Ringwald 
2888f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
2889f55bd529SMatthias Ringwald                 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
2890f55bd529SMatthias Ringwald 
289127c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2892c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
28930b8af2a5SMatthias Ringwald                 } else {
28940b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
289527c32905SMatthias Ringwald                 }
28960b8af2a5SMatthias Ringwald 
2897687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
28983deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2899446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2900c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29013deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2902446a8c36SMatthias Ringwald                 }
29033deb3ec6SMatthias Ringwald                 return;
290442134bc6SMatthias Ringwald #endif
29053deb3ec6SMatthias Ringwald 
29063deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29073deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29083deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29099c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
291042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29113deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29123deb3ec6SMatthias Ringwald                 } else {
29133deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29143deb3ec6SMatthias Ringwald                 }
2915687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29163deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29173deb3ec6SMatthias Ringwald                 break;
29183deb3ec6SMatthias Ringwald             }
29193deb3ec6SMatthias Ringwald 
2920d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29213deb3ec6SMatthias Ringwald                 // already busy?
29223deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2923d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2924d1a1f6a4SMatthias 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);
2925d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2926d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2927f3582630SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_a, (void *)(uintptr_t) connection->sm_handle);
29283deb3ec6SMatthias Ringwald                 break;
29293deb3ec6SMatthias Ringwald 
29303deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29313deb3ec6SMatthias Ringwald                 // already busy?
29323deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29333deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2934d1a1f6a4SMatthias 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);
2935d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2936d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2937f3582630SMatthias 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);
29383deb3ec6SMatthias Ringwald                 break;
2939d1a1f6a4SMatthias Ringwald 
29403deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29413deb3ec6SMatthias Ringwald                 // already busy?
29423deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29433deb3ec6SMatthias Ringwald                 // calculate STK
294442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2945d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29463deb3ec6SMatthias Ringwald                 } else {
2947d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29483deb3ec6SMatthias Ringwald                 }
2949d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2950d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2951f3582630SMatthias 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);
29523deb3ec6SMatthias Ringwald                 break;
2953d1a1f6a4SMatthias Ringwald 
29543deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29553deb3ec6SMatthias Ringwald                 // already busy?
29563deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29573deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29589ad0dd7cSMatthias Ringwald 
29599ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29609ad0dd7cSMatthias Ringwald                 // r' = padding || r
29619ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29629ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29636535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29649ad0dd7cSMatthias Ringwald 
29653deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2966d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2967d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2968f3582630SMatthias 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);
2969d1a1f6a4SMatthias Ringwald                 break;
2970d1a1f6a4SMatthias Ringwald 
29713deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29723deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29733deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29749c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
297542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29763deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29773deb3ec6SMatthias Ringwald                 } else {
29783deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
29793deb3ec6SMatthias Ringwald                 }
2980687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29813deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29823deb3ec6SMatthias Ringwald                 return;
29833deb3ec6SMatthias Ringwald             }
298442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
29853deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
29863deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
29879c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
29883deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
29893deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
29903deb3ec6SMatthias Ringwald                 return;
29913deb3ec6SMatthias Ringwald             }
2992d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
29933deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
29949c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
29955567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
29963deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
29973deb3ec6SMatthias Ringwald                 return;
29983deb3ec6SMatthias Ringwald             }
2999dd12a62bSMatthias Ringwald 
3000dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30013deb3ec6SMatthias Ringwald                 // already busy?
30023deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30033deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3004c61cfe5aSMatthias Ringwald 
3005dd12a62bSMatthias Ringwald 				sm_reset_setup();
3006dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3007dd12a62bSMatthias Ringwald 
300842646f38SMatthias Ringwald 				sm_reencryption_started(connection);
300942646f38SMatthias Ringwald 
3010c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3011c61cfe5aSMatthias Ringwald                 // r' = padding || r
3012c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3013c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30146535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3015c61cfe5aSMatthias Ringwald 
30163deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3017d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3018d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3019f3582630SMatthias 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);
30203deb3ec6SMatthias Ringwald                 return;
302142134bc6SMatthias Ringwald #endif
302242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
302342134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
302442134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
302542134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
302642134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
302742134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
302842134bc6SMatthias Ringwald                 return;
302942134bc6SMatthias Ringwald             }
303042134bc6SMatthias Ringwald #endif
30313deb3ec6SMatthias Ringwald 
30323deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3033403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3034403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30353deb3ec6SMatthias Ringwald                     return;
30363deb3ec6SMatthias Ringwald                 }
30373deb3ec6SMatthias Ringwald 
30383deb3ec6SMatthias Ringwald                 // keys are sent
303942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30403deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
30413deb3ec6SMatthias Ringwald                     if (sm_key_distribution_all_received(connection)){
30423deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3043f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3044f5020412SMatthias Ringwald                         // start CTKD right away
3045f5020412SMatthias Ringwald                         continue;
30463deb3ec6SMatthias Ringwald                     } else {
30473deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30483deb3ec6SMatthias Ringwald                     }
30493deb3ec6SMatthias Ringwald                 } else {
30501dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30513deb3ec6SMatthias Ringwald                 }
30523deb3ec6SMatthias Ringwald                 break;
30533deb3ec6SMatthias Ringwald 
30543deb3ec6SMatthias Ringwald             default:
30553deb3ec6SMatthias Ringwald                 break;
30563deb3ec6SMatthias Ringwald         }
30573deb3ec6SMatthias Ringwald 
30583deb3ec6SMatthias Ringwald         // check again if active connection was released
30597149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
30603deb3ec6SMatthias Ringwald     }
30613deb3ec6SMatthias Ringwald }
30623deb3ec6SMatthias Ringwald 
3063d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3064d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3065f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
306604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
306704678764SMatthias Ringwald 
3068f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3069f3582630SMatthias Ringwald     if (connection == NULL) return;
3070f3582630SMatthias Ringwald 
3071d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
307204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3073f3582630SMatthias 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);
3074d1a1f6a4SMatthias Ringwald }
30753deb3ec6SMatthias Ringwald 
3076d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3077f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
307804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
307904678764SMatthias Ringwald 
3080f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3081f3582630SMatthias Ringwald     if (connection == NULL) return;
3082f3582630SMatthias Ringwald 
30838314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
30843deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
308570b44dd4SMatthias Ringwald     sm_trigger_run();
3086d1a1f6a4SMatthias Ringwald }
3087d1a1f6a4SMatthias Ringwald 
3088d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3089d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3090f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
309104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
309204678764SMatthias Ringwald 
3093f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3094f3582630SMatthias Ringwald     if (connection == NULL) return;
3095f3582630SMatthias Ringwald 
3096d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
309704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3098f3582630SMatthias 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);
3099d1a1f6a4SMatthias Ringwald }
3100d1a1f6a4SMatthias Ringwald 
3101d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3102f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
310304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
310404678764SMatthias Ringwald 
3105f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3106f3582630SMatthias Ringwald     if (connection == NULL) return;
3107f3582630SMatthias Ringwald 
3108d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3109d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3110f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
311170b44dd4SMatthias Ringwald         sm_trigger_run();
31123deb3ec6SMatthias Ringwald         return;
31133deb3ec6SMatthias Ringwald     }
311442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31153deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
311670b44dd4SMatthias Ringwald         sm_trigger_run();
31173deb3ec6SMatthias Ringwald     } else {
3118d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3119d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3120f3582630SMatthias 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);
31213deb3ec6SMatthias Ringwald     }
31223deb3ec6SMatthias Ringwald }
3123d1a1f6a4SMatthias Ringwald 
3124d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
312504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3126f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
312704678764SMatthias Ringwald 
3128f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3129f3582630SMatthias Ringwald     if (connection == NULL) return;
3130f3582630SMatthias Ringwald 
31313deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
31328314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
313342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31343deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
31353deb3ec6SMatthias Ringwald     } else {
31363deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
31373deb3ec6SMatthias Ringwald     }
313870b44dd4SMatthias Ringwald     sm_trigger_run();
3139d1a1f6a4SMatthias Ringwald }
3140d1a1f6a4SMatthias Ringwald 
3141d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3142d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3143f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
314404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
314504678764SMatthias Ringwald 
3146f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3147f3582630SMatthias Ringwald     if (connection == NULL) return;
3148f3582630SMatthias Ringwald 
3149d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31503deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31513deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
31523deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
31533deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31543deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31553deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3156d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
315704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3158f3582630SMatthias 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);
31593deb3ec6SMatthias Ringwald }
3160d1a1f6a4SMatthias Ringwald 
31612a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3162d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3163d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
316404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3165f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
316604678764SMatthias Ringwald 
3167f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3168f3582630SMatthias Ringwald     if (connection == NULL) return;
3169f3582630SMatthias Ringwald 
3170d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31713deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31723deb3ec6SMatthias Ringwald 
31733deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
31743deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
31753deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31763deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31773deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3178d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
317904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3180f3582630SMatthias 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);
31813deb3ec6SMatthias Ringwald }
31822a526f21SMatthias Ringwald #endif
3183d1a1f6a4SMatthias Ringwald 
3184d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3185d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3186f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
318704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
318804678764SMatthias Ringwald 
3189f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3190f3582630SMatthias Ringwald     if (connection == NULL) return;
3191f3582630SMatthias Ringwald 
31928314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
31933deb3ec6SMatthias Ringwald     // calc CSRK next
3194d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
319504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3196f3582630SMatthias 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);
3197d1a1f6a4SMatthias Ringwald }
3198d1a1f6a4SMatthias Ringwald 
3199d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3200f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
320104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
320204678764SMatthias Ringwald 
3203f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3204f3582630SMatthias Ringwald     if (connection == NULL) return;
3205f3582630SMatthias Ringwald 
3206d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
32078314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
32083deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
32093deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
32103deb3ec6SMatthias Ringwald     } else {
32113deb3ec6SMatthias Ringwald         // no keys to send, just continue
321242134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3213c5a72e35SMatthias Ringwald             if (sm_key_distribution_all_received(connection)){
3214c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3215c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3216c5a72e35SMatthias Ringwald             } else {
32173deb3ec6SMatthias Ringwald                 // slave -> receive master keys
32183deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3219c5a72e35SMatthias Ringwald             }
32203deb3ec6SMatthias Ringwald         } else {
3221af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
32223deb3ec6SMatthias Ringwald         }
32232bacf595SMatthias Ringwald     }
322470b44dd4SMatthias Ringwald     sm_trigger_run();
3225d1a1f6a4SMatthias Ringwald }
3226d1a1f6a4SMatthias Ringwald 
322742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3228d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3229f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323104678764SMatthias Ringwald 
3232f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3233f3582630SMatthias Ringwald     if (connection == NULL) return;
3234f3582630SMatthias Ringwald 
32353deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32368314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3237d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
323870b44dd4SMatthias Ringwald     sm_trigger_run();
3239d1a1f6a4SMatthias Ringwald }
3240d1a1f6a4SMatthias Ringwald #endif
3241d1a1f6a4SMatthias Ringwald 
3242d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3243d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3244d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324504678764SMatthias Ringwald 
3246d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3247d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3248d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3249d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3250d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3251a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
325270b44dd4SMatthias Ringwald         sm_trigger_run();
32533deb3ec6SMatthias Ringwald         return;
32543deb3ec6SMatthias Ringwald     }
3255d1a1f6a4SMatthias Ringwald     // no match, try next
3256d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
325770b44dd4SMatthias Ringwald     sm_trigger_run();
32583deb3ec6SMatthias Ringwald }
32593deb3ec6SMatthias Ringwald 
3260d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3261d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3262d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326304678764SMatthias Ringwald 
3264d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3265d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
326670b44dd4SMatthias Ringwald     sm_trigger_run();
32677df18c15SMatthias Ringwald }
3268d1a1f6a4SMatthias Ringwald 
3269d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3270d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3271d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327204678764SMatthias Ringwald 
3273d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3274d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
327570b44dd4SMatthias Ringwald     sm_trigger_run();
32767df18c15SMatthias Ringwald }
3277d1a1f6a4SMatthias Ringwald 
3278d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3279d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3280d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
328104678764SMatthias Ringwald 
32826535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3283d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
328470b44dd4SMatthias Ringwald     sm_trigger_run();
328551fa0b28SMatthias Ringwald }
32867df18c15SMatthias Ringwald 
3287d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3288d1a1f6a4SMatthias Ringwald     UNUSED(arg);
32893deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
32903deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
32913deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
32923deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
32933deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
32944ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
32954ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
32963deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
32973deb3ec6SMatthias Ringwald             break;
32983deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
32993deb3ec6SMatthias Ringwald         default:
33003deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
33014ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33023deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
33033deb3ec6SMatthias Ringwald             break;
33043deb3ec6SMatthias Ringwald     }
330570b44dd4SMatthias Ringwald     sm_trigger_run();
33063deb3ec6SMatthias Ringwald }
33073deb3ec6SMatthias Ringwald 
3308c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
33096ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3310f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3311f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3312f3582630SMatthias Ringwald     if (connection == NULL) return;
3313c59d0c92SMatthias Ringwald 
331465a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
331570b44dd4SMatthias Ringwald     sm_trigger_run();
331665a9a04eSMatthias Ringwald }
3317d1a1f6a4SMatthias Ringwald 
33186ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
33196ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
33206ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
33216ca80073SMatthias Ringwald     if (connection == NULL) return;
33226ca80073SMatthias Ringwald 
3323b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
332470b44dd4SMatthias Ringwald     sm_trigger_run();
3325d1a1f6a4SMatthias Ringwald }
3326f1c1783eSMatthias Ringwald #endif
3327f1c1783eSMatthias Ringwald 
3328d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3329f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3330f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3331f3582630SMatthias Ringwald     if (connection == NULL) return;
3332f3582630SMatthias Ringwald 
3333d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
333470b44dd4SMatthias Ringwald     sm_trigger_run();
3335d1a1f6a4SMatthias Ringwald }
3336d1a1f6a4SMatthias Ringwald 
3337d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3338f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3339f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3340f3582630SMatthias Ringwald     if (connection == NULL) return;
3341f3582630SMatthias Ringwald 
3342caf15bf3SMatthias Ringwald     sm_reset_tk();
3343caf15bf3SMatthias Ringwald     uint32_t tk;
33445ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
33453deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3346d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
33473deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
33484ea43905SMatthias Ringwald         if (tk >= 999999u){
33494ea43905SMatthias Ringwald             tk = tk - 999999u;
33503deb3ec6SMatthias Ringwald         }
3351caf15bf3SMatthias Ringwald     } else {
3352caf15bf3SMatthias Ringwald         // override with pre-defined passkey
33534b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3354caf15bf3SMatthias Ringwald     }
3355f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
335642134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33573deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
33583deb3ec6SMatthias Ringwald     } else {
3359b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3360b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3361b41539d5SMatthias Ringwald         } else {
33623deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
33633deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
33643deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
33653deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3366f3582630SMatthias 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);
33673deb3ec6SMatthias Ringwald             }
33683deb3ec6SMatthias Ringwald         }
3369b41539d5SMatthias Ringwald     }
337070b44dd4SMatthias Ringwald     sm_trigger_run();
33713deb3ec6SMatthias Ringwald }
3372d1a1f6a4SMatthias Ringwald 
3373d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3374f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3375f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3376f3582630SMatthias Ringwald     if (connection == NULL) return;
3377f3582630SMatthias Ringwald 
3378d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3379d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3380d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3381d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
338270b44dd4SMatthias Ringwald     sm_trigger_run();
3383d1a1f6a4SMatthias Ringwald }
3384d1a1f6a4SMatthias Ringwald 
3385d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3386f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3387f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3388f3582630SMatthias Ringwald     if (connection == NULL) return;
3389f3582630SMatthias Ringwald 
3390d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
33913deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
33924ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
33933deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
33944ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
33958b3ffec5SMatthias 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);
33963deb3ec6SMatthias Ringwald }
3397899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3398899e6e02SMatthias Ringwald     // warn about default ER/IR
33991979f09cSMatthias Ringwald     bool warning = false;
3400899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
34011979f09cSMatthias Ringwald         warning = true;
3402899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3403899e6e02SMatthias Ringwald     }
3404899e6e02SMatthias Ringwald     if (sm_er_is_default()){
34051979f09cSMatthias Ringwald         warning = true;
3406899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3407899e6e02SMatthias Ringwald     }
340821045273SMatthias Ringwald     if (warning) {
3409899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3410899e6e02SMatthias Ringwald     }
341121045273SMatthias Ringwald }
3412899e6e02SMatthias Ringwald 
3413899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
34141979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34159305033eSMatthias Ringwald     if (arg != NULL){
3416899e6e02SMatthias Ringwald         // key generated, store in tlv
34174ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3418899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3419e0d13a19SMilanka Ringwald         UNUSED(status);
3420899e6e02SMatthias Ringwald     }
3421899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
34228d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3423841468bbSMatthias Ringwald 
3424841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3425841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3426841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3427841468bbSMatthias Ringwald     }
3428841468bbSMatthias Ringwald 
342970b44dd4SMatthias Ringwald     sm_trigger_run();
3430899e6e02SMatthias Ringwald }
3431899e6e02SMatthias Ringwald 
3432899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
34331979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34349305033eSMatthias Ringwald     if (arg != 0){
3435899e6e02SMatthias Ringwald         // key generated, store in tlv
34364ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3437899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3438e0d13a19SMilanka Ringwald         UNUSED(status);
3439899e6e02SMatthias Ringwald     }
3440899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3441899e6e02SMatthias Ringwald 
3442899e6e02SMatthias Ringwald     // try load ir
34434ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3444899e6e02SMatthias Ringwald     if (key_size == 16){
3445899e6e02SMatthias Ringwald         // ok, let's continue
3446899e6e02SMatthias Ringwald         log_info("IR from TLV");
3447899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3448899e6e02SMatthias Ringwald     } else {
3449899e6e02SMatthias Ringwald         // invalid, generate new random one
34501979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3451899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3452899e6e02SMatthias Ringwald     }
3453899e6e02SMatthias Ringwald }
34543deb3ec6SMatthias Ringwald 
3455f664b5e8SMatthias 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){
3456f664b5e8SMatthias Ringwald 
3457f664b5e8SMatthias Ringwald     // connection info
3458f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3459f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3460f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3461f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3462f664b5e8SMatthias Ringwald 
3463f664b5e8SMatthias Ringwald     // security properties
3464f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3465f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3466f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3467f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3468f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3469f664b5e8SMatthias Ringwald 
3470f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3471f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3472f664b5e8SMatthias Ringwald 
3473f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3474f664b5e8SMatthias Ringwald }
3475f664b5e8SMatthias Ringwald 
3476d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
34773deb3ec6SMatthias Ringwald 
3478cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3479cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
34809ec2630cSMatthias Ringwald 
34813deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3482711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3483fbe050beSMatthias Ringwald     uint8_t           status;
3484f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3485f664b5e8SMatthias Ringwald 
34863deb3ec6SMatthias Ringwald     switch (packet_type) {
34873deb3ec6SMatthias Ringwald 
34883deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
34890e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
34903deb3ec6SMatthias Ringwald 
34913deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
34923deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3493be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
34943deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3495899e6e02SMatthias Ringwald 
3496899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3497899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
34989305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
34994ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3500899e6e02SMatthias Ringwald                             if (key_size == 16){
3501899e6e02SMatthias Ringwald                                 // ok, let's continue
3502899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3503899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3504899e6e02SMatthias Ringwald                             } else {
3505899e6e02SMatthias Ringwald                                 // invalid, generate random one
35061979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3507899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3508899e6e02SMatthias Ringwald                             }
3509899e6e02SMatthias Ringwald                         } else {
3510899e6e02SMatthias Ringwald                             sm_validate_er_ir();
35118d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3512841468bbSMatthias Ringwald 
3513841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3514841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3515841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3516841468bbSMatthias Ringwald                             }
3517899e6e02SMatthias Ringwald                         }
35181bf086daSMatthias Ringwald 
35191bf086daSMatthias Ringwald                         // restart random address updates after power cycle
35201bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
35213deb3ec6SMatthias Ringwald 					}
35223deb3ec6SMatthias Ringwald 					break;
35232d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
35242d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
35252d095694SMatthias Ringwald 			        // ignore if connection failed
35262d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
35273deb3ec6SMatthias Ringwald 
35282d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
35292d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
35302d095694SMatthias Ringwald 			        if (!sm_conn) break;
35312d095694SMatthias Ringwald 
35322d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
35332d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
35342d095694SMatthias Ringwald                                        con_handle,
35352d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3536*f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
35372d095694SMatthias Ringwald                                        addr);
35382d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
35392d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
35402d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
35412d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
35422d095694SMatthias Ringwald 			        break;
35432d095694SMatthias Ringwald #endif
35443deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
35453deb3ec6SMatthias Ringwald                     switch (packet[2]) {
35463deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3547f664b5e8SMatthias Ringwald                             // ignore if connection failed
3548f664b5e8SMatthias Ringwald                             if (packet[3]) return;
35493deb3ec6SMatthias Ringwald 
3550711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3551711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35523deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35533deb3ec6SMatthias Ringwald 
3554f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3555f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3556f664b5e8SMatthias Ringwald                                                con_handle,
3557f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3558f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3559f664b5e8SMatthias Ringwald                                                addr);
3560687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3561f664b5e8SMatthias Ringwald 
3562f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3563f664b5e8SMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet)){
3564ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3565ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3566f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3567ba9fc867SMatthias Ringwald                             } else {
3568ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3569ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
35703deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
35713deb3ec6SMatthias Ringwald                             }
35723deb3ec6SMatthias Ringwald                             break;
35733deb3ec6SMatthias Ringwald 
35743deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3575711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3576711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35773deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35783deb3ec6SMatthias Ringwald 
35793deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
35803deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
35813deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
35823deb3ec6SMatthias Ringwald                                 break;
35833deb3ec6SMatthias Ringwald                             }
3584c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3585778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3586778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3587e53be891SMatthias Ringwald                                 break;
3588e53be891SMatthias Ringwald                             }
35893deb3ec6SMatthias Ringwald 
35903deb3ec6SMatthias Ringwald                             // store rand and ediv
35919c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3592f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3593549ad5d2SMatthias Ringwald 
3594549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3595549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
35964ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
35976c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
359806cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3599549ad5d2SMatthias Ringwald                                     break;
3600549ad5d2SMatthias Ringwald                                 }
36016c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
36026c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
36036c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
36046c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
36056c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
36066c39055aSMatthias Ringwald                                         break;
36076c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
36086c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
36096c39055aSMatthias Ringwald                                         break;
36106c39055aSMatthias Ringwald                                     default:
36116c39055aSMatthias Ringwald                                         // wait for irk look doen
36126c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
36136c39055aSMatthias Ringwald                                         break;
36146c39055aSMatthias Ringwald                                 }
36156c39055aSMatthias Ringwald                                 break;
36166c39055aSMatthias Ringwald                             }
3617549ad5d2SMatthias Ringwald 
3618549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
361906cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3620549ad5d2SMatthias Ringwald #else
3621549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3622549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3623549ad5d2SMatthias Ringwald #endif
36243deb3ec6SMatthias Ringwald                             break;
3625804d3e67SMatthias Ringwald 
36263deb3ec6SMatthias Ringwald                         default:
36273deb3ec6SMatthias Ringwald                             break;
36283deb3ec6SMatthias Ringwald                     }
36293deb3ec6SMatthias Ringwald                     break;
36303deb3ec6SMatthias Ringwald 
36313deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
36323b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3633711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36343deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36353deb3ec6SMatthias Ringwald 
36363b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
36373deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
36383deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
36393deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
364003a9359aSMatthias Ringwald 
3641fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3642fbe050beSMatthias Ringwald 
36435567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
364403a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3645fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3646fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
36478d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
36488d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36498d4eef95SMatthias Ringwald                                 } else {
365003a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36518d4eef95SMatthias Ringwald                                 }
3652fbe050beSMatthias Ringwald                             } else {
3653e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3654cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
36553b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3656cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
36573b7fd749SMatthias Ringwald                             }
3658fbe050beSMatthias Ringwald 
3659fbe050beSMatthias Ringwald                             // emit re-encryption complete
366073102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3661fbe050beSMatthias Ringwald 
3662c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3663c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3664c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
36650ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
366603a9359aSMatthias Ringwald                             }
366703a9359aSMatthias Ringwald 
36683deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
36693deb3ec6SMatthias Ringwald                             break;
3670fbe050beSMatthias Ringwald 
36713deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3672fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3673dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
367442134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
36753deb3ec6SMatthias Ringwald                                 // slave
3676bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3677bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3678bbf8db22SMatthias Ringwald                                 } else {
3679f3582630SMatthias 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);
3680bbf8db22SMatthias Ringwald                                 }
36813deb3ec6SMatthias Ringwald                             } else {
36823deb3ec6SMatthias Ringwald                                 // master
36833deb3ec6SMatthias Ringwald                                 if (sm_key_distribution_all_received(sm_conn)){
36843deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
36853deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3686f3582630SMatthias 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);
36873deb3ec6SMatthias Ringwald                                 } else {
36883deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
36893deb3ec6SMatthias Ringwald                                 }
36903deb3ec6SMatthias Ringwald                             }
36913deb3ec6SMatthias Ringwald                             break;
36923deb3ec6SMatthias Ringwald                         default:
36933deb3ec6SMatthias Ringwald                             break;
36943deb3ec6SMatthias Ringwald                     }
36953deb3ec6SMatthias Ringwald                     break;
36963deb3ec6SMatthias Ringwald 
36973deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3698711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3699711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37003deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37013deb3ec6SMatthias Ringwald 
37023deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
37033deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
37043deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
37053deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37065567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
37075567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
37085567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
37095567aa60SMatthias Ringwald                             } else {
37103deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37115567aa60SMatthias Ringwald                             }
37123deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
37133deb3ec6SMatthias Ringwald                             break;
37143deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
371542134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
37163deb3ec6SMatthias Ringwald                                 // slave
3717f3582630SMatthias 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);
37183deb3ec6SMatthias Ringwald                             } else {
37193deb3ec6SMatthias Ringwald                                 // master
37203deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
37213deb3ec6SMatthias Ringwald                             }
37223deb3ec6SMatthias Ringwald                             break;
37233deb3ec6SMatthias Ringwald                         default:
37243deb3ec6SMatthias Ringwald                             break;
37253deb3ec6SMatthias Ringwald                     }
37263deb3ec6SMatthias Ringwald                     break;
37273deb3ec6SMatthias Ringwald 
37283deb3ec6SMatthias Ringwald 
37293deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3730711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3731711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3732711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37333deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37343deb3ec6SMatthias Ringwald 
373503f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
37367f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37377f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
37387f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
37397f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
37407f3f442dSMatthias Ringwald                             break;
37417f3f442dSMatthias Ringwald                         default:
374268a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37430ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
37447f3f442dSMatthias Ringwald                             break;
374503f736b1SMatthias Ringwald                     }
3746accbde80SMatthias Ringwald 
37473deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
37483deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
37493deb3ec6SMatthias Ringwald                     break;
37503deb3ec6SMatthias Ringwald 
37513deb3ec6SMatthias Ringwald 				case HCI_EVENT_COMMAND_COMPLETE:
375233373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
37539091c5f5SMatthias Ringwald                         // set local addr for le device db
375433373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
37550c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
375633373e40SMatthias Ringwald                     }
375765b44ffdSMatthias Ringwald                     break;
375865b44ffdSMatthias Ringwald                 default:
375965b44ffdSMatthias Ringwald                     break;
37603deb3ec6SMatthias Ringwald 			}
376165b44ffdSMatthias Ringwald             break;
376265b44ffdSMatthias Ringwald         default:
376365b44ffdSMatthias Ringwald             break;
37643deb3ec6SMatthias Ringwald 	}
37653deb3ec6SMatthias Ringwald 
37663deb3ec6SMatthias Ringwald     sm_run();
37673deb3ec6SMatthias Ringwald }
37683deb3ec6SMatthias Ringwald 
37693deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
37703deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
37713deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
37723deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
37733deb3ec6SMatthias Ringwald }
37743deb3ec6SMatthias Ringwald 
3775945888f5SMatthias Ringwald 
377631c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3777945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3778945888f5SMatthias Ringwald     switch (method){
3779945888f5SMatthias Ringwald         case JUST_WORKS:
378047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3781945888f5SMatthias Ringwald             return 1;
3782945888f5SMatthias Ringwald         default:
3783945888f5SMatthias Ringwald             return 0;
3784945888f5SMatthias Ringwald     }
3785945888f5SMatthias Ringwald }
378607036a04SMatthias Ringwald // responder
3787945888f5SMatthias Ringwald 
3788688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3789688a08f9SMatthias Ringwald     switch (method){
3790688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3791688a08f9SMatthias Ringwald             return 1;
3792688a08f9SMatthias Ringwald         default:
3793688a08f9SMatthias Ringwald             return 0;
3794688a08f9SMatthias Ringwald     }
3795688a08f9SMatthias Ringwald }
379640c5d850SMatthias Ringwald 
379740c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
379840c5d850SMatthias Ringwald     switch (method){
379940c5d850SMatthias Ringwald         case PK_RESP_INPUT:
380040c5d850SMatthias Ringwald         case PK_INIT_INPUT:
380147fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
380240c5d850SMatthias Ringwald             return 1;
380340c5d850SMatthias Ringwald         default:
380440c5d850SMatthias Ringwald             return 0;
380540c5d850SMatthias Ringwald     }
380640c5d850SMatthias Ringwald }
380740c5d850SMatthias Ringwald 
380831c09488SMatthias Ringwald #endif
3809688a08f9SMatthias Ringwald 
38103deb3ec6SMatthias Ringwald /**
38113deb3ec6SMatthias Ringwald  * @return ok
38123deb3ec6SMatthias Ringwald  */
38133deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
38143deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
38153deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
38163deb3ec6SMatthias Ringwald         case JUST_WORKS:
38174ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
38183deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
38193deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
382047fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
38214ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
38223deb3ec6SMatthias Ringwald         case OOB:
38234ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
382447fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
38254ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
38263deb3ec6SMatthias Ringwald         default:
38273deb3ec6SMatthias Ringwald             return 0;
38283deb3ec6SMatthias Ringwald     }
38293deb3ec6SMatthias Ringwald }
38303deb3ec6SMatthias Ringwald 
38318334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
38328334d3d8SMatthias Ringwald 
38334c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
38344c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
38354c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
38364c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
38374c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
38384c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
38394c1d1092SMatthias Ringwald             17, // 0x04 pairing random
38404c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
38414c1d1092SMatthias Ringwald             17, // 0x06 encryption information
38427a2e6387SMatthias Ringwald             11, // 0x07 master identification
38434c1d1092SMatthias Ringwald             17, // 0x08 identification information
38444c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
38454c1d1092SMatthias Ringwald             17, // 0x0a signing information
38464c1d1092SMatthias Ringwald             2,  // 0x0b security request
38474c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
38484c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
38494c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
38504c1d1092SMatthias Ringwald     };
38513deb3ec6SMatthias Ringwald 
3852c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3853b170b20fSMatthias Ringwald         sm_run();
3854b170b20fSMatthias Ringwald     }
3855b170b20fSMatthias Ringwald 
38563deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
38574ea43905SMatthias Ringwald     if (size == 0u) return;
38584c1d1092SMatthias Ringwald 
38594c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
38604c1d1092SMatthias Ringwald 
38614c1d1092SMatthias Ringwald     // validate pdu size
38624c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
38637a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
38643deb3ec6SMatthias Ringwald 
3865711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
38663deb3ec6SMatthias Ringwald     if (!sm_conn) return;
38673deb3ec6SMatthias Ringwald 
38684c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
386968a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
38700ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3871accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
38723deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
38733deb3ec6SMatthias Ringwald         return;
38743deb3ec6SMatthias Ringwald     }
38753deb3ec6SMatthias Ringwald 
38764c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
38773deb3ec6SMatthias Ringwald 
38783deb3ec6SMatthias Ringwald     int err;
387942134bc6SMatthias Ringwald     UNUSED(err);
38803deb3ec6SMatthias Ringwald 
38814c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
38823d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
38833d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
38843d7fe1e9SMatthias Ringwald         buffer[1] = 3;
38853d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
38863d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
38873d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
38883d7fe1e9SMatthias Ringwald         return;
38893d7fe1e9SMatthias Ringwald     }
38903d7fe1e9SMatthias Ringwald 
3891a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
3892212d735eSMatthias Ringwald     int have_ltk;
3893212d735eSMatthias Ringwald     uint8_t ltk[16];
3894a6ca6916SDavid Lechner #endif
3895212d735eSMatthias Ringwald 
38963deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
38973deb3ec6SMatthias Ringwald 
3898c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
38993deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
39003deb3ec6SMatthias Ringwald             return;
39013deb3ec6SMatthias Ringwald 
390242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
390342134bc6SMatthias Ringwald 
39043deb3ec6SMatthias Ringwald         // Initiator
39053deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
39064c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
39073deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39083deb3ec6SMatthias Ringwald                 break;
39093deb3ec6SMatthias Ringwald             }
391034c39fbdSMatthias Ringwald 
39112c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
39122c041b42SMatthias Ringwald             if (sm_sc_only_mode){
39132c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
39142c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
3915f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
39162c041b42SMatthias Ringwald                     break;
39172c041b42SMatthias Ringwald                 }
39182c041b42SMatthias Ringwald             }
39192c041b42SMatthias Ringwald #endif
39202c041b42SMatthias Ringwald 
392134c39fbdSMatthias Ringwald             // IRK complete?
392234c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
392334c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
3924dc8ca372SMatthias Ringwald                     // start pairing
39253deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
39263deb3ec6SMatthias Ringwald                     break;
3927e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
3928e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3929e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
39308549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
39318549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
39328549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
39335567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
3934e061bbd4SMatthias Ringwald                     } else {
3935dc8ca372SMatthias Ringwald                         // start pairing
3936e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3937e061bbd4SMatthias Ringwald                     }
3938e061bbd4SMatthias Ringwald                     break;
393934c39fbdSMatthias Ringwald                 default:
39403deb3ec6SMatthias Ringwald                     // otherwise, store security request
39413deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
39423deb3ec6SMatthias Ringwald                     break;
3943dc8ca372SMatthias Ringwald             }
3944dc8ca372SMatthias Ringwald             break;
39453deb3ec6SMatthias Ringwald 
39463deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3947aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
3948aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3949aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3950aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3951aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
3952aacfafc3SMatthias Ringwald                 break;
3953aacfafc3SMatthias Ringwald             }
3954aacfafc3SMatthias Ringwald 
3955aacfafc3SMatthias Ringwald             // all other pdus are incorrect
39564c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
39573deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39583deb3ec6SMatthias Ringwald                 break;
39593deb3ec6SMatthias Ringwald             }
39600af429c6SMatthias Ringwald 
39613deb3ec6SMatthias Ringwald             // store pairing request
39626535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
39636535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
39643deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
39650af429c6SMatthias Ringwald 
39660af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
39670af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
39680af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
39690af429c6SMatthias Ringwald                 err = test_pairing_failure;
39700af429c6SMatthias Ringwald             }
39710af429c6SMatthias Ringwald #endif
39720af429c6SMatthias Ringwald 
39739305033eSMatthias Ringwald             if (err != 0){
3974f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
39753deb3ec6SMatthias Ringwald                 break;
39763deb3ec6SMatthias Ringwald             }
3977b41539d5SMatthias Ringwald 
3978b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
3979b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3980f3582630SMatthias 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);
3981b41539d5SMatthias Ringwald                 break;
3982b41539d5SMatthias Ringwald             }
3983b41539d5SMatthias Ringwald 
3984136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3985136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
39868cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
39878cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
3988136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3989136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
3990136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3991c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3992136d331aSMatthias Ringwald                     }
39938cba5ca3SMatthias Ringwald                 } else {
3994c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
39958cba5ca3SMatthias Ringwald                 }
3996136d331aSMatthias Ringwald                 break;
3997136d331aSMatthias Ringwald             }
3998136d331aSMatthias Ringwald #endif
39993deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
40003deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
40013deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
40023deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4003f3582630SMatthias 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);
40043deb3ec6SMatthias Ringwald             }
40053deb3ec6SMatthias Ringwald             break;
40063deb3ec6SMatthias Ringwald 
40073deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
40084c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
40093deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40103deb3ec6SMatthias Ringwald                 break;
40113deb3ec6SMatthias Ringwald             }
40123deb3ec6SMatthias Ringwald 
40133deb3ec6SMatthias Ringwald             // store s_confirm
40149c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4015192365feSMatthias Ringwald 
4016aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4017aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4018aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4019aa9b34e5SMatthias Ringwald                 break;
4020aa9b34e5SMatthias Ringwald             }
4021aa9b34e5SMatthias Ringwald 
4022192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4023192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4024192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4025192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4026192365feSMatthias Ringwald             }
4027192365feSMatthias Ringwald #endif
40283deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
40293deb3ec6SMatthias Ringwald             break;
40303deb3ec6SMatthias Ringwald 
40313deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
40324c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
40333deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40343deb3ec6SMatthias Ringwald                 break;;
40353deb3ec6SMatthias Ringwald             }
40363deb3ec6SMatthias Ringwald 
40373deb3ec6SMatthias Ringwald             // received random value
40389c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
40393deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
40403deb3ec6SMatthias Ringwald             break;
404142134bc6SMatthias Ringwald #endif
40423deb3ec6SMatthias Ringwald 
404342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
40443deb3ec6SMatthias Ringwald         // Responder
40453deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
40463deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
40473deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
40484c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
40493deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40503deb3ec6SMatthias Ringwald                 break;;
40513deb3ec6SMatthias Ringwald             }
40523deb3ec6SMatthias Ringwald 
40533deb3ec6SMatthias Ringwald             // store pairing request
4054212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4055212d735eSMatthias Ringwald 
4056212d735eSMatthias Ringwald             // check if IRK completed
4057212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4058212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4059212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
40603deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
40613deb3ec6SMatthias Ringwald                     break;
4062212d735eSMatthias Ringwald                 default:
4063212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4064212d735eSMatthias Ringwald                     break;
4065212d735eSMatthias Ringwald             }
4066212d735eSMatthias Ringwald             break;
406742134bc6SMatthias Ringwald #endif
40683deb3ec6SMatthias Ringwald 
406927c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4070c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
40714c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
407227c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
407327c32905SMatthias Ringwald                 break;
407427c32905SMatthias Ringwald             }
4075bccf5e67SMatthias Ringwald 
4076e53be891SMatthias Ringwald             // store public key for DH Key calculation
4077fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4078fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4079bccf5e67SMatthias Ringwald 
408002658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
408102658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
408202658749SMatthias Ringwald                 log_info("Remote PK matches ours");
408302658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
408402658749SMatthias Ringwald                 break;
408502658749SMatthias Ringwald             }
408602658749SMatthias Ringwald 
4087d1a1f6a4SMatthias Ringwald             // validate public key
4088d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
40899305033eSMatthias Ringwald             if (err != 0){
409002658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4091349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4092bccf5e67SMatthias Ringwald                 break;
4093bccf5e67SMatthias Ringwald             }
4094891bb64aSMatthias Ringwald 
4095d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4096f3582630SMatthias 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);
40973cf37b8cSMatthias Ringwald 
409865a9a04eSMatthias Ringwald 
409965a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
410042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4101136d331aSMatthias Ringwald                 // responder
4102c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4103136d331aSMatthias Ringwald             } else {
4104136d331aSMatthias Ringwald                 // initiator
4105a1e31e9cSMatthias Ringwald                 // stk generation method
4106a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4107a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4108a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
410947fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4110c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4111a1e31e9cSMatthias Ringwald                         break;
4112a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
411307036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
411407036a04SMatthias Ringwald                         break;
411507036a04SMatthias Ringwald                     case PK_INIT_INPUT:
411647fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
411707036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
411807036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
411907036a04SMatthias Ringwald                             break;
412007036a04SMatthias Ringwald                         }
4121b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4122a1e31e9cSMatthias Ringwald                         break;
4123a1e31e9cSMatthias Ringwald                     case OOB:
4124d1a1f6a4SMatthias Ringwald                         // generate Nx
41254acf7b7bSMatthias Ringwald                         log_info("Generate Na");
41266ca80073SMatthias 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);
4127a1e31e9cSMatthias Ringwald                         break;
41287bbeb3adSMilanka Ringwald                     default:
41297bbeb3adSMilanka Ringwald                         btstack_assert(false);
41307bbeb3adSMilanka Ringwald                         break;
4131a1e31e9cSMatthias Ringwald                 }
4132136d331aSMatthias Ringwald             }
413327c32905SMatthias Ringwald             break;
4134e53be891SMatthias Ringwald 
4135c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
41364c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
413745a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
413845a61d50SMatthias Ringwald                 break;
413945a61d50SMatthias Ringwald             }
414045a61d50SMatthias Ringwald             // received confirm value
414145a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
414245a61d50SMatthias Ringwald 
4143192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4144192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4145192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4146192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4147192365feSMatthias Ringwald             }
4148192365feSMatthias Ringwald #endif
414942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
415045a61d50SMatthias Ringwald                 // responder
415107036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
415207036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
415307036a04SMatthias Ringwald                         // still waiting for passkey
415407036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
415507036a04SMatthias Ringwald                         break;
415607036a04SMatthias Ringwald                     }
415707036a04SMatthias Ringwald                 }
4158b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
415945a61d50SMatthias Ringwald             } else {
416045a61d50SMatthias Ringwald                 // initiator
4161945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
41626ca80073SMatthias 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);
4163f1c1783eSMatthias Ringwald                 } else {
4164c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
416545a61d50SMatthias Ringwald                 }
4166f1c1783eSMatthias Ringwald             }
416745a61d50SMatthias Ringwald             break;
416845a61d50SMatthias Ringwald 
4169c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
41704c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4171e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4172136d331aSMatthias Ringwald                 break;
4173e53be891SMatthias Ringwald             }
4174e53be891SMatthias Ringwald 
4175e53be891SMatthias Ringwald             // received random value
4176e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4177e53be891SMatthias Ringwald 
41785a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4179ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4180d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4181d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4182d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
418365a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4184d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4185688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4186ae451ec5SMatthias Ringwald                  break;
41875a293e6eSMatthias Ringwald             }
41886f52a196SMatthias Ringwald 
41894acf7b7bSMatthias Ringwald             // OOB
41904acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
41914acf7b7bSMatthias Ringwald 
41924acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
41934acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
41944acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
41954ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
41964acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
41974acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
41984acf7b7bSMatthias Ringwald                     } else {
41996535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
42004acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
42014acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
42024acf7b7bSMatthias Ringwald                     }
42034acf7b7bSMatthias Ringwald                 }  else {
42044ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
42054acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
42064acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
42074acf7b7bSMatthias Ringwald                     } else {
42086535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
42094acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
42104acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
42114acf7b7bSMatthias Ringwald                     }
42124acf7b7bSMatthias Ringwald                 }
42134acf7b7bSMatthias Ringwald 
4214a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
42154acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4216a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4217a680ba6bSMatthias Ringwald                      break;
4218a680ba6bSMatthias Ringwald                 }
42194acf7b7bSMatthias Ringwald             }
4220a680ba6bSMatthias Ringwald 
4221a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4222688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4223e53be891SMatthias Ringwald             break;
4224e53be891SMatthias Ringwald 
4225901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4226901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
42273cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4228901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4229901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4230901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4231901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4232901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4233901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4234901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4235c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4236901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4237d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
42384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4239e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4240e53be891SMatthias Ringwald                 break;
4241e53be891SMatthias Ringwald             }
4242e53be891SMatthias Ringwald             // store DHKey Check
4243901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4244e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4245446a8c36SMatthias Ringwald 
4246901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4247901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4248019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4249bd57ffebSMatthias Ringwald             }
4250bd57ffebSMatthias Ringwald             break;
425127c32905SMatthias Ringwald #endif
425227c32905SMatthias Ringwald 
425342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42543deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
42554c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42563deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
425727c32905SMatthias Ringwald                 break;
42583deb3ec6SMatthias Ringwald             }
42593deb3ec6SMatthias Ringwald 
42603deb3ec6SMatthias Ringwald             // received confirm value
42619c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
42623deb3ec6SMatthias Ringwald 
4263192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4264192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4265192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4266192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4267192365feSMatthias Ringwald             }
4268192365feSMatthias Ringwald #endif
42693deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
42703deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
42715611a760SMatthias 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);
42723deb3ec6SMatthias Ringwald             }
42733deb3ec6SMatthias Ringwald 
42743deb3ec6SMatthias Ringwald             // handle user cancel pairing?
42753deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4276f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
42773deb3ec6SMatthias Ringwald                 break;
42783deb3ec6SMatthias Ringwald             }
42793deb3ec6SMatthias Ringwald 
42803deb3ec6SMatthias Ringwald             // wait for user action?
42813deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
42823deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42833deb3ec6SMatthias Ringwald                 break;
42843deb3ec6SMatthias Ringwald             }
42853deb3ec6SMatthias Ringwald 
42863deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4287f3582630SMatthias 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);
42883deb3ec6SMatthias Ringwald             break;
42893deb3ec6SMatthias Ringwald 
42903deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
42914c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42923deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42933deb3ec6SMatthias Ringwald                 break;;
42943deb3ec6SMatthias Ringwald             }
42953deb3ec6SMatthias Ringwald 
42963deb3ec6SMatthias Ringwald             // received random value
42979c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42983deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42993deb3ec6SMatthias Ringwald             break;
430042134bc6SMatthias Ringwald #endif
43013deb3ec6SMatthias Ringwald 
43023deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
43034c1d1092SMatthias Ringwald             switch(sm_pdu_code){
43043deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
43053deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
43069c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
43073deb3ec6SMatthias Ringwald                     break;
43083deb3ec6SMatthias Ringwald 
43093deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
43103deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4311f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
43129c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
43133deb3ec6SMatthias Ringwald                     break;
43143deb3ec6SMatthias Ringwald 
43153deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
43163deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
43179c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
43183deb3ec6SMatthias Ringwald                     break;
43193deb3ec6SMatthias Ringwald 
43203deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
43213deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
43223deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4323724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
43243deb3ec6SMatthias Ringwald                     break;
43253deb3ec6SMatthias Ringwald 
43263deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
43273deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
43289c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
43293deb3ec6SMatthias Ringwald                     break;
43303deb3ec6SMatthias Ringwald                 default:
43313deb3ec6SMatthias Ringwald                     // Unexpected PDU
43323deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
43333deb3ec6SMatthias Ringwald                     break;
43343deb3ec6SMatthias Ringwald             }
43353deb3ec6SMatthias Ringwald             // done with key distribution?
43363deb3ec6SMatthias Ringwald             if (sm_key_distribution_all_received(sm_conn)){
43373deb3ec6SMatthias Ringwald 
43383deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
43393deb3ec6SMatthias Ringwald 
434042134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43416f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
43423deb3ec6SMatthias Ringwald                 } else {
4343625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4344625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4345bbf8db22SMatthias Ringwald                     } else {
4346f3582630SMatthias 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);
4347625f00b2SMatthias Ringwald                     }
43483deb3ec6SMatthias Ringwald                 }
43493deb3ec6SMatthias Ringwald             }
43503deb3ec6SMatthias Ringwald             break;
43513deb3ec6SMatthias Ringwald         default:
43523deb3ec6SMatthias Ringwald             // Unexpected PDU
43533deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
43542d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
43553deb3ec6SMatthias Ringwald             break;
43563deb3ec6SMatthias Ringwald     }
43573deb3ec6SMatthias Ringwald 
435870b44dd4SMatthias Ringwald     // try to send next pdu
435970b44dd4SMatthias Ringwald     sm_trigger_run();
43603deb3ec6SMatthias Ringwald }
43613deb3ec6SMatthias Ringwald 
43623deb3ec6SMatthias Ringwald // Security Manager Client API
4363a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
43643deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
43653deb3ec6SMatthias Ringwald }
43663deb3ec6SMatthias Ringwald 
43674acf7b7bSMatthias 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)){
4368a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4369a680ba6bSMatthias Ringwald }
4370a680ba6bSMatthias Ringwald 
437189a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
437289a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
437389a78d34SMatthias Ringwald }
437489a78d34SMatthias Ringwald 
43753deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
43763deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
43773deb3ec6SMatthias Ringwald }
43783deb3ec6SMatthias Ringwald 
43793deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
43803deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
43813deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
43823deb3ec6SMatthias Ringwald }
43833deb3ec6SMatthias Ringwald 
43843deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
438598d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
438698d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
438798d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
438898d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
438998d95509SMatthias Ringwald     }
439098d95509SMatthias Ringwald #endif
43913deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
43923deb3ec6SMatthias Ringwald }
43933deb3ec6SMatthias Ringwald 
43943deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
43953deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
43963deb3ec6SMatthias Ringwald }
43973deb3ec6SMatthias Ringwald 
439842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43993deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
44003deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
44013deb3ec6SMatthias Ringwald }
440242134bc6SMatthias Ringwald #endif
44033deb3ec6SMatthias Ringwald 
44043deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
44056535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
44063deb3ec6SMatthias Ringwald }
44073deb3ec6SMatthias Ringwald 
44083deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
44096535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
44103deb3ec6SMatthias Ringwald }
44113deb3ec6SMatthias Ringwald 
44123deb3ec6SMatthias Ringwald // Testing support only
44133deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
44146535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4415103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4416841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
44173deb3ec6SMatthias Ringwald }
44183deb3ec6SMatthias Ringwald 
44193deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4420841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
44213deb3ec6SMatthias Ringwald }
44223deb3ec6SMatthias Ringwald 
4423d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4424d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4425d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4426d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
442734b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
442870b44dd4SMatthias Ringwald     sm_trigger_run();
4429d1a1f6a4SMatthias Ringwald }
4430674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
443134b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4432674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4433674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4434674e5b4aSMatthias Ringwald }
4435d1a1f6a4SMatthias Ringwald #endif
4436d1a1f6a4SMatthias Ringwald 
4437192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4438192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4439192365feSMatthias Ringwald     test_pairing_failure = reason;
4440192365feSMatthias Ringwald }
4441192365feSMatthias Ringwald #endif
4442192365feSMatthias Ringwald 
44433deb3ec6SMatthias Ringwald void sm_init(void){
44442d2d4d3cSMatthias Ringwald 
44452d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
44462d2d4d3cSMatthias Ringwald 
4447899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4448899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4449899e6e02SMatthias Ringwald 
44503deb3ec6SMatthias Ringwald     // defaults
44513deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
44523deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4453b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4454b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4455b4343428SMatthias Ringwald 
44563deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
44573deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
44583deb3ec6SMatthias Ringwald 
44595ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
44601979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4461caf15bf3SMatthias Ringwald 
4462d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4463d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
44647a766ebfSMatthias Ringwald #endif
44658d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4466fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
44673deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
44683deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
44693deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
44703deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
44713deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
44723deb3ec6SMatthias Ringwald 
44733deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
44747149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
44753deb3ec6SMatthias Ringwald 
4476841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
44773deb3ec6SMatthias Ringwald 
447884c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
447984c0c5c7SMatthias Ringwald 
4480e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4481e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4482e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4483e03e489aSMatthias Ringwald 
4484d1a1f6a4SMatthias Ringwald     //
4485d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4486d1a1f6a4SMatthias Ringwald 
448751bd74d1SMatthias Ringwald     // init le_device_db
448851bd74d1SMatthias Ringwald     le_device_db_init();
448951bd74d1SMatthias Ringwald 
4490b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4491e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
449227c32905SMatthias Ringwald 
449309e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4494674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4495a3aba2f9SMatthias Ringwald #endif
44962d2d4d3cSMatthias Ringwald 
44972d2d4d3cSMatthias Ringwald     sm_initialized = true;
44983deb3ec6SMatthias Ringwald }
44993deb3ec6SMatthias Ringwald 
450015537ea4SMatthias Ringwald void sm_deinit(void){
450115537ea4SMatthias Ringwald     sm_initialized = false;
450215537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
450315537ea4SMatthias Ringwald }
450415537ea4SMatthias Ringwald 
45054b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
45064b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4507caf15bf3SMatthias Ringwald }
4508caf15bf3SMatthias Ringwald 
45096c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
45101979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
45116c39055aSMatthias Ringwald }
45126c39055aSMatthias Ringwald 
4513711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4514711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
45153deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
45163deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
45173deb3ec6SMatthias Ringwald }
45183deb3ec6SMatthias Ringwald 
45196bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4520711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4521711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45223deb3ec6SMatthias Ringwald     if (!sm_conn) return;
45236bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
45246bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
45253deb3ec6SMatthias Ringwald }
45263deb3ec6SMatthias Ringwald 
45273deb3ec6SMatthias Ringwald // request pairing
4528711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4529711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45303deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45313deb3ec6SMatthias Ringwald 
45327af5dcd5SMatthias Ringwald     bool have_ltk;
45337af5dcd5SMatthias Ringwald     uint8_t ltk[16];
45343deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
453542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
453624c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
453724c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
453824c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
45397af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45407af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45417af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
45427af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
45437af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
45447af5dcd5SMatthias Ringwald                         if (have_ltk){
45457af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
454624c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45477af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
45487af5dcd5SMatthias Ringwald                             break;
45497af5dcd5SMatthias Ringwald                         }
45507af5dcd5SMatthias Ringwald                         /* fall through */
45517af5dcd5SMatthias Ringwald 
45527af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45537af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45547af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45557af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
45567af5dcd5SMatthias Ringwald                         break;
45577af5dcd5SMatthias Ringwald                     default:
45587af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
45597af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45607af5dcd5SMatthias Ringwald                         break;
45617af5dcd5SMatthias Ringwald                 }
456224c20dc4SMatthias Ringwald                 break;
456324c20dc4SMatthias Ringwald             default:
456424c20dc4SMatthias Ringwald                 break;
456524c20dc4SMatthias Ringwald         }
45663deb3ec6SMatthias Ringwald     } else {
45673deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4568175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4569175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
45703deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45713deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45723dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4573f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4574f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4575f53ec649SMatthias Ringwald                         if (have_ltk){
4576c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
45775567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4578c245ca32SMatthias Ringwald                             break;
4579f53ec649SMatthias Ringwald                         }
4580cf373d3aSMatthias Ringwald                         /* fall through */
4581c245ca32SMatthias Ringwald 
458234c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45833deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
45843deb3ec6SMatthias Ringwald                         break;
45853deb3ec6SMatthias Ringwald                     default:
4586d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
458709ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45883deb3ec6SMatthias Ringwald                         break;
45893deb3ec6SMatthias Ringwald                 }
4590175b7faaSMatthias Ringwald                 break;
4591cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4592cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4593cb6d7eb0SMatthias Ringwald                 break;
4594175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
459509ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4596175b7faaSMatthias Ringwald                 break;
4597175b7faaSMatthias Ringwald             default:
4598175b7faaSMatthias Ringwald                 break;
45993deb3ec6SMatthias Ringwald         }
46003deb3ec6SMatthias Ringwald     }
460170b44dd4SMatthias Ringwald     sm_trigger_run();
46023deb3ec6SMatthias Ringwald }
46033deb3ec6SMatthias Ringwald 
46043deb3ec6SMatthias Ringwald // called by client app on authorization request
4605711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4606711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46073deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46083deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4609589f5a99SMatthias 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);
46103deb3ec6SMatthias Ringwald }
46113deb3ec6SMatthias Ringwald 
4612711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4613711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46143deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46153deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4616589f5a99SMatthias 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);
46173deb3ec6SMatthias Ringwald }
46183deb3ec6SMatthias Ringwald 
46193deb3ec6SMatthias Ringwald // GAP Bonding API
46203deb3ec6SMatthias Ringwald 
4621711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4622711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46233deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46243deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
46250af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
46260af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
46270af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46280af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
46290af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
46300af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
46310af429c6SMatthias Ringwald #endif
46320af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4633de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4634de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4635de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
463647fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
46370af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4638de2fd182SMatthias Ringwald                     break;
463947fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4640de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4641de2fd182SMatthias Ringwald                     break;
4642de2fd182SMatthias Ringwald                 case JUST_WORKS:
4643de2fd182SMatthias Ringwald                 case OOB:
4644de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4645de2fd182SMatthias Ringwald                     break;
46467bbeb3adSMilanka Ringwald                 default:
46477bbeb3adSMilanka Ringwald                     btstack_assert(false);
46487bbeb3adSMilanka Ringwald                     break;
4649de2fd182SMatthias Ringwald             }
46500af429c6SMatthias Ringwald             break;
46510af429c6SMatthias Ringwald         default:
46520af429c6SMatthias Ringwald             break;
46533deb3ec6SMatthias Ringwald     }
465470b44dd4SMatthias Ringwald     sm_trigger_run();
46553deb3ec6SMatthias Ringwald }
46563deb3ec6SMatthias Ringwald 
4657711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4658711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46593deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46603deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
46613deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4662136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4663c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4664bbf8db22SMatthias Ringwald         } else {
4665f3582630SMatthias 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);
4666136d331aSMatthias Ringwald         }
46673deb3ec6SMatthias Ringwald     }
46680346c37cSMatthias Ringwald 
46690346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4670c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4671dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4672446a8c36SMatthias Ringwald     }
46730346c37cSMatthias Ringwald #endif
46740346c37cSMatthias Ringwald 
467570b44dd4SMatthias Ringwald     sm_trigger_run();
46763deb3ec6SMatthias Ringwald }
46773deb3ec6SMatthias Ringwald 
4678c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4679c8c46d51SMatthias Ringwald     // for now, it's the same
4680c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4681c8c46d51SMatthias Ringwald }
4682c8c46d51SMatthias Ringwald 
4683711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4684711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46853deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46863deb3ec6SMatthias Ringwald     sm_reset_tk();
4687f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
46883deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
46893deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4690f3582630SMatthias 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);
46913deb3ec6SMatthias Ringwald     }
46921c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46936535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
46946535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
469507036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
469607036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
469707036a04SMatthias Ringwald     }
46981c516d8fSMatthias Ringwald #endif
469970b44dd4SMatthias Ringwald     sm_trigger_run();
47003deb3ec6SMatthias Ringwald }
47013deb3ec6SMatthias Ringwald 
47023d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
47033d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47043d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
47053d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4706dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
47074ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4708dd4a08fbSMatthias Ringwald     switch (action){
4709dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4710dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
47114ea43905SMatthias Ringwald             flags |= (1u << action);
4712dd4a08fbSMatthias Ringwald             break;
4713dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4714dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
47154ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4716dd4a08fbSMatthias Ringwald             break;
4717dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
47184ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4719dd4a08fbSMatthias Ringwald                 // erase actions queued
4720dd4a08fbSMatthias Ringwald                 num_actions--;
47214ea43905SMatthias Ringwald                 if (num_actions == 0u){
4722dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47234ea43905SMatthias Ringwald                     flags &= 0x19u;
4724dd4a08fbSMatthias Ringwald                 }
4725dd4a08fbSMatthias Ringwald                 break;
4726dd4a08fbSMatthias Ringwald             }
4727dd4a08fbSMatthias Ringwald             num_actions++;
47284ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4729dd4a08fbSMatthias Ringwald             break;
4730dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
47314ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4732dd4a08fbSMatthias Ringwald                 // enter actions queued
4733dd4a08fbSMatthias Ringwald                 num_actions--;
47344ea43905SMatthias Ringwald                 if (num_actions == 0u){
4735dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
47364ea43905SMatthias Ringwald                     flags &= 0x19u;
4737dd4a08fbSMatthias Ringwald                 }
4738dd4a08fbSMatthias Ringwald                 break;
4739dd4a08fbSMatthias Ringwald             }
4740dd4a08fbSMatthias Ringwald             num_actions++;
47414ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4742dd4a08fbSMatthias Ringwald             break;
4743dd4a08fbSMatthias Ringwald         default:
4744dd4a08fbSMatthias Ringwald             break;
4745dd4a08fbSMatthias Ringwald     }
4746dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
474770b44dd4SMatthias Ringwald     sm_trigger_run();
47483d7fe1e9SMatthias Ringwald }
47493d7fe1e9SMatthias Ringwald 
4750c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4751d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
4752d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4753d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
475470b44dd4SMatthias Ringwald     sm_trigger_run();
4755d1a1f6a4SMatthias Ringwald }
4756c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
47578334d3d8SMatthias Ringwald 
47588334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
47598334d3d8SMatthias Ringwald 
4760c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4761c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
4762d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4763d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4764c59d0c92SMatthias Ringwald     return 0;
4765c59d0c92SMatthias Ringwald }
4766c59d0c92SMatthias Ringwald #endif
4767c59d0c92SMatthias Ringwald 
47683deb3ec6SMatthias Ringwald /**
4769ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
4770ba394633SMatthias Ringwald  * @param con_handle
4771ba394633SMatthias Ringwald  * @return irk_lookup_state_t
4772ba394633SMatthias Ringwald  */
4773ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4774ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4775ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
4776ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
4777ba394633SMatthias Ringwald }
4778ba394633SMatthias Ringwald 
4779ba394633SMatthias Ringwald /**
47803deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
47813deb3ec6SMatthias Ringwald  * @param handle
47823deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
47833deb3ec6SMatthias Ringwald  */
4784711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
4785711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47863deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
47873deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
47883deb3ec6SMatthias Ringwald }
47893deb3ec6SMatthias Ringwald 
47908f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
479147ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
479247ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
479347ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
479447ba4de1SMatthias Ringwald             return 0;
479547ba4de1SMatthias Ringwald         default:
47968f57b085SMatthias Ringwald             return 1;
47978f57b085SMatthias Ringwald     }
479847ba4de1SMatthias Ringwald }
4799d70217a2SMatthias Ringwald 
480033373e40SMatthias Ringwald static uint8_t own_address_type(void){
4801b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
4802b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4803b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
4804b95a5a35SMatthias Ringwald         default:
4805b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
4806b95a5a35SMatthias Ringwald     }
480733373e40SMatthias Ringwald }
48088f57b085SMatthias Ringwald 
48093deb3ec6SMatthias Ringwald // GAP LE API
48103deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
48113deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48123deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
4813b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
48148f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48153deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48163deb3ec6SMatthias Ringwald     gap_random_address_trigger();
48173deb3ec6SMatthias Ringwald }
48183deb3ec6SMatthias Ringwald 
48193deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
48203deb3ec6SMatthias Ringwald     return gap_random_adress_type;
48213deb3ec6SMatthias Ringwald }
48223deb3ec6SMatthias Ringwald 
48233deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
48243deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
48258f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
48263deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
48273deb3ec6SMatthias Ringwald     gap_random_address_update_start();
48283deb3ec6SMatthias Ringwald }
48293deb3ec6SMatthias Ringwald 
4830667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
48318f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
48326535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
48337e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
483470b44dd4SMatthias Ringwald     sm_trigger_run();
48357e252622SMatthias Ringwald }
48367e252622SMatthias Ringwald 
4837d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48383deb3ec6SMatthias Ringwald /*
48393deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
48403deb3ec6SMatthias Ringwald  * @param adv_int_min
48413deb3ec6SMatthias Ringwald  * @param adv_int_max
48423deb3ec6SMatthias Ringwald  * @param adv_type
48433deb3ec6SMatthias Ringwald  * @param direct_address_type
48443deb3ec6SMatthias Ringwald  * @param direct_address
48453deb3ec6SMatthias Ringwald  * @param channel_map
48463deb3ec6SMatthias Ringwald  * @param filter_policy
48473deb3ec6SMatthias Ringwald  *
48483deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
48493deb3ec6SMatthias Ringwald  */
48503deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
48513deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4852b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
48533deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
48543deb3ec6SMatthias Ringwald }
4855d70217a2SMatthias Ringwald #endif
4856dcd6c9b5SMatthias Ringwald 
4857dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4858dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4859dcd6c9b5SMatthias Ringwald      // wrong connection
4860dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
4861dcd6c9b5SMatthias Ringwald     // already encrypted
4862dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
4863dcd6c9b5SMatthias Ringwald     // irk status?
4864dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
4865dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
4866dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
4867dcd6c9b5SMatthias Ringwald             return 0;
4868dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
4869dcd6c9b5SMatthias Ringwald             break;
4870dcd6c9b5SMatthias Ringwald         default:
4871dcd6c9b5SMatthias Ringwald             // IR Lookup pending
4872dcd6c9b5SMatthias Ringwald             return 1;
4873dcd6c9b5SMatthias Ringwald     }
4874f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
4875f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
4876b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
4877b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
4878b15d5ceaSMatthias Ringwald     } else {
4879dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4880dcd6c9b5SMatthias Ringwald     }
4881b15d5ceaSMatthias Ringwald }
48823cdbe9dbSMatthias Ringwald 
48833cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
48843cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
48853cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
48863cdbe9dbSMatthias Ringwald #else
48873cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
48883cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
48893cdbe9dbSMatthias Ringwald #endif
48903cdbe9dbSMatthias Ringwald }
4891052bbdc5SMatthias Ringwald 
4892052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
4893052bbdc5SMatthias Ringwald     return sm_persistent_irk;
4894052bbdc5SMatthias Ringwald }
48954f384501SMatthias Ringwald 
48964f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
48974f384501SMatthias Ringwald     uint16_t i;
48984f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
48994f384501SMatthias Ringwald         bd_addr_t entry_address;
49004f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
49014f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
49024f384501SMatthias Ringwald         // skip unused entries
49034f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
49044f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
49054f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
49064f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
49074f384501SMatthias Ringwald #endif
49084f384501SMatthias Ringwald             le_device_db_remove(i);
49094f384501SMatthias Ringwald             break;
49104f384501SMatthias Ringwald         }
49114f384501SMatthias Ringwald     }
49124f384501SMatthias Ringwald }
4913