xref: /btstack/src/ble/sm.c (revision 2c041b42320445196fc791e24c45bb595c11777e)
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     // used in all phases
3053deb3ec6SMatthias Ringwald     uint8_t   sm_pairing_failed_reason;
3063deb3ec6SMatthias Ringwald 
3073deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3083deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
309dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3103deb3ec6SMatthias Ringwald 
3113deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
313715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
314715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3153deb3ec6SMatthias Ringwald 
3163deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3173deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3183deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
319a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
32027c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3213deb3ec6SMatthias Ringwald 
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3233deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3243deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3273deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3283deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3293deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3303deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3313deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3323deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3333deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3343deb3ec6SMatthias Ringwald 
33568437d83SMatthias Ringwald     uint8_t   sm_state_vars;
336e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
337fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
338446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
339446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
340d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
341e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
342e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
343446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
344446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3452bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
346a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3477df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
348e53be891SMatthias Ringwald #endif
34927c32905SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // Phase 3
3513deb3ec6SMatthias Ringwald 
3523deb3ec6SMatthias Ringwald     // key distribution, we generate
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3543deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3553deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3563deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3583deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3593deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3603deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3613deb3ec6SMatthias Ringwald 
3623deb3ec6SMatthias Ringwald     // key distribution, received from peer
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3643deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3653deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3663deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3683deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3693deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3703deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3713deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
372715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
373715a43d1SMatthias Ringwald     int       sm_le_device_index;
374715a43d1SMatthias Ringwald #endif
3753deb3ec6SMatthias Ringwald } sm_setup_context_t;
3763deb3ec6SMatthias Ringwald 
3773deb3ec6SMatthias Ringwald //
3783deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3793deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3803deb3ec6SMatthias Ringwald 
3813deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3827149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3833deb3ec6SMatthias Ringwald 
3843deb3ec6SMatthias Ringwald // @returns 1 if oob data is available
3853deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3863deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3874acf7b7bSMatthias 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);
3883deb3ec6SMatthias Ringwald 
3893deb3ec6SMatthias Ringwald static void sm_run(void);
390711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
391711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
3923deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3933deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
394d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
395d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
396d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
397d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
398d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4042a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4072a526f21SMatthias Ringwald #endif
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
412d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4136d80b495SMatthias 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));
41434b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4156ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4166ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4172a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
418d1a1f6a4SMatthias Ringwald #endif
4190ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4203deb3ec6SMatthias Ringwald 
4213deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4223deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4233deb3ec6SMatthias Ringwald }
4243deb3ec6SMatthias Ringwald 
4251fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4261fbd72c5SMatthias Ringwald //     return packet[0];
4271fbd72c5SMatthias Ringwald // }
4281fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4291fbd72c5SMatthias Ringwald     return packet[1];
4301fbd72c5SMatthias Ringwald }
4311fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4321fbd72c5SMatthias Ringwald     return packet[2];
4331fbd72c5SMatthias Ringwald }
4341fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4351fbd72c5SMatthias Ringwald     return packet[3];
4361fbd72c5SMatthias Ringwald }
4371fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4381fbd72c5SMatthias Ringwald     return packet[4];
4391fbd72c5SMatthias Ringwald }
4401fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4411fbd72c5SMatthias Ringwald     return packet[5];
4421fbd72c5SMatthias Ringwald }
4431fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4441fbd72c5SMatthias Ringwald     return packet[6];
4451fbd72c5SMatthias Ringwald }
4461fbd72c5SMatthias Ringwald 
4471fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4481fbd72c5SMatthias Ringwald     packet[0] = code;
4491fbd72c5SMatthias Ringwald }
4501fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4511fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4521fbd72c5SMatthias Ringwald }
4531fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4541fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4551fbd72c5SMatthias Ringwald }
4561fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4571fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4581fbd72c5SMatthias Ringwald }
4591fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4601fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4611fbd72c5SMatthias Ringwald }
4621fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4631fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4641fbd72c5SMatthias Ringwald }
4651fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4661fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4671fbd72c5SMatthias Ringwald }
4681fbd72c5SMatthias Ringwald 
4693deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4701979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4713deb3ec6SMatthias Ringwald     int i;
4723764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47384c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4741979f09cSMatthias Ringwald             return false;
47584c0c5c7SMatthias Ringwald         }
4763deb3ec6SMatthias Ringwald     }
4771979f09cSMatthias Ringwald     return true;
4783deb3ec6SMatthias Ringwald }
4793deb3ec6SMatthias Ringwald 
4801979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4813764b551SMatthias Ringwald     return sm_is_null(random, 8);
4823764b551SMatthias Ringwald }
4833764b551SMatthias Ringwald 
4841979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4853764b551SMatthias Ringwald     return sm_is_null(key, 16);
4863764b551SMatthias Ringwald }
4873764b551SMatthias Ringwald 
48870b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
48970b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49070b44dd4SMatthias Ringwald 	UNUSED(ts);
49170b44dd4SMatthias Ringwald 	sm_run();
49270b44dd4SMatthias Ringwald }
49370b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4942d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49584c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49670b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49770b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49870b44dd4SMatthias Ringwald }
49970b44dd4SMatthias Ringwald 
5003deb3ec6SMatthias Ringwald // Key utils
5013deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5023deb3ec6SMatthias Ringwald     int i;
5033deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5043deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5053deb3ec6SMatthias Ringwald     }
5063deb3ec6SMatthias Ringwald }
5073deb3ec6SMatthias Ringwald 
5083deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5093deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5103deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5113deb3ec6SMatthias Ringwald     int i;
5123deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5133deb3ec6SMatthias Ringwald         key[15-i] = 0;
5143deb3ec6SMatthias Ringwald     }
5153deb3ec6SMatthias Ringwald }
5163deb3ec6SMatthias Ringwald 
517899e6e02SMatthias Ringwald // ER / IR checks
51821045273SMatthias Ringwald static void sm_er_ir_set_default(void){
519899e6e02SMatthias Ringwald     int i;
520899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
521899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
522899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
523899e6e02SMatthias Ringwald     }
524899e6e02SMatthias Ringwald }
525899e6e02SMatthias Ringwald 
526899e6e02SMatthias Ringwald static int sm_er_is_default(void){
527899e6e02SMatthias Ringwald     int i;
528899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
529899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
530899e6e02SMatthias Ringwald     }
531899e6e02SMatthias Ringwald     return 1;
532899e6e02SMatthias Ringwald }
533899e6e02SMatthias Ringwald 
534899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
535899e6e02SMatthias Ringwald     int i;
536899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
537899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
538899e6e02SMatthias Ringwald     }
539899e6e02SMatthias Ringwald     return 1;
540899e6e02SMatthias Ringwald }
541899e6e02SMatthias Ringwald 
54273102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54373102768SMatthias Ringwald     UNUSED(channel);
54473102768SMatthias Ringwald 
54573102768SMatthias Ringwald     // log event
54673102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54773102768SMatthias Ringwald     // dispatch to all event handlers
54873102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
54973102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55073102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55173102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55273102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55373102768SMatthias Ringwald     }
55473102768SMatthias Ringwald }
55573102768SMatthias Ringwald 
55673102768SMatthias 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){
55773102768SMatthias Ringwald     event[0] = type;
55873102768SMatthias Ringwald     event[1] = event_size - 2;
55973102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56073102768SMatthias Ringwald     event[4] = addr_type;
56173102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56273102768SMatthias Ringwald }
56373102768SMatthias Ringwald 
56473102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56573102768SMatthias Ringwald     uint8_t event[11];
56673102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56773102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56873102768SMatthias Ringwald }
56973102768SMatthias Ringwald 
57073102768SMatthias 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){
57173102768SMatthias Ringwald     uint8_t event[15];
57273102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57373102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57473102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57573102768SMatthias Ringwald }
57673102768SMatthias Ringwald 
57773102768SMatthias 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){
57873102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57973102768SMatthias Ringwald     bd_addr_t identity_address;
58073102768SMatthias Ringwald     int identity_address_type;
58173102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58273102768SMatthias Ringwald 
58373102768SMatthias Ringwald     uint8_t event[20];
58473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58573102768SMatthias Ringwald     event[11] = identity_address_type;
58673102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58773102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58873102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58973102768SMatthias Ringwald }
59073102768SMatthias Ringwald 
59173102768SMatthias 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){
59273102768SMatthias Ringwald     uint8_t event[12];
59373102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59473102768SMatthias Ringwald     event[11] = status;
59573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59673102768SMatthias Ringwald }
59773102768SMatthias Ringwald 
59873102768SMatthias Ringwald 
59973102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60073102768SMatthias Ringwald 
6013ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6023ab61f77SMatthias Ringwald 
6037b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60473102768SMatthias Ringwald 
60573102768SMatthias Ringwald     int       identity_addr_type;
60673102768SMatthias Ringwald     bd_addr_t identity_addr;
6073c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6083c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60973102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6103c0e26deSMatthias Ringwald     } else {
6113c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6123c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6133c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6143c0e26deSMatthias Ringwald     }
61573102768SMatthias Ringwald 
61673102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61773102768SMatthias Ringwald }
61873102768SMatthias Ringwald 
61973102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62073102768SMatthias Ringwald 
62160be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62260be5b21SMatthias Ringwald 
6237b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62473102768SMatthias Ringwald 
62573102768SMatthias Ringwald     int       identity_addr_type;
62673102768SMatthias Ringwald     bd_addr_t identity_addr;
6273c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6283c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62973102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6303c0e26deSMatthias Ringwald     } else {
6313c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6323c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6333c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6343c0e26deSMatthias Ringwald     }
63573102768SMatthias Ringwald 
63673102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63773102768SMatthias Ringwald }
63873102768SMatthias Ringwald 
639d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
640d3c12277SMatthias Ringwald 
641d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
642d3c12277SMatthias Ringwald 
643d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
644d3c12277SMatthias Ringwald 
645d3c12277SMatthias Ringwald     uint8_t event[11];
646d3c12277SMatthias 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);
647d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
648d3c12277SMatthias Ringwald }
649d3c12277SMatthias Ringwald 
6500ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
651f61072f5SMatthias Ringwald 
652d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
653d77906ffSMatthias Ringwald 
6540ccf6c9cSMatthias Ringwald     uint8_t event[13];
6550ccf6c9cSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_COMPLETE, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
6560ccf6c9cSMatthias Ringwald     event[11] = status;
6570ccf6c9cSMatthias Ringwald     event[12] = reason;
6580ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6590ccf6c9cSMatthias Ringwald }
6600ccf6c9cSMatthias Ringwald 
6613deb3ec6SMatthias Ringwald // SMP Timeout implementation
6623deb3ec6SMatthias Ringwald 
6633deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6643deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6653deb3ec6SMatthias Ringwald //
6663deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6673deb3ec6SMatthias Ringwald //
6683deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6693deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6703deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6713deb3ec6SMatthias Ringwald // established.
6723deb3ec6SMatthias Ringwald 
673ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6743deb3ec6SMatthias Ringwald     log_info("SM timeout");
675c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6763deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67768a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6780ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6793deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6803deb3ec6SMatthias Ringwald 
6813deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6823deb3ec6SMatthias Ringwald     sm_run();
6833deb3ec6SMatthias Ringwald }
6843deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
685528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
687528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
688528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
689528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6903deb3ec6SMatthias Ringwald }
6913deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
692528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6933deb3ec6SMatthias Ringwald }
6943deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6953deb3ec6SMatthias Ringwald     sm_timeout_stop();
6963deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald 
6993deb3ec6SMatthias Ringwald // end of sm timeout
7003deb3ec6SMatthias Ringwald 
7013deb3ec6SMatthias Ringwald // GAP Random Address updates
7023deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
703ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7043deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7053deb3ec6SMatthias Ringwald 
7063deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
707899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
708d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
709fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71070b44dd4SMatthias Ringwald     sm_trigger_run();
7113deb3ec6SMatthias Ringwald }
7123deb3ec6SMatthias Ringwald 
713ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7149ec2630cSMatthias Ringwald     UNUSED(timer);
7159ec2630cSMatthias Ringwald 
7163deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
717528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
718528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7193deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7203deb3ec6SMatthias Ringwald }
7213deb3ec6SMatthias Ringwald 
7223deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
723528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
724528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
725528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7263deb3ec6SMatthias Ringwald }
7273deb3ec6SMatthias Ringwald 
7283deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
729528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7303deb3ec6SMatthias Ringwald }
7313deb3ec6SMatthias Ringwald 
7323deb3ec6SMatthias Ringwald // ah(k,r) helper
7333deb3ec6SMatthias Ringwald // r = padding || r
7343deb3ec6SMatthias Ringwald // r - 24 bit value
7354a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7363deb3ec6SMatthias Ringwald     // r'= padding || r
7373deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7386535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7393deb3ec6SMatthias Ringwald }
7403deb3ec6SMatthias Ringwald 
7413deb3ec6SMatthias Ringwald // d1 helper
7423deb3ec6SMatthias Ringwald // d' = padding || r || d
7433deb3ec6SMatthias Ringwald // d,r - 16 bit values
7444a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7453deb3ec6SMatthias Ringwald     // d'= padding || r || d
7463deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
747f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
748f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7493deb3ec6SMatthias Ringwald }
7503deb3ec6SMatthias Ringwald 
7513deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7524a6806f3SMatthias Ringwald static void sm_c1_t1(sm_key_t r, uint8_t preq[7], uint8_t pres[7], uint8_t iat, uint8_t rat, uint8_t * t1){
7533deb3ec6SMatthias Ringwald 
7543deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7553deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7563deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7573deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7583deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7593deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald     sm_key_t p1;
7629c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7639c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7643deb3ec6SMatthias Ringwald     p1[14] = rat;
7653deb3ec6SMatthias Ringwald     p1[15] = iat;
7668314c363SMatthias Ringwald     log_info_key("p1", p1);
7678314c363SMatthias Ringwald     log_info_key("r", r);
7683deb3ec6SMatthias Ringwald 
7693deb3ec6SMatthias Ringwald     // t1 = r xor p1
7703deb3ec6SMatthias Ringwald     int i;
7713deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7723deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7733deb3ec6SMatthias Ringwald     }
7748314c363SMatthias Ringwald     log_info_key("t1", t1);
7753deb3ec6SMatthias Ringwald }
7763deb3ec6SMatthias Ringwald 
7773deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7784a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7793deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7803deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7813deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7823deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7833deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7843deb3ec6SMatthias Ringwald 
7853deb3ec6SMatthias Ringwald     sm_key_t p2;
7863deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7876535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7886535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7898314c363SMatthias Ringwald     log_info_key("p2", p2);
7903deb3ec6SMatthias Ringwald 
7913deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7923deb3ec6SMatthias Ringwald     int i;
7933deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7943deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7953deb3ec6SMatthias Ringwald     }
7968314c363SMatthias Ringwald     log_info_key("t3", t3);
7973deb3ec6SMatthias Ringwald }
7983deb3ec6SMatthias Ringwald 
7994a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8008314c363SMatthias Ringwald     log_info_key("r1", r1);
8018314c363SMatthias Ringwald     log_info_key("r2", r2);
8026535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8036535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8043deb3ec6SMatthias Ringwald }
8053deb3ec6SMatthias Ringwald 
806fbe050beSMatthias Ringwald 
8073deb3ec6SMatthias Ringwald // decide on stk generation based on
8083deb3ec6SMatthias Ringwald // - pairing request
8093deb3ec6SMatthias Ringwald // - io capabilities
8103deb3ec6SMatthias Ringwald // - OOB data availability
8113deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8123deb3ec6SMatthias Ringwald 
8138334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8148334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8158334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8168334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8178334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8188334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8198334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8208334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8218334d3d8SMatthias Ringwald     };
8228334d3d8SMatthias Ringwald 
8238334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8248334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8258334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8278334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8288334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8298334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8308334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8318334d3d8SMatthias Ringwald     };
8328334d3d8SMatthias Ringwald #endif
8338334d3d8SMatthias Ringwald 
8343deb3ec6SMatthias Ringwald     // default: just works
8353deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8363deb3ec6SMatthias Ringwald 
83727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83827c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83927c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8404ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84127c32905SMatthias Ringwald #else
84227c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84327c32905SMatthias Ringwald #endif
84498d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84527c32905SMatthias Ringwald 
84665a9a04eSMatthias Ringwald 
84765a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8481979f09cSMatthias Ringwald     bool use_oob;
84965a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85065a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85165a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8521979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85365a9a04eSMatthias Ringwald     } else {
85465a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85565a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8561979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85765a9a04eSMatthias Ringwald     }
85865a9a04eSMatthias Ringwald     if (use_oob){
85965a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86065a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86165a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86265a9a04eSMatthias Ringwald         return;
86365a9a04eSMatthias Ringwald     }
86465a9a04eSMatthias Ringwald 
86527c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86627c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86727c32905SMatthias Ringwald     // model shall be used.
8684ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8694ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87027c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87127c32905SMatthias Ringwald         return;
87227c32905SMatthias Ringwald     }
87327c32905SMatthias Ringwald 
8743deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8753deb3ec6SMatthias Ringwald     sm_reset_tk();
8763deb3ec6SMatthias Ringwald 
8773deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8788da2e96dSMatthias Ringwald     if ((sm_pairing_packet_get_io_capability(setup->sm_m_preq) > IO_CAPABILITY_KEYBOARD_DISPLAY) || (sm_pairing_packet_get_io_capability(setup->sm_s_pres) > IO_CAPABILITY_KEYBOARD_DISPLAY)){
8793deb3ec6SMatthias Ringwald         return;
8803deb3ec6SMatthias Ringwald     }
8813deb3ec6SMatthias Ringwald 
8823deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8833deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88427c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88527c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88627c32905SMatthias Ringwald 
88727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
888c6b7cbd9SMatthias Ringwald     // table not define by default
88927c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89027c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89127c32905SMatthias Ringwald     }
89227c32905SMatthias Ringwald #endif
89327c32905SMatthias Ringwald     setup->sm_stk_generation_method = generation_method[sm_pairing_packet_get_io_capability(setup->sm_s_pres)][sm_pairing_packet_get_io_capability(setup->sm_m_preq)];
89427c32905SMatthias Ringwald 
8953deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8961ad129beSMatthias Ringwald         sm_pairing_packet_get_io_capability(setup->sm_m_preq), sm_pairing_packet_get_io_capability(setup->sm_s_pres), setup->sm_stk_generation_method);
8973deb3ec6SMatthias Ringwald }
8983deb3ec6SMatthias Ringwald 
8993deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9003deb3ec6SMatthias Ringwald     int flags = 0;
9013deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9023deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9033deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9043deb3ec6SMatthias Ringwald     }
9053deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9073deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9083deb3ec6SMatthias Ringwald     }
9093deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     return flags;
9133deb3ec6SMatthias Ringwald }
9143deb3ec6SMatthias Ringwald 
9153deb3ec6SMatthias Ringwald static void sm_setup_key_distribution(uint8_t key_set){
9163deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9173deb3ec6SMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(key_set);
918715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9199790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
920715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9219790be5fSMatthias Ringwald #endif
9223deb3ec6SMatthias Ringwald }
9233deb3ec6SMatthias Ringwald 
9243deb3ec6SMatthias Ringwald // CSRK Key Lookup
9253deb3ec6SMatthias Ringwald 
9263deb3ec6SMatthias Ringwald 
9273deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9283deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9293deb3ec6SMatthias Ringwald }
9303deb3ec6SMatthias Ringwald 
931711e6c80SMatthias 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){
9326535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9333deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9343deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9353deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9363deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
937711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9383deb3ec6SMatthias Ringwald }
9393deb3ec6SMatthias Ringwald 
9403deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9413deb3ec6SMatthias Ringwald     // check if already in list
942665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9433deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
944665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
945665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
946665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9473deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9483deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9493deb3ec6SMatthias Ringwald         // already in list
9503deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9513deb3ec6SMatthias Ringwald     }
9523deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9533deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9543deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9556535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
956665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
95770b44dd4SMatthias Ringwald     sm_trigger_run();
9583deb3ec6SMatthias Ringwald     return 0;
9593deb3ec6SMatthias Ringwald }
9603deb3ec6SMatthias Ringwald 
961d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
962d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
963514d35fcSMatthias Ringwald 
964d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
965d1a1f6a4SMatthias Ringwald     UNUSED(arg);
966d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
967d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
96870b44dd4SMatthias Ringwald     sm_trigger_run();
9693deb3ec6SMatthias Ringwald }
970514d35fcSMatthias Ringwald 
9714dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9724ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9733deb3ec6SMatthias Ringwald }
9746d80b495SMatthias Ringwald #endif
9753deb3ec6SMatthias Ringwald 
9766d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
977514d35fcSMatthias Ringwald // generic cmac calculation
978d1a1f6a4SMatthias 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)){
979d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
980d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
981d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9823deb3ec6SMatthias Ringwald }
9837a766ebfSMatthias Ringwald #endif
9843deb3ec6SMatthias Ringwald 
985514d35fcSMatthias Ringwald // cmac for ATT Message signing
9867a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
987d1a1f6a4SMatthias Ringwald 
988d1a1f6a4SMatthias 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)){
989d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
990d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
991d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
992d1a1f6a4SMatthias Ringwald }
993d1a1f6a4SMatthias Ringwald 
9944dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
995d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
996d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
9974dfd504aSMatthias Ringwald         return 0;
9984dfd504aSMatthias Ringwald     }
9994dfd504aSMatthias Ringwald 
1000d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10014dfd504aSMatthias Ringwald 
1002d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10034dfd504aSMatthias Ringwald     if (offset < 3){
1004d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10054dfd504aSMatthias Ringwald     }
1006d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10074dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1008d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10094dfd504aSMatthias Ringwald     }
1010d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10114dfd504aSMatthias Ringwald }
10124dfd504aSMatthias Ringwald 
10134dfd504aSMatthias 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)){
1014514d35fcSMatthias Ringwald     // ATT Message Signing
1015d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1016d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1017d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1018514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1019d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1020d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1021d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10223deb3ec6SMatthias Ringwald }
10237a766ebfSMatthias Ringwald #endif
10243deb3ec6SMatthias Ringwald 
10253deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1026446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10273deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1028d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10293deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10303deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103142134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10323deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10335611a760SMatthias 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);
10343deb3ec6SMatthias Ringwald             } else {
1035c9b8fdd9SMatthias 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));
10363deb3ec6SMatthias Ringwald             }
10373deb3ec6SMatthias Ringwald             break;
10383deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
103942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1040c9b8fdd9SMatthias 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));
10413deb3ec6SMatthias Ringwald             } else {
10423deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10435611a760SMatthias 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);
10443deb3ec6SMatthias Ringwald             }
10453deb3ec6SMatthias Ringwald             break;
104647fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10473deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10485611a760SMatthias 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);
10493deb3ec6SMatthias Ringwald             break;
105047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1051446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1052c8c46d51SMatthias 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));
105327c32905SMatthias Ringwald             break;
10543deb3ec6SMatthias Ringwald         case JUST_WORKS:
10553deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10565611a760SMatthias 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);
10573deb3ec6SMatthias Ringwald             break;
10583deb3ec6SMatthias Ringwald         case OOB:
10593deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10603deb3ec6SMatthias Ringwald             break;
10617bbeb3adSMilanka Ringwald         default:
10627bbeb3adSMilanka Ringwald             btstack_assert(false);
10637bbeb3adSMilanka Ringwald             break;
10643deb3ec6SMatthias Ringwald     }
10653deb3ec6SMatthias Ringwald }
10663deb3ec6SMatthias Ringwald 
10673deb3ec6SMatthias Ringwald static int sm_key_distribution_all_received(sm_connection_t * sm_conn){
10683deb3ec6SMatthias Ringwald     int recv_flags;
106942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
107052f9cf63SMatthias Ringwald         // slave / responder
10711ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres));
10723deb3ec6SMatthias Ringwald     } else {
10733deb3ec6SMatthias Ringwald         // master / initiator
10741ad129beSMatthias Ringwald         recv_flags = sm_key_distribution_flags_for_set(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
10753deb3ec6SMatthias Ringwald     }
1076eddc894fSMatthias Ringwald 
1077eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1078eddc894fSMatthias Ringwald     // LTK (= encyrption information & master identification) only used exchanged for LE Legacy Connection
1079eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1080eddc894fSMatthias Ringwald         recv_flags &= ~(SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION | SM_KEYDIST_FLAG_MASTER_IDENTIFICATION);
1081eddc894fSMatthias Ringwald     }
1082eddc894fSMatthias Ringwald #endif
1083eddc894fSMatthias Ringwald 
10843deb3ec6SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, recv_flags);
108544263cccSMatthias Ringwald     return (setup->sm_key_distribution_received_set & recv_flags) == recv_flags;
10863deb3ec6SMatthias Ringwald }
10873deb3ec6SMatthias Ringwald 
1088711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10897149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10903deb3ec6SMatthias Ringwald         sm_timeout_stop();
10917149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1092711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1093c085d9ffSMatthias Ringwald 
1094c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1095c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1096c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1097c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1098c085d9ffSMatthias Ringwald         }
1099c085d9ffSMatthias Ringwald #endif
11003deb3ec6SMatthias Ringwald     }
11013deb3ec6SMatthias Ringwald }
11023deb3ec6SMatthias Ringwald 
11037d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11041dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11050ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11061dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11071dca9d8aSMatthias Ringwald }
11081dca9d8aSMatthias Ringwald 
11093deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1110bb09604fSMatthias Ringwald 
1111bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11123deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1113bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11143deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1115bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1116bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1117bb09604fSMatthias Ringwald #endif
11187ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11197ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11207ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11217ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11227ece0eaaSMatthias Ringwald         }
11237ece0eaaSMatthias Ringwald #endif
11243deb3ec6SMatthias Ringwald     }
11253deb3ec6SMatthias Ringwald     return flags;
11263deb3ec6SMatthias Ringwald }
11273deb3ec6SMatthias Ringwald 
1128d7471931SMatthias Ringwald static void sm_reset_setup(void){
11293deb3ec6SMatthias Ringwald     // fill in sm setup
1130901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1131dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
11323deb3ec6SMatthias Ringwald     sm_reset_tk();
1133d7471931SMatthias Ringwald }
1134d7471931SMatthias Ringwald 
1135d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1136d7471931SMatthias Ringwald 
1137d7471931SMatthias Ringwald     // fill in sm setup
11383deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11396535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11403deb3ec6SMatthias Ringwald 
1141a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
1142a680ba6bSMatthias Ringwald     setup->sm_have_oob_data = 0;
11439305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1144a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11453deb3ec6SMatthias Ringwald     }
11463deb3ec6SMatthias Ringwald 
1147a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1148a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11494acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11504acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1151a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11529305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11534acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1154a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1155a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1156a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1157a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11584acf7b7bSMatthias Ringwald                     setup->sm_ra);
11594acf7b7bSMatthias Ringwald             } else {
11604acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11614acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11624acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11634acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11644acf7b7bSMatthias Ringwald                     setup->sm_rb);
11654acf7b7bSMatthias Ringwald             }
1166a680ba6bSMatthias Ringwald         } else {
1167a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1168a680ba6bSMatthias Ringwald         }
1169a680ba6bSMatthias Ringwald     }
1170a680ba6bSMatthias Ringwald #endif
1171a680ba6bSMatthias Ringwald 
11723deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11743deb3ec6SMatthias Ringwald         // slave
11753deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
1176b95a5a35SMatthias Ringwald         gap_le_get_own_address(&setup->sm_s_addr_type, setup->sm_s_address);
11773deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
11786535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
11793deb3ec6SMatthias Ringwald     } else {
11803deb3ec6SMatthias Ringwald         // master
11813deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
1182b95a5a35SMatthias Ringwald         gap_le_get_own_address(&setup->sm_m_addr_type, setup->sm_m_address);
11833deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
11846535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
11853deb3ec6SMatthias Ringwald 
11863deb3ec6SMatthias Ringwald         int key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11871ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11881ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11893deb3ec6SMatthias Ringwald     }
11903deb3ec6SMatthias Ringwald 
119157132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1192*2c041b42SMatthias Ringwald     uint8_t max_encryptinon_key_size = sm_max_encryption_key_size;
1193*2c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1194*2c041b42SMatthias Ringwald     // enable SC for SC only mode
1195*2c041b42SMatthias Ringwald     if (sm_sc_only_mode){
1196*2c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1197*2c041b42SMatthias Ringwald         max_encryptinon_key_size = 16;
1198*2c041b42SMatthias Ringwald     }
1199*2c041b42SMatthias Ringwald #endif
120057132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120157132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120257132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120357132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120457132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120557132f12SMatthias Ringwald 	}
120657132f12SMatthias Ringwald #endif
12071ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1208a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1209df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1210*2c041b42SMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryptinon_key_size);
12113deb3ec6SMatthias Ringwald }
12123deb3ec6SMatthias Ringwald 
12133deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12143deb3ec6SMatthias Ringwald 
12153deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12163deb3ec6SMatthias Ringwald     int                   remote_key_request;
121742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121852f9cf63SMatthias Ringwald         // slave / responder
12193deb3ec6SMatthias Ringwald         remote_packet      = &setup->sm_m_preq;
12201ad129beSMatthias Ringwald         remote_key_request = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12213deb3ec6SMatthias Ringwald     } else {
12223deb3ec6SMatthias Ringwald         // master / initiator
12233deb3ec6SMatthias Ringwald         remote_packet      = &setup->sm_s_pres;
12241ad129beSMatthias Ringwald         remote_key_request = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12253deb3ec6SMatthias Ringwald     }
12263deb3ec6SMatthias Ringwald 
12273deb3ec6SMatthias Ringwald     // check key size
1228*2c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1229*2c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
1230*2c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
1231*2c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
1232*2c041b42SMatthias Ringwald     }
1233*2c041b42SMatthias Ringwald #endif
12341ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12354ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12363deb3ec6SMatthias Ringwald 
1237eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12383deb3ec6SMatthias Ringwald     sm_setup_tk();
12393deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12403deb3ec6SMatthias Ringwald 
12413deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12423deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12433deb3ec6SMatthias Ringwald 
1244eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1245*2c041b42SMatthias Ringwald     // Check LE SC Only mode
12463cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12473cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12483cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12493cdbe9dbSMatthias Ringwald     }
12503cdbe9dbSMatthias Ringwald 
1251eddc894fSMatthias Ringwald     // LTK (= encyrption information & master identification) only used exchanged for LE Legacy Connection
1252eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
1253eddc894fSMatthias Ringwald         remote_key_request &= ~SM_KEYDIST_ENC_KEY;
1254eddc894fSMatthias Ringwald     }
1255eddc894fSMatthias Ringwald #endif
1256eddc894fSMatthias Ringwald 
125752f9cf63SMatthias Ringwald     // identical to responder
125852f9cf63SMatthias Ringwald     sm_setup_key_distribution(remote_key_request);
125952f9cf63SMatthias Ringwald 
12603deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1261c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12623deb3ec6SMatthias Ringwald 
12633deb3ec6SMatthias Ringwald     return 0;
12643deb3ec6SMatthias Ringwald }
12653deb3ec6SMatthias Ringwald 
12663deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12673deb3ec6SMatthias Ringwald 
12683deb3ec6SMatthias Ringwald     // cache and reset context
12693deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12703deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12713deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12723deb3ec6SMatthias Ringwald 
12733deb3ec6SMatthias Ringwald     // reset context
12743deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12753deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12763deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1277711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12783deb3ec6SMatthias Ringwald 
12793deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1280d2e90122SMatthias Ringwald     sm_key_t ltk;
12811979f09cSMatthias Ringwald     bool have_ltk;
12826c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12831979f09cSMatthias Ringwald     bool trigger_pairing;
128442134bc6SMatthias Ringwald #endif
12853deb3ec6SMatthias Ringwald     switch (mode){
12863deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12873deb3ec6SMatthias Ringwald             break;
12883deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12893deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1290711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12916c44b759SMatthias Ringwald 
12926c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12936c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12946c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12956c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12966c44b759SMatthias Ringwald 
12973deb3ec6SMatthias Ringwald             switch (event){
1298a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
12993deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13003deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1301a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13026c44b759SMatthias Ringwald 
13036c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13046c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13056c44b759SMatthias Ringwald 
13066c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13076c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1308212d735eSMatthias Ringwald                         // IRK required before, continue
13096c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13106c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13116c39055aSMatthias Ringwald                             break;
13126c39055aSMatthias Ringwald                         }
1313212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1314212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1315212d735eSMatthias Ringwald                             break;
1316212d735eSMatthias Ringwald                         }
13177af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13187af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13196c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13207af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13217af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13226c44b759SMatthias Ringwald #endif
13237af5dcd5SMatthias Ringwald 
13247af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13251979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13267af5dcd5SMatthias Ringwald 
13277af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13287af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13297af5dcd5SMatthias Ringwald                             if (have_ltk){
13307af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13317af5dcd5SMatthias Ringwald                             } else {
13327af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13337af5dcd5SMatthias Ringwald                             }
13347af5dcd5SMatthias Ringwald                             sm_trigger_run();
13356c44b759SMatthias Ringwald                         }
13366c44b759SMatthias Ringwald #endif
13376c44b759SMatthias Ringwald                     } else {
13386c44b759SMatthias Ringwald 
133942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13406c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13416c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13426c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13431979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13443deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134509ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134632bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1347c245ca32SMatthias Ringwald 
1348d4af1595SMatthias Ringwald                         if (have_ltk){
13496a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1350b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135132bc5d65SMatthias Ringwald #else
135232bc5d65SMatthias Ringwald                             if (trigger_pairing){
135332bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135432bc5d65SMatthias Ringwald                             } else {
135532bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135632bc5d65SMatthias Ringwald                             }
135732bc5d65SMatthias Ringwald #endif
135832bc5d65SMatthias Ringwald                         }
135932bc5d65SMatthias Ringwald 
136032bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13616c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13625567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1363d4af1595SMatthias Ringwald                             break;
1364d4af1595SMatthias Ringwald                         }
13656c44b759SMatthias Ringwald 
13666c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13676c44b759SMatthias Ringwald                         if (trigger_pairing){
13683deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1369d4af1595SMatthias Ringwald                             break;
13703deb3ec6SMatthias Ringwald                         }
137142134bc6SMatthias Ringwald #endif
1372298ab52bSMatthias Ringwald                     }
13733deb3ec6SMatthias Ringwald                     break;
13743deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13753deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13766c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13777af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13786c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13796c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13806c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13816c39055aSMatthias Ringwald                         }
13827af5dcd5SMatthias Ringwald                         // send security request if requested
13837af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13847af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13857af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13867af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13877af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13887af5dcd5SMatthias Ringwald                         }
13896c39055aSMatthias Ringwald                         break;
13907af5dcd5SMatthias Ringwald #endif
13916c39055aSMatthias Ringwald                     }
139242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139309ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13943deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139509ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13963deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139742134bc6SMatthias Ringwald #endif
13983deb3ec6SMatthias Ringwald                     break;
13997bbeb3adSMilanka Ringwald 
14007bbeb3adSMilanka Ringwald                 default:
14017bbeb3adSMilanka Ringwald                     btstack_assert(false);
14027bbeb3adSMilanka Ringwald                     break;
14033deb3ec6SMatthias Ringwald             }
14043deb3ec6SMatthias Ringwald             break;
14053deb3ec6SMatthias Ringwald         default:
14063deb3ec6SMatthias Ringwald             break;
14073deb3ec6SMatthias Ringwald     }
14083deb3ec6SMatthias Ringwald 
14093deb3ec6SMatthias Ringwald     switch (event){
1410a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1411711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14123deb3ec6SMatthias Ringwald             break;
14133deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1414711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14153deb3ec6SMatthias Ringwald             break;
14167bbeb3adSMilanka Ringwald         default:
14177bbeb3adSMilanka Ringwald             btstack_assert(false);
14187bbeb3adSMilanka Ringwald             break;
14193deb3ec6SMatthias Ringwald     }
14203deb3ec6SMatthias Ringwald }
14213deb3ec6SMatthias Ringwald 
14223deb3ec6SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
14233deb3ec6SMatthias Ringwald 
14243deb3ec6SMatthias Ringwald     int le_db_index = -1;
14253deb3ec6SMatthias Ringwald 
142627ef8bc8SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
14271979f09cSMatthias Ringwald     bool bonding_enabed = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
142827ef8bc8SMatthias Ringwald                          & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
14294ea43905SMatthias Ringwald                          & SM_AUTHREQ_BONDING ) != 0u;
143027ef8bc8SMatthias Ringwald 
143127ef8bc8SMatthias Ringwald     if (bonding_enabed){
143227ef8bc8SMatthias Ringwald 
14333deb3ec6SMatthias Ringwald         // lookup device based on IRK
14343deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14353deb3ec6SMatthias Ringwald             int i;
1436092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14373deb3ec6SMatthias Ringwald                 sm_key_t irk;
14383deb3ec6SMatthias Ringwald                 bd_addr_t address;
1439c7e2c1a5SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14403deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, irk);
1441adf5eaa9SMatthias Ringwald                 // skip unused entries
1442c7e2c1a5SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1443c7e2c1a5SMatthias Ringwald                 // compare IRK
1444c7e2c1a5SMatthias Ringwald                 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1445c7e2c1a5SMatthias Ringwald 
14463deb3ec6SMatthias Ringwald                 log_info("sm: device found for IRK, updating");
14473deb3ec6SMatthias Ringwald                 le_db_index = i;
14483deb3ec6SMatthias Ringwald                 break;
14493deb3ec6SMatthias Ringwald             }
1450c7e2c1a5SMatthias Ringwald         } else {
1451c7e2c1a5SMatthias Ringwald             // assert IRK is set to zero
1452c7e2c1a5SMatthias Ringwald             memset(setup->sm_peer_irk, 0, 16);
14533deb3ec6SMatthias Ringwald         }
14543deb3ec6SMatthias Ringwald 
14553deb3ec6SMatthias Ringwald         // if not found, lookup via public address if possible
14563deb3ec6SMatthias Ringwald         log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1457c1ab6cc1SMatthias Ringwald         if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14583deb3ec6SMatthias Ringwald             int i;
1459092ec58eSMatthias Ringwald             for (i=0; i < le_device_db_max_count(); i++){
14603deb3ec6SMatthias Ringwald                 bd_addr_t address;
1461adf5eaa9SMatthias Ringwald                 int address_type = BD_ADDR_TYPE_UNKNOWN;
14623deb3ec6SMatthias Ringwald                 le_device_db_info(i, &address_type, address, NULL);
1463adf5eaa9SMatthias Ringwald                 // skip unused entries
1464adf5eaa9SMatthias Ringwald                 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14653deb3ec6SMatthias Ringwald                 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14665df9dc78SMatthias Ringwald                 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14673deb3ec6SMatthias Ringwald                     log_info("sm: device found for public address, updating");
14683deb3ec6SMatthias Ringwald                     le_db_index = i;
14693deb3ec6SMatthias Ringwald                     break;
14703deb3ec6SMatthias Ringwald                 }
14713deb3ec6SMatthias Ringwald             }
14723deb3ec6SMatthias Ringwald         }
14733deb3ec6SMatthias Ringwald 
14743deb3ec6SMatthias Ringwald         // if not found, add to db
147502b02cffSMatthias Ringwald         bool new_to_le_device_db = false;
14763deb3ec6SMatthias Ringwald         if (le_db_index < 0) {
14773deb3ec6SMatthias Ringwald             le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147802b02cffSMatthias Ringwald 			new_to_le_device_db = true;
14793deb3ec6SMatthias Ringwald         }
14803deb3ec6SMatthias Ringwald 
14813deb3ec6SMatthias Ringwald         if (le_db_index >= 0){
14823deb3ec6SMatthias Ringwald 
148302b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148402b02cffSMatthias Ringwald         	if (!new_to_le_device_db){
148502b02cffSMatthias Ringwald 				hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148602b02cffSMatthias Ringwald         	}
148702b02cffSMatthias Ringwald 			hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148802b02cffSMatthias Ringwald #else
148902b02cffSMatthias Ringwald 			UNUSED(new_to_le_device_db);
149002b02cffSMatthias Ringwald #endif
149102b02cffSMatthias Ringwald 
149248163929SMatthias 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);
1493e1086030SMatthias Ringwald             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14947710ebd2SMatthias Ringwald             sm_conn->sm_le_db_index = le_db_index;
149548163929SMatthias Ringwald 
1496eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14973deb3ec6SMatthias Ringwald             // store local CSRK
1498715a43d1SMatthias Ringwald             setup->sm_le_device_index = le_db_index;
1499715a43d1SMatthias Ringwald             if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15003deb3ec6SMatthias Ringwald                 log_info("sm: store local CSRK");
15013deb3ec6SMatthias Ringwald                 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15023deb3ec6SMatthias Ringwald                 le_device_db_local_counter_set(le_db_index, 0);
15033deb3ec6SMatthias Ringwald             }
15043deb3ec6SMatthias Ringwald 
15053deb3ec6SMatthias Ringwald             // store remote CSRK
15063deb3ec6SMatthias Ringwald             if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15073deb3ec6SMatthias Ringwald                 log_info("sm: store remote CSRK");
15083deb3ec6SMatthias Ringwald                 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15093deb3ec6SMatthias Ringwald                 le_device_db_remote_counter_set(le_db_index, 0);
15103deb3ec6SMatthias Ringwald             }
1511eda85fbfSMatthias Ringwald #endif
151278f44163SMatthias Ringwald             // store encryption information for secure connections: LTK generated by ECDH
151378f44163SMatthias Ringwald             if (setup->sm_use_secure_connections){
1514e6343eb6SMatthias Ringwald                 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151578f44163SMatthias Ringwald                 uint8_t zero_rand[8];
151678f44163SMatthias Ringwald                 memset(zero_rand, 0, 8);
151778f44163SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15183dc3a67dSMatthias Ringwald                     sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151978f44163SMatthias Ringwald             }
152078f44163SMatthias Ringwald 
1521e6343eb6SMatthias Ringwald             // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152278f44163SMatthias Ringwald             else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
152378f44163SMatthias Ringwald                    && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1524e6343eb6SMatthias Ringwald                 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15253deb3ec6SMatthias Ringwald                 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15263dc3a67dSMatthias Ringwald                     sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152778f44163SMatthias Ringwald 
15283deb3ec6SMatthias Ringwald             }
15293deb3ec6SMatthias Ringwald         }
153027ef8bc8SMatthias Ringwald     } else {
153127ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153227ef8bc8SMatthias Ringwald     }
15333deb3ec6SMatthias Ringwald }
15343deb3ec6SMatthias Ringwald 
1535688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1536688a08f9SMatthias Ringwald     setup->sm_pairing_failed_reason = reason;
1537688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1538688a08f9SMatthias Ringwald }
1539688a08f9SMatthias Ringwald 
1540688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1541688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1542688a08f9SMatthias Ringwald }
1543688a08f9SMatthias Ringwald 
15449af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1545688a08f9SMatthias Ringwald 
1546dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1547945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1548f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1549dc300847SMatthias Ringwald 
1550b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1551b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15521f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1553b90c4e75SMatthias Ringwald     } else {
1554b90c4e75SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_w2_cmac_for_confirmation, (void *)(uintptr_t) sm_conn->sm_handle);
1555b35a3de2SMatthias Ringwald     }
1556b35a3de2SMatthias Ringwald }
1557b35a3de2SMatthias Ringwald 
1558688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
155942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1560688a08f9SMatthias Ringwald         // Responder
15614acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15624acf7b7bSMatthias Ringwald             // generate Nb
15634acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15646ca80073SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_send_pairing_random, (void *)(uintptr_t) sm_conn->sm_handle);
15654acf7b7bSMatthias Ringwald         } else {
1566688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15674acf7b7bSMatthias Ringwald         }
1568688a08f9SMatthias Ringwald     } else {
1569688a08f9SMatthias Ringwald         // Initiator role
1570688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1571688a08f9SMatthias Ringwald             case JUST_WORKS:
1572dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1573688a08f9SMatthias Ringwald                 break;
1574688a08f9SMatthias Ringwald 
157547fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1576bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1577688a08f9SMatthias Ringwald                 break;
1578688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1579688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158047fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15814ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1582b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1583688a08f9SMatthias Ringwald                 } else {
1584dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1585688a08f9SMatthias Ringwald                 }
1586688a08f9SMatthias Ringwald                 break;
1587688a08f9SMatthias Ringwald             case OOB:
158865a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1589688a08f9SMatthias Ringwald                 break;
15907bbeb3adSMilanka Ringwald             default:
15917bbeb3adSMilanka Ringwald                 btstack_assert(false);
15927bbeb3adSMilanka Ringwald                 break;
1593688a08f9SMatthias Ringwald         }
1594688a08f9SMatthias Ringwald     }
1595688a08f9SMatthias Ringwald }
1596688a08f9SMatthias Ringwald 
1597aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1598688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1599688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1600688a08f9SMatthias Ringwald 
1601c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1602c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1603a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1604c59d0c92SMatthias Ringwald         return;
1605c59d0c92SMatthias Ringwald     }
1606c59d0c92SMatthias Ringwald 
1607bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1608bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16096857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16102bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1611b4f65634SMatthias Ringwald #endif
1612bd57ffebSMatthias Ringwald 
1613bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1614aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16156535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1616bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1617aec94140SMatthias Ringwald             break;
1618688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1619688a08f9SMatthias Ringwald             // check
1620688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1621bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1622688a08f9SMatthias Ringwald                 break;
1623688a08f9SMatthias Ringwald             }
1624bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1625688a08f9SMatthias Ringwald             break;
1626901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1627901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1628901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1629901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1630901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1631019005a0SMatthias Ringwald             break;
1632019005a0SMatthias Ringwald         }
16330346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16346535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1635bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16360346c37cSMatthias Ringwald             break;
16370346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16386535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1639bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16400346c37cSMatthias Ringwald             break;
16410346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1642b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1643b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1644b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1645b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16466535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16476535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1648893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1649bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1650019005a0SMatthias Ringwald             break;
1651901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16526535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1654901c000fSMatthias Ringwald                 // responder
1655901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1656901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1657901c000fSMatthias Ringwald                 } else {
1658901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1659901c000fSMatthias Ringwald                 }
1660901c000fSMatthias Ringwald             } else {
1661901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1662901c000fSMatthias Ringwald             }
1663901c000fSMatthias Ringwald             break;
1664901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1665901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1666901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1667aec94140SMatthias Ringwald                 break;
1668aec94140SMatthias Ringwald             }
166942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1670901c000fSMatthias Ringwald                 // responder
1671901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1672901c000fSMatthias Ringwald             } else {
1673901c000fSMatthias Ringwald                 // initiator
1674901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1675bd57ffebSMatthias Ringwald             }
1676901c000fSMatthias Ringwald             break;
16776857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
167857132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16796535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168057132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16812bacf595SMatthias Ringwald             break;
168257132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16832bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16842bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16852bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16868974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168755160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16888974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16892bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16902bacf595SMatthias Ringwald             } else {
16912bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16922bacf595SMatthias Ringwald             }
16930ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16942bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16952bacf595SMatthias Ringwald             break;
1696bdb14b0eSMatthias Ringwald #endif
1697bd57ffebSMatthias Ringwald         default:
1698bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1699bd57ffebSMatthias Ringwald             break;
1700bd57ffebSMatthias Ringwald     }
170170b44dd4SMatthias Ringwald     sm_trigger_run();
1702aec94140SMatthias Ringwald }
1703aec94140SMatthias Ringwald 
1704688a08f9SMatthias 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){
1705dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1706aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17076535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17086535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1709aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1710aec94140SMatthias Ringwald     log_info("f4 key");
1711aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1712aec94140SMatthias Ringwald     log_info("f4 message");
1713dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1714d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1715aec94140SMatthias Ringwald }
1716aec94140SMatthias Ringwald 
17170346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17180346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17190346c37cSMatthias Ringwald 
17200346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17218334d3d8SMatthias Ringwald 
17228334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17238334d3d8SMatthias Ringwald 
172440c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17250346c37cSMatthias Ringwald     // calculate salt for f5
17260346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17270346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17286535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1729d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17300346c37cSMatthias Ringwald }
17310346c37cSMatthias Ringwald 
17320346c37cSMatthias 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){
17330346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17340346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17350346c37cSMatthias Ringwald 
17360346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17370346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17386535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17396535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17406535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17416535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17426535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17436535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17440346c37cSMatthias Ringwald     log_info("f5 key");
17450346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17460346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17470346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1748d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17490346c37cSMatthias Ringwald }
17500346c37cSMatthias Ringwald 
17510346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17520346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17530346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17540346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17556535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17566535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
175742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17580346c37cSMatthias Ringwald         // responder
17590346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17600346c37cSMatthias Ringwald     } else {
17610346c37cSMatthias Ringwald         // initiator
17620346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17630346c37cSMatthias Ringwald     }
17640346c37cSMatthias Ringwald }
17650346c37cSMatthias Ringwald 
17660346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17670346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17680346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17690346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17700346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17710346c37cSMatthias Ringwald     // 1..52 setup before
17720346c37cSMatthias Ringwald     log_info("f5 key");
17730346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17740346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17750346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1776d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17770346c37cSMatthias Ringwald }
1778f92edc8eSMatthias Ringwald 
17790346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17800346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17810346c37cSMatthias Ringwald }
17820346c37cSMatthias Ringwald 
178331f061fbSMatthias 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){
17846535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17856535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17866535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17876535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
17886535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
17896535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
179031f061fbSMatthias Ringwald }
179131f061fbSMatthias Ringwald 
179231f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
179331f061fbSMatthias Ringwald     const uint16_t message_len = 65;
179431f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1795dc300847SMatthias Ringwald     log_info("f6 key");
1796dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1797dc300847SMatthias Ringwald     log_info("f6 message");
1798dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1799d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1800dc300847SMatthias Ringwald }
1801dc300847SMatthias Ringwald 
1802f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1803f92edc8eSMatthias Ringwald // - U is 256 bits
1804f92edc8eSMatthias Ringwald // - V is 256 bits
1805f92edc8eSMatthias Ringwald // - X is 128 bits
1806f92edc8eSMatthias Ringwald // - Y is 128 bits
1807bd57ffebSMatthias 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){
1808bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1809bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18106535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18126535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1813f92edc8eSMatthias Ringwald     log_info("g2 key");
1814f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1815f92edc8eSMatthias Ringwald     log_info("g2 message");
18162bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1817d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1818f92edc8eSMatthias Ringwald }
1819f92edc8eSMatthias Ringwald 
1820b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1821f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
182242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1823f92edc8eSMatthias Ringwald         // responder
1824fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1825f92edc8eSMatthias Ringwald     } else {
1826f92edc8eSMatthias Ringwald         // initiator
1827fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1828f92edc8eSMatthias Ringwald     }
1829f92edc8eSMatthias Ringwald }
1830f92edc8eSMatthias Ringwald 
1831945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18329af0f475SMatthias Ringwald     uint8_t z = 0;
183340c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18349af0f475SMatthias Ringwald         // some form of passkey
18359af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18364ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18379af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18389af0f475SMatthias Ringwald     }
1839fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18409af0f475SMatthias Ringwald }
1841688a08f9SMatthias Ringwald 
1842688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1843a680ba6bSMatthias Ringwald     // OOB
1844a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18454acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18464acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18474acf7b7bSMatthias Ringwald         } else {
18484acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18494acf7b7bSMatthias Ringwald         }
1850a680ba6bSMatthias Ringwald         return;
1851a680ba6bSMatthias Ringwald     }
1852a680ba6bSMatthias Ringwald 
1853688a08f9SMatthias Ringwald     uint8_t z = 0;
185440c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1855688a08f9SMatthias Ringwald         // some form of passkey
1856688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1857688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18584ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1859688a08f9SMatthias Ringwald     }
1860fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1861688a08f9SMatthias Ringwald }
1862688a08f9SMatthias Ringwald 
18630346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1864505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18653cf37b8cSMatthias Ringwald 
18663cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18673cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18683cf37b8cSMatthias Ringwald         return;
18693cf37b8cSMatthias Ringwald     } else {
18703cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18713cf37b8cSMatthias Ringwald     }
1872d1a1f6a4SMatthias Ringwald }
18733cf37b8cSMatthias Ringwald 
1874d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1875f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1876f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1877f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1878f3582630SMatthias Ringwald 
1879d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1880d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1881d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1882d1a1f6a4SMatthias Ringwald     // trigger next step
1883d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1884d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1885d1a1f6a4SMatthias Ringwald     }
188670b44dd4SMatthias Ringwald     sm_trigger_run();
1887dc300847SMatthias Ringwald }
1888dc300847SMatthias Ringwald 
1889dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1890dc300847SMatthias Ringwald     // calculate DHKCheck
1891dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1892dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1893dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18946535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18956535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1896dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1897dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1898dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1899dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1900dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1901dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1902dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1903dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
190442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1905dc300847SMatthias Ringwald         // responder
190631f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
190731f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1908dc300847SMatthias Ringwald     } else {
1909dc300847SMatthias Ringwald         // initiator
191031f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
191131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1912dc300847SMatthias Ringwald     }
1913dc300847SMatthias Ringwald }
1914dc300847SMatthias Ringwald 
1915019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1916019005a0SMatthias Ringwald     // validate E = f6()
1917019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1918019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1919019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19206535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19216535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1922019005a0SMatthias Ringwald 
1923019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1924019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1925019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1926019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1927019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1928019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1929019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1930019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
193142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1932019005a0SMatthias Ringwald         // responder
193331f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
193431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1935019005a0SMatthias Ringwald     } else {
1936019005a0SMatthias Ringwald         // initiator
193731f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
193831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1939019005a0SMatthias Ringwald     }
1940019005a0SMatthias Ringwald }
19412bacf595SMatthias Ringwald 
194255c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19432bacf595SMatthias Ringwald 
19442bacf595SMatthias Ringwald //
19452bacf595SMatthias Ringwald // Link Key Conversion Function h6
19462bacf595SMatthias Ringwald //
194757132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19482bacf595SMatthias Ringwald // - W is 128 bits
19492bacf595SMatthias Ringwald // - keyID is 32 bits
19502bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19512bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19522bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19532bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19542bacf595SMatthias Ringwald     log_info("h6 key");
19552bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19562bacf595SMatthias Ringwald     log_info("h6 message");
19572bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1958d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19592bacf595SMatthias Ringwald }
196057132f12SMatthias Ringwald //
196157132f12SMatthias Ringwald // Link Key Conversion Function h7
196257132f12SMatthias Ringwald //
196357132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
196457132f12SMatthias Ringwald // - SALT is 128 bits
196557132f12SMatthias Ringwald // - W    is 128 bits
196657132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
196757132f12SMatthias Ringwald 	const uint16_t message_len = 16;
196857132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
196957132f12SMatthias Ringwald 	log_info("h7 key");
197057132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
197157132f12SMatthias Ringwald 	log_info("h7 message");
197257132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
197357132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
197457132f12SMatthias Ringwald }
19752bacf595SMatthias Ringwald 
1976b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1977b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1978b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1979b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
198057132f12SMatthias Ringwald 
19812bacf595SMatthias Ringwald static void h6_calculate_ilk(sm_connection_t * sm_conn){
1982b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19832bacf595SMatthias Ringwald }
19842bacf595SMatthias Ringwald 
19852bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
19862bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
19872bacf595SMatthias Ringwald }
19882bacf595SMatthias Ringwald 
198957132f12SMatthias Ringwald static void h7_calculate_ilk(sm_connection_t * sm_conn){
199057132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
199157132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
199257132f12SMatthias Ringwald }
19939af0f475SMatthias Ringwald #endif
19949af0f475SMatthias Ringwald 
199555c62cf5SMatthias Ringwald #endif
199655c62cf5SMatthias Ringwald 
1997613da3deSMatthias Ringwald // key management legacy connections:
1998613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
1999613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2000613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2001613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2002613da3deSMatthias Ringwald 
2003613da3deSMatthias Ringwald // key management secure connections:
2004613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2005613da3deSMatthias Ringwald 
200642134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20075829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20085829ebe2SMatthias Ringwald     int encryption_key_size;
20095829ebe2SMatthias Ringwald     int authenticated;
20105829ebe2SMatthias Ringwald     int authorized;
20113dc3a67dSMatthias Ringwald     int secure_connection;
20125829ebe2SMatthias Ringwald 
20135829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20145829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20153dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20163dc3a67dSMatthias 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);
20175829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20185829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20195829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20203dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20215829ebe2SMatthias Ringwald }
202242134bc6SMatthias Ringwald #endif
2023bd57ffebSMatthias Ringwald 
202442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
202559066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20266535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
202759066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
202859066796SMatthias Ringwald     // re-establish used key encryption size
202959066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20304ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
203159066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20324ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20333dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20343dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
203559066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
203659066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
203759066796SMatthias Ringwald }
203842134bc6SMatthias Ringwald #endif
203959066796SMatthias Ringwald 
20403deb3ec6SMatthias Ringwald // distributed key generation
2041d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20423deb3ec6SMatthias Ringwald     switch (dkg_state){
20433deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20443deb3ec6SMatthias Ringwald             // already busy?
20453deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2046d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20473deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2048d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2049d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2050d1a1f6a4SMatthias 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);
2051d7f1c72eSMatthias Ringwald                 return true;
20523deb3ec6SMatthias Ringwald             }
20533deb3ec6SMatthias Ringwald             break;
20543deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20553deb3ec6SMatthias Ringwald             // already busy?
20563deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2057d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20583deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2059d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2060d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2061d1a1f6a4SMatthias 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);
2062d7f1c72eSMatthias Ringwald                 return true;
20633deb3ec6SMatthias Ringwald             }
20643deb3ec6SMatthias Ringwald             break;
20653deb3ec6SMatthias Ringwald         default:
20663deb3ec6SMatthias Ringwald             break;
20673deb3ec6SMatthias Ringwald     }
2068d7f1c72eSMatthias Ringwald     return false;
2069d7f1c72eSMatthias Ringwald }
20703deb3ec6SMatthias Ringwald 
20713deb3ec6SMatthias Ringwald // random address updates
2072d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
20733deb3ec6SMatthias Ringwald     switch (rau_state){
2074fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2075fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
20765b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2077d7f1c72eSMatthias Ringwald             return true;
20783deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
20793deb3ec6SMatthias Ringwald             // already busy?
20803deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2081d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2082d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2083d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2084d7f1c72eSMatthias Ringwald                 return true;
20853deb3ec6SMatthias Ringwald             }
20863deb3ec6SMatthias Ringwald             break;
20873deb3ec6SMatthias Ringwald         case RAU_SET_ADDRESS:
20883deb3ec6SMatthias Ringwald             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
20893deb3ec6SMatthias Ringwald             rau_state = RAU_IDLE;
20903deb3ec6SMatthias Ringwald             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
2091d7f1c72eSMatthias Ringwald             return true;
20923deb3ec6SMatthias Ringwald         default:
20933deb3ec6SMatthias Ringwald             break;
20943deb3ec6SMatthias Ringwald     }
2095d7f1c72eSMatthias Ringwald     return false;
2096d7f1c72eSMatthias Ringwald }
20973deb3ec6SMatthias Ringwald 
20983deb3ec6SMatthias Ringwald // CSRK Lookup
2099d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2100d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2101d7f1c72eSMatthias Ringwald 
21023deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21033deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21043deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2105665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2106665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21073deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21083deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21093deb3ec6SMatthias Ringwald                 // and start lookup
21103deb3ec6SMatthias 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);
21113deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21123deb3ec6SMatthias Ringwald                 break;
21133deb3ec6SMatthias Ringwald             }
21143deb3ec6SMatthias Ringwald         }
21153deb3ec6SMatthias Ringwald     }
21163deb3ec6SMatthias Ringwald 
21173deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21183deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2119665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21203deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2121665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21223deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21233deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21243deb3ec6SMatthias Ringwald         }
21253deb3ec6SMatthias Ringwald     }
21263deb3ec6SMatthias Ringwald 
21273deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21283deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2129092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2130092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2131adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21323deb3ec6SMatthias Ringwald             bd_addr_t addr;
21333deb3ec6SMatthias Ringwald             sm_key_t irk;
21343deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21353deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21363deb3ec6SMatthias Ringwald 
2137adf5eaa9SMatthias Ringwald             // skip unused entries
2138adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2139adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2140adf5eaa9SMatthias Ringwald                 continue;
2141adf5eaa9SMatthias Ringwald             }
2142adf5eaa9SMatthias Ringwald 
21435df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21443deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2145a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21463deb3ec6SMatthias Ringwald                 break;
21473deb3ec6SMatthias Ringwald             }
21483deb3ec6SMatthias Ringwald 
2149a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2150a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21513deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21523deb3ec6SMatthias Ringwald                 continue;
21533deb3ec6SMatthias Ringwald             }
21543deb3ec6SMatthias Ringwald 
21553deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21563deb3ec6SMatthias Ringwald 
21573deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21588314c363SMatthias Ringwald             log_info_key("IRK", irk);
21593deb3ec6SMatthias Ringwald 
21606535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2161d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21623deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2163d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2164d1a1f6a4SMatthias 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);
2165d7f1c72eSMatthias Ringwald             return true;
21663deb3ec6SMatthias Ringwald         }
21673deb3ec6SMatthias Ringwald 
2168092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
21693deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
21703deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
21713deb3ec6SMatthias Ringwald         }
21723deb3ec6SMatthias Ringwald     }
2173d7f1c72eSMatthias Ringwald     return false;
2174d7f1c72eSMatthias Ringwald }
21753deb3ec6SMatthias Ringwald 
2176d7f1c72eSMatthias Ringwald // SC OOB
2177d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2178c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2179c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2180c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2181c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2182c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2183c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2184d7f1c72eSMatthias Ringwald             return true;
2185c59d0c92SMatthias Ringwald         default:
2186c59d0c92SMatthias Ringwald             break;
2187c59d0c92SMatthias Ringwald     }
2188c59d0c92SMatthias Ringwald #endif
2189d7f1c72eSMatthias Ringwald     return false;
2190d7f1c72eSMatthias Ringwald }
2191275aafe8SMatthias Ringwald 
219241d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2193d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2194d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
219541d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2196e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
219741d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
219841d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
219941d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
220041d32297SMatthias Ringwald             // responder side
220141d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
220241d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
220341d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2204d7f1c72eSMatthias Ringwald                 return true;
22054b8b5afeSMatthias Ringwald 
22064b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2207*2c041b42SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2208*2c041b42SMatthias Ringwald                 // respond with auth req error if received sec req with SC = 0 in SC Only mode
2209*2c041b42SMatthias Ringwald                 btstack_assert(sm_connection->sm_role == 0);
2210*2c041b42SMatthias Ringwald                 sm_connection->sm_engine_state = SM_INITIATOR_CONNECTED;
2211*2c041b42SMatthias Ringwald                 uint8_t buffer[2];
2212*2c041b42SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2213*2c041b42SMatthias Ringwald                 buffer[1] = SM_REASON_AUTHENTHICATION_REQUIREMENTS;
2214*2c041b42SMatthias Ringwald                 l2cap_send_connectionless(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t *) buffer, sizeof(buffer));
2215*2c041b42SMatthias Ringwald                 break;
2216*2c041b42SMatthias Ringwald             }
22174b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22184b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22194b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2220e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22214b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22224b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2223d7f1c72eSMatthias Ringwald                         return true;
22244b8b5afeSMatthias Ringwald                     default:
22254b8b5afeSMatthias Ringwald                         break;
22264b8b5afeSMatthias Ringwald                 }
22274b8b5afeSMatthias Ringwald                 break;
22284b8b5afeSMatthias Ringwald #endif
222941d32297SMatthias Ringwald             default:
223041d32297SMatthias Ringwald                 break;
223141d32297SMatthias Ringwald         }
223241d32297SMatthias Ringwald     }
2233d7f1c72eSMatthias Ringwald     return false;
2234d7f1c72eSMatthias Ringwald }
22353deb3ec6SMatthias Ringwald 
2236d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22373deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2238d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22393deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22407149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2241665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22423deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22433deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22441979f09cSMatthias Ringwald         bool done = true;
22453deb3ec6SMatthias Ringwald         int err;
224642134bc6SMatthias Ringwald         UNUSED(err);
224734b6528fSMatthias Ringwald 
224834b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
224934b6528fSMatthias Ringwald         // assert ec key is ready
2250505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2251178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2252178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
225334b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
225434b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
225534b6528fSMatthias Ringwald             }
225634b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
225734b6528fSMatthias Ringwald                 continue;
225834b6528fSMatthias Ringwald             }
225934b6528fSMatthias Ringwald         }
226034b6528fSMatthias Ringwald #endif
226134b6528fSMatthias Ringwald 
22623deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
226342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
22643deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
22653deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
226642134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2267549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
226806cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
226987014f74SMatthias Ringwald #endif
227087014f74SMatthias Ringwald #endif
227134c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
22725567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
227334c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2274549ad5d2SMatthias Ringwald #endif
227587014f74SMatthias Ringwald 				// just lock context
227687014f74SMatthias Ringwald 				break;
22773deb3ec6SMatthias Ringwald             default:
22781979f09cSMatthias Ringwald                 done = false;
22793deb3ec6SMatthias Ringwald                 break;
22803deb3ec6SMatthias Ringwald         }
22813deb3ec6SMatthias Ringwald         if (done){
22827149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
22837149bde5SMatthias 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);
22843deb3ec6SMatthias Ringwald         }
22853deb3ec6SMatthias Ringwald     }
2286d7f1c72eSMatthias Ringwald }
2287d7f1c72eSMatthias Ringwald 
2288403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2289403280b9SMatthias Ringwald     int i;
2290403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2291403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2292403280b9SMatthias Ringwald     uint8_t action = 0;
2293403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2294403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2295403280b9SMatthias Ringwald             bool clear_flag = true;
2296403280b9SMatthias Ringwald             switch (i){
2297403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2298403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2299403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2300403280b9SMatthias Ringwald                 default:
2301403280b9SMatthias Ringwald                     break;
2302403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2303403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2304403280b9SMatthias Ringwald                     num_actions--;
2305403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2306403280b9SMatthias Ringwald                     break;
2307403280b9SMatthias Ringwald             }
2308403280b9SMatthias Ringwald             if (clear_flag){
2309403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2310403280b9SMatthias Ringwald             }
2311403280b9SMatthias Ringwald             action = i;
2312403280b9SMatthias Ringwald             break;
2313403280b9SMatthias Ringwald         }
2314403280b9SMatthias Ringwald     }
2315403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2316403280b9SMatthias Ringwald 
2317403280b9SMatthias Ringwald     // send keypress notification
2318403280b9SMatthias Ringwald     uint8_t buffer[2];
2319403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2320403280b9SMatthias Ringwald     buffer[1] = action;
2321403280b9SMatthias Ringwald     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2322403280b9SMatthias Ringwald 
2323403280b9SMatthias Ringwald     // try
2324403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2325403280b9SMatthias Ringwald }
2326403280b9SMatthias Ringwald 
2327403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2328403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2329403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2330403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2331403280b9SMatthias Ringwald         uint8_t buffer[17];
2332403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2333403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2334403280b9SMatthias Ringwald         l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2335403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2336403280b9SMatthias Ringwald         return;
2337403280b9SMatthias Ringwald     }
2338403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2339403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2340403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2341403280b9SMatthias Ringwald         uint8_t buffer[11];
2342403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2343403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2344403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2345403280b9SMatthias Ringwald         l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2346403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2347403280b9SMatthias Ringwald         return;
2348403280b9SMatthias Ringwald     }
2349403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2350403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2351403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2352403280b9SMatthias Ringwald         uint8_t buffer[17];
2353403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2354403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2355403280b9SMatthias Ringwald         l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2356403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2357403280b9SMatthias Ringwald         return;
2358403280b9SMatthias Ringwald     }
2359403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2360403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2361403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2362403280b9SMatthias Ringwald         bd_addr_t local_address;
2363403280b9SMatthias Ringwald         uint8_t buffer[8];
2364403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2365403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2366403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2367403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2368403280b9SMatthias Ringwald                 // public or static random
2369403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2370403280b9SMatthias Ringwald                 break;
2371403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2372403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2373403280b9SMatthias Ringwald                 // fallback to public
2374403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2375403280b9SMatthias Ringwald                 buffer[1] = 0;
2376403280b9SMatthias Ringwald                 break;
2377403280b9SMatthias Ringwald             default:
2378403280b9SMatthias Ringwald                 btstack_assert(false);
2379403280b9SMatthias Ringwald                 break;
2380403280b9SMatthias Ringwald         }
2381403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2382403280b9SMatthias Ringwald         l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2383403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2384403280b9SMatthias Ringwald         return;
2385403280b9SMatthias Ringwald     }
2386403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2387403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2388403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2389403280b9SMatthias Ringwald 
2390403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2391403280b9SMatthias Ringwald         // hack to reproduce test runs
2392403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2393403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2394403280b9SMatthias Ringwald                     }
2395403280b9SMatthias Ringwald 
2396403280b9SMatthias Ringwald                     // store local CSRK
2397403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2398403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2399403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2400403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2401403280b9SMatthias Ringwald                     }
2402403280b9SMatthias Ringwald #endif
2403403280b9SMatthias Ringwald 
2404403280b9SMatthias Ringwald         uint8_t buffer[17];
2405403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2406403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2407403280b9SMatthias Ringwald         l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2408403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2409403280b9SMatthias Ringwald         return;
2410403280b9SMatthias Ringwald     }
2411403280b9SMatthias Ringwald     btstack_assert(false);
2412403280b9SMatthias Ringwald }
2413403280b9SMatthias Ringwald 
2414bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2415bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2416bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2417bbd73538SMatthias Ringwald     // - use secure connections
2418bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2419bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2420bbd73538SMatthias 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;
2421bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2422bbd73538SMatthias Ringwald     // - need identity address / public addr
2423bbd73538SMatthias 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);
2424bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2425bbd73538SMatthias 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)
2426bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2427bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2428bbd73538SMatthias 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.
2429bbd73538SMatthias Ringwald     uint8_t link_key[16];
2430bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2431bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2432bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2433bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2434bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2435bbd73538SMatthias Ringwald         return false;
2436bbd73538SMatthias Ringwald     }
2437bbd73538SMatthias Ringwald     // get started (all of the above are true)
2438bbd73538SMatthias Ringwald     return true;
2439bbd73538SMatthias Ringwald #else
2440bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2441bbd73538SMatthias Ringwald 	return false;
2442bbd73538SMatthias Ringwald #endif
2443bbd73538SMatthias Ringwald }
2444bbd73538SMatthias Ringwald 
24456f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24466f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24476f7422f1SMatthias 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;
24486f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24496f7422f1SMatthias Ringwald     } else {
24506f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24516f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24526f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24536f7422f1SMatthias Ringwald     }
24546f7422f1SMatthias Ringwald }
24556f7422f1SMatthias Ringwald 
2456af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2457af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2458af7ef9d1SMatthias 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;
2459af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2460af7ef9d1SMatthias Ringwald     } else {
2461af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2462af7ef9d1SMatthias Ringwald     }
2463af7ef9d1SMatthias Ringwald }
2464af7ef9d1SMatthias Ringwald 
2465d7f1c72eSMatthias Ringwald static void sm_run(void){
2466d7f1c72eSMatthias Ringwald 
2467d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2468d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2469d7f1c72eSMatthias Ringwald 
2470d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2471d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2472d7f1c72eSMatthias Ringwald 
2473d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2474d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2475d7f1c72eSMatthias Ringwald 
2476d7f1c72eSMatthias Ringwald     bool done;
2477d7f1c72eSMatthias Ringwald 
2478d7f1c72eSMatthias Ringwald     //
2479d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2480d7f1c72eSMatthias Ringwald     //
2481d7f1c72eSMatthias Ringwald 
2482d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2483d7f1c72eSMatthias Ringwald     if (done) return;
2484d7f1c72eSMatthias Ringwald 
2485d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2486d7f1c72eSMatthias Ringwald     if (done) return;
2487d7f1c72eSMatthias Ringwald 
2488d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2489d7f1c72eSMatthias Ringwald     if (done) return;
2490d7f1c72eSMatthias Ringwald 
2491d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2492d7f1c72eSMatthias Ringwald     if (done) return;
2493d7f1c72eSMatthias Ringwald 
2494d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2495d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2496d7f1c72eSMatthias Ringwald 
2497d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2498d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2499d7f1c72eSMatthias Ringwald     if (done) return;
2500d7f1c72eSMatthias Ringwald 
2501d7f1c72eSMatthias Ringwald     //
2502d7f1c72eSMatthias Ringwald     // active connection handling
2503d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2504d7f1c72eSMatthias Ringwald 
2505d7f1c72eSMatthias Ringwald     while (true) {
2506d7f1c72eSMatthias Ringwald 
2507d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2508d7f1c72eSMatthias Ringwald 
2509d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25103deb3ec6SMatthias Ringwald 
25113deb3ec6SMatthias Ringwald         //
25123deb3ec6SMatthias Ringwald         // active connection handling
25133deb3ec6SMatthias Ringwald         //
25143deb3ec6SMatthias Ringwald 
25153cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25163cf37b8cSMatthias Ringwald         if (!connection) {
25173cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25183cf37b8cSMatthias Ringwald             return;
25193cf37b8cSMatthias Ringwald         }
25203cf37b8cSMatthias Ringwald 
25213deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25227149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25237149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25247149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2525b170b20fSMatthias Ringwald             return;
2526b170b20fSMatthias Ringwald         }
25273deb3ec6SMatthias Ringwald 
25283d7fe1e9SMatthias Ringwald         // send keypress notifications
2529dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2530403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2531d7471931SMatthias Ringwald             return;
25323d7fe1e9SMatthias Ringwald         }
25333d7fe1e9SMatthias Ringwald 
25343deb3ec6SMatthias Ringwald         int key_distribution_flags;
253542134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2536b6afa23eSMatthias Ringwald 		int err;
2537b6afa23eSMatthias Ringwald 		UNUSED(err);
25389b75de03SMatthias Ringwald         bool have_ltk;
25399b75de03SMatthias Ringwald         uint8_t ltk[16];
25403deb3ec6SMatthias Ringwald 
25413deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2542dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2543dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2544dd4a08fbSMatthias Ringwald         }
25453deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25463deb3ec6SMatthias Ringwald 
25473deb3ec6SMatthias Ringwald             // general
25483deb3ec6SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
25493deb3ec6SMatthias Ringwald                 uint8_t buffer[2];
25503deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
25513deb3ec6SMatthias Ringwald                 buffer[1] = setup->sm_pairing_failed_reason;
25523deb3ec6SMatthias Ringwald                 connection->sm_engine_state = connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
25533deb3ec6SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
25540ccf6c9cSMatthias Ringwald                 sm_pairing_complete(connection, ERROR_CODE_AUTHENTICATION_FAILURE, setup->sm_pairing_failed_reason);
25553deb3ec6SMatthias Ringwald                 sm_done_for_handle(connection->sm_handle);
25563deb3ec6SMatthias Ringwald                 break;
25573deb3ec6SMatthias Ringwald             }
25583deb3ec6SMatthias Ringwald 
2559f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2560aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2561aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2562aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2563aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2564aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2565aec94140SMatthias Ringwald                 break;
2566688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2567688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2568688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2569688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2570688a08f9SMatthias Ringwald                 break;
2571dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2572dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2573dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2574dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2575dc300847SMatthias Ringwald                 break;
2576019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2577b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2578019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
25790346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
25800346c37cSMatthias Ringwald                 break;
25810346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2582b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25830346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
25840346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
25850346c37cSMatthias Ringwald                 break;
25860346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2587b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25880346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
25890346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
25900346c37cSMatthias Ringwald                 break;
25910346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2592b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
25930346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
25940346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2595019005a0SMatthias Ringwald                 break;
2596bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2597b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2598bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2599b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2600bd57ffebSMatthias Ringwald                 break;
26016857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
260257132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
26032bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
260457132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
26052bacf595SMatthias Ringwald                 h6_calculate_ilk(connection);
26062bacf595SMatthias Ringwald                 break;
260757132f12SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
26082bacf595SMatthias Ringwald                 if (!sm_cmac_ready()) break;
260957132f12SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
26102bacf595SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
26112bacf595SMatthias Ringwald                 break;
261257132f12SMatthias Ringwald 			case SM_SC_W2_CALCULATE_ILK_USING_H7:
261357132f12SMatthias Ringwald 				if (!sm_cmac_ready()) break;
261457132f12SMatthias Ringwald 				connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
261557132f12SMatthias Ringwald 				h7_calculate_ilk(connection);
261657132f12SMatthias Ringwald 				break;
2617aec94140SMatthias Ringwald #endif
2618a756d52bSMatthias Ringwald #endif
261941d32297SMatthias Ringwald 
262042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26213deb3ec6SMatthias Ringwald             // initiator side
2622f32b7a88SMatthias Ringwald 
26235567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2624f32b7a88SMatthias Ringwald 				sm_reset_setup();
2625f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2626daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2627f32b7a88SMatthias Ringwald 
26283deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26299c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26305567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26313deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2632c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2633c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26343deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26353deb3ec6SMatthias Ringwald                 return;
26363deb3ec6SMatthias Ringwald             }
26373deb3ec6SMatthias Ringwald 
2638b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2639b26f445fSMatthias Ringwald 				sm_reset_setup();
2640b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2641b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2642d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2643b26f445fSMatthias Ringwald 
26441ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26453deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
26463deb3ec6SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26473deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26483deb3ec6SMatthias Ringwald                 break;
264942134bc6SMatthias Ringwald #endif
26503deb3ec6SMatthias Ringwald 
265127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
265241d32297SMatthias Ringwald 
2653c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26541979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26551979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
265627c32905SMatthias Ringwald                 uint8_t buffer[65];
265727c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
265827c32905SMatthias Ringwald                 //
2659fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2660fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2661e53be891SMatthias Ringwald 
2662349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2663349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2664349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2665349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2666349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2667349d0adbSMatthias Ringwald                 }
2668349d0adbSMatthias Ringwald #endif
2669349d0adbSMatthias Ringwald 
267045a61d50SMatthias Ringwald                 // stk generation method
267145a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
267245a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
267345a61d50SMatthias Ringwald                     case JUST_WORKS:
267447fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
267542134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
267607036a04SMatthias Ringwald                             // responder
26771979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2678b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
267927c32905SMatthias Ringwald                         } else {
268007036a04SMatthias Ringwald                             // initiator
2681c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
268227c32905SMatthias Ringwald                         }
268345a61d50SMatthias Ringwald                         break;
268445a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
268545a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
268647fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
268707036a04SMatthias Ringwald                         // use random TK for display
26886535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
26896535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
269045a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
269107036a04SMatthias Ringwald 
269242134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269345a61d50SMatthias Ringwald                             // responder
2694c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
269545a61d50SMatthias Ringwald                         } else {
269645a61d50SMatthias Ringwald                             // initiator
2697c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
269845a61d50SMatthias Ringwald                         }
26991979f09cSMatthias Ringwald                         trigger_user_response = true;
270045a61d50SMatthias Ringwald                         break;
270145a61d50SMatthias Ringwald                     case OOB:
270265a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
270365a9a04eSMatthias Ringwald                             // responder
270465a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
270565a9a04eSMatthias Ringwald                         } else {
270665a9a04eSMatthias Ringwald                             // initiator
270765a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270865a9a04eSMatthias Ringwald                         }
270945a61d50SMatthias Ringwald                         break;
27107bbeb3adSMilanka Ringwald                     default:
27117bbeb3adSMilanka Ringwald                         btstack_assert(false);
27127bbeb3adSMilanka Ringwald                         break;
271345a61d50SMatthias Ringwald                 }
271445a61d50SMatthias Ringwald 
271527c32905SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
271627c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2717644c6a1dSMatthias Ringwald 
2718b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2719644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2720644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2721644c6a1dSMatthias Ringwald                 }
2722b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2723b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2724b90c4e75SMatthias Ringwald                 }
272527c32905SMatthias Ringwald                 break;
272627c32905SMatthias Ringwald             }
2727c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2728e53be891SMatthias Ringwald                 uint8_t buffer[17];
2729e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27309af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
273142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2732c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2733e53be891SMatthias Ringwald                 } else {
2734c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2735e53be891SMatthias Ringwald                 }
2736e53be891SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2737e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2738e53be891SMatthias Ringwald                 break;
2739e53be891SMatthias Ringwald             }
2740c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2741e53be891SMatthias Ringwald                 uint8_t buffer[17];
2742e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2743e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27449d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27454ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
274640c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
274742134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
274845a61d50SMatthias Ringwald                         // responder
2749c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
275045a61d50SMatthias Ringwald                     } else {
275145a61d50SMatthias Ringwald                         // initiator
2752c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
275345a61d50SMatthias Ringwald                     }
275445a61d50SMatthias Ringwald                 } else {
275540c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
275642134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2757e53be891SMatthias Ringwald                         // responder
275847fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
275940c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2760901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27612886623dSMatthias Ringwald                         } else {
276240c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27632886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2764446a8c36SMatthias Ringwald                         }
2765e53be891SMatthias Ringwald                     } else {
2766136d331aSMatthias Ringwald                         // initiator
2767c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2768e53be891SMatthias Ringwald                     }
276945a61d50SMatthias Ringwald                 }
2770e53be891SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2771e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2772e53be891SMatthias Ringwald                 break;
2773e53be891SMatthias Ringwald             }
2774c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2775e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2776e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2777e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2778dc300847SMatthias Ringwald 
277942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2780c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2781e53be891SMatthias Ringwald                 } else {
2782c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2783e53be891SMatthias Ringwald                 }
2784e083ca23SMatthias Ringwald 
2785e53be891SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2786e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2787e53be891SMatthias Ringwald                 break;
2788e53be891SMatthias Ringwald             }
2789e53be891SMatthias Ringwald 
2790e53be891SMatthias Ringwald #endif
279142134bc6SMatthias Ringwald 
279242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2793dd12a62bSMatthias Ringwald 
279487014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
279587014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
279687014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
279787014f74SMatthias Ringwald 				l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL,  (uint8_t *) buffer, sizeof(buffer));
2798c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
279987014f74SMatthias Ringwald 				break;
280087014f74SMatthias Ringwald 			}
280187014f74SMatthias Ringwald 
280238196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
280338196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
280438196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
280538196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
280638196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
280738196718SMatthias Ringwald 						// start using context by loading security info
280838196718SMatthias Ringwald 						sm_reset_setup();
280938196718SMatthias Ringwald 						sm_load_security_info(connection);
281038196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
281138196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
281238196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
281342646f38SMatthias Ringwald                             sm_reencryption_started(connection);
281438196718SMatthias Ringwald                             sm_trigger_run();
281538196718SMatthias Ringwald 							break;
281638196718SMatthias Ringwald 						}
281738196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
281838196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
281938196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
282038196718SMatthias Ringwald 						return;
282138196718SMatthias Ringwald 					default:
282238196718SMatthias Ringwald 						// just wait until IRK lookup is completed
282338196718SMatthias Ringwald 						break;
282438196718SMatthias Ringwald 				}
282538196718SMatthias Ringwald 				break;
282638196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
282738196718SMatthias Ringwald 
2828b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2829b6afa23eSMatthias Ringwald                 sm_reset_setup();
28309b75de03SMatthias Ringwald 
28319b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28329b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28339b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28349b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28359b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28369b75de03SMatthias Ringwald                         if (have_ltk){
28379b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
283819a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28399b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28409b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28419b75de03SMatthias Ringwald                         }
28429b75de03SMatthias Ringwald                         break;
28439b75de03SMatthias Ringwald                     default:
28449b75de03SMatthias Ringwald                         break;
28459b75de03SMatthias Ringwald                 }
28469b75de03SMatthias Ringwald 
2847b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2848d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
284939543d07SMatthias Ringwald 
2850b6afa23eSMatthias Ringwald 				// recover pairing request
2851b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2852b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2853b6afa23eSMatthias Ringwald 
2854b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2855b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2856b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2857b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2858b6afa23eSMatthias Ringwald                     }
2859b6afa23eSMatthias Ringwald #endif
28609305033eSMatthias Ringwald 				if (err != 0){
2861b6afa23eSMatthias Ringwald 					setup->sm_pairing_failed_reason = err;
2862b6afa23eSMatthias Ringwald 					connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
2863b6afa23eSMatthias Ringwald 					sm_trigger_run();
2864b6afa23eSMatthias Ringwald 					break;
2865b6afa23eSMatthias Ringwald 				}
2866b6afa23eSMatthias Ringwald 
2867b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2868b6afa23eSMatthias Ringwald 
2869b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2870b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2871b6afa23eSMatthias 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);
2872b6afa23eSMatthias Ringwald 					break;
2873b6afa23eSMatthias Ringwald 				}
2874b6afa23eSMatthias Ringwald 
2875b6afa23eSMatthias Ringwald 				/* fall through */
2876b6afa23eSMatthias Ringwald 
28773deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28781ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2879f55bd529SMatthias Ringwald 
2880f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28813deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28821ad129beSMatthias Ringwald 
2883f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2884f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2885f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2886f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2887f55bd529SMatthias Ringwald                 }
2888f55bd529SMatthias Ringwald #endif
2889f55bd529SMatthias Ringwald                 // setup in response
2890f55bd529SMatthias 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);
2891f55bd529SMatthias 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);
2892f55bd529SMatthias Ringwald 
2893f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
2894f55bd529SMatthias Ringwald                 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
2895f55bd529SMatthias Ringwald 
289627c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2897c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
28980b8af2a5SMatthias Ringwald                 } else {
28990b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
290027c32905SMatthias Ringwald                 }
29010b8af2a5SMatthias Ringwald 
29023deb3ec6SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29033deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2904446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2905c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29063deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2907446a8c36SMatthias Ringwald                 }
29083deb3ec6SMatthias Ringwald                 return;
290942134bc6SMatthias Ringwald #endif
29103deb3ec6SMatthias Ringwald 
29113deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29123deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29133deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29149c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
291542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29163deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29173deb3ec6SMatthias Ringwald                 } else {
29183deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29193deb3ec6SMatthias Ringwald                 }
29203deb3ec6SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
29213deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29223deb3ec6SMatthias Ringwald                 break;
29233deb3ec6SMatthias Ringwald             }
29243deb3ec6SMatthias Ringwald 
2925d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29263deb3ec6SMatthias Ringwald                 // already busy?
29273deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2928d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2929d1a1f6a4SMatthias 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);
2930d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2931d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2932f3582630SMatthias 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);
29333deb3ec6SMatthias Ringwald                 break;
29343deb3ec6SMatthias Ringwald 
29353deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29363deb3ec6SMatthias Ringwald                 // already busy?
29373deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29383deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2939d1a1f6a4SMatthias 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);
2940d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2941d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2942f3582630SMatthias 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);
29433deb3ec6SMatthias Ringwald                 break;
2944d1a1f6a4SMatthias Ringwald 
29453deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29463deb3ec6SMatthias Ringwald                 // already busy?
29473deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29483deb3ec6SMatthias Ringwald                 // calculate STK
294942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2950d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29513deb3ec6SMatthias Ringwald                 } else {
2952d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29533deb3ec6SMatthias Ringwald                 }
2954d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2955d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2956f3582630SMatthias 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);
29573deb3ec6SMatthias Ringwald                 break;
2958d1a1f6a4SMatthias Ringwald 
29593deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29603deb3ec6SMatthias Ringwald                 // already busy?
29613deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29623deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29639ad0dd7cSMatthias Ringwald 
29649ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29659ad0dd7cSMatthias Ringwald                 // r' = padding || r
29669ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29679ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29686535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29699ad0dd7cSMatthias Ringwald 
29703deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2971d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2972d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2973f3582630SMatthias 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);
2974d1a1f6a4SMatthias Ringwald                 break;
2975d1a1f6a4SMatthias Ringwald 
29763deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29773deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29783deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29799c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
298042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29813deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29823deb3ec6SMatthias Ringwald                 } else {
29833deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
29843deb3ec6SMatthias Ringwald                 }
29853deb3ec6SMatthias Ringwald                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
29863deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29873deb3ec6SMatthias Ringwald                 return;
29883deb3ec6SMatthias Ringwald             }
298942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
29903deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
29913deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
29929c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
29933deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
29943deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
29953deb3ec6SMatthias Ringwald                 return;
29963deb3ec6SMatthias Ringwald             }
2997d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
29983deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
29999c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30005567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30013deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30023deb3ec6SMatthias Ringwald                 return;
30033deb3ec6SMatthias Ringwald             }
3004dd12a62bSMatthias Ringwald 
3005dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30063deb3ec6SMatthias Ringwald                 // already busy?
30073deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30083deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3009c61cfe5aSMatthias Ringwald 
3010dd12a62bSMatthias Ringwald 				sm_reset_setup();
3011dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3012dd12a62bSMatthias Ringwald 
301342646f38SMatthias Ringwald 				sm_reencryption_started(connection);
301442646f38SMatthias Ringwald 
3015c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3016c61cfe5aSMatthias Ringwald                 // r' = padding || r
3017c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3018c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30196535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3020c61cfe5aSMatthias Ringwald 
30213deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3022d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3023d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3024f3582630SMatthias 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);
30253deb3ec6SMatthias Ringwald                 return;
302642134bc6SMatthias Ringwald #endif
302742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
302842134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
302942134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
303042134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
303142134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
303242134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
303342134bc6SMatthias Ringwald                 return;
303442134bc6SMatthias Ringwald             }
303542134bc6SMatthias Ringwald #endif
30363deb3ec6SMatthias Ringwald 
30373deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3038403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3039403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30403deb3ec6SMatthias Ringwald                     return;
30413deb3ec6SMatthias Ringwald                 }
30423deb3ec6SMatthias Ringwald 
30433deb3ec6SMatthias Ringwald                 // keys are sent
304442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30453deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
30463deb3ec6SMatthias Ringwald                     if (sm_key_distribution_all_received(connection)){
30473deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3048f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3049f5020412SMatthias Ringwald                         // start CTKD right away
3050f5020412SMatthias Ringwald                         continue;
30513deb3ec6SMatthias Ringwald                     } else {
30523deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30533deb3ec6SMatthias Ringwald                     }
30543deb3ec6SMatthias Ringwald                 } else {
30551dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30563deb3ec6SMatthias Ringwald                 }
30573deb3ec6SMatthias Ringwald                 break;
30583deb3ec6SMatthias Ringwald 
30593deb3ec6SMatthias Ringwald             default:
30603deb3ec6SMatthias Ringwald                 break;
30613deb3ec6SMatthias Ringwald         }
30623deb3ec6SMatthias Ringwald 
30633deb3ec6SMatthias Ringwald         // check again if active connection was released
30647149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
30653deb3ec6SMatthias Ringwald     }
30663deb3ec6SMatthias Ringwald }
30673deb3ec6SMatthias Ringwald 
3068d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3069d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3070f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
307104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
307204678764SMatthias Ringwald 
3073f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3074f3582630SMatthias Ringwald     if (connection == NULL) return;
3075f3582630SMatthias Ringwald 
3076d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
307704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3078f3582630SMatthias 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);
3079d1a1f6a4SMatthias Ringwald }
30803deb3ec6SMatthias Ringwald 
3081d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3082f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
308304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
308404678764SMatthias Ringwald 
3085f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3086f3582630SMatthias Ringwald     if (connection == NULL) return;
3087f3582630SMatthias Ringwald 
30888314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
30893deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
309070b44dd4SMatthias Ringwald     sm_trigger_run();
3091d1a1f6a4SMatthias Ringwald }
3092d1a1f6a4SMatthias Ringwald 
3093d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3094d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3095f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
309604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
309704678764SMatthias Ringwald 
3098f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3099f3582630SMatthias Ringwald     if (connection == NULL) return;
3100f3582630SMatthias Ringwald 
3101d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
310204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3103f3582630SMatthias 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);
3104d1a1f6a4SMatthias Ringwald }
3105d1a1f6a4SMatthias Ringwald 
3106d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3107f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
310804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
310904678764SMatthias Ringwald 
3110f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3111f3582630SMatthias Ringwald     if (connection == NULL) return;
3112f3582630SMatthias Ringwald 
3113d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3114d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
31153deb3ec6SMatthias Ringwald         setup->sm_pairing_failed_reason = SM_REASON_CONFIRM_VALUE_FAILED;
31163deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
311770b44dd4SMatthias Ringwald         sm_trigger_run();
31183deb3ec6SMatthias Ringwald         return;
31193deb3ec6SMatthias Ringwald     }
312042134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31213deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
312270b44dd4SMatthias Ringwald         sm_trigger_run();
31233deb3ec6SMatthias Ringwald     } else {
3124d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3125d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3126f3582630SMatthias Ringwald         btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_stk, (void *)(uintptr_t) connection->sm_handle);
31273deb3ec6SMatthias Ringwald     }
31283deb3ec6SMatthias Ringwald }
3129d1a1f6a4SMatthias Ringwald 
3130d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
313104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3132f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
313304678764SMatthias Ringwald 
3134f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3135f3582630SMatthias Ringwald     if (connection == NULL) return;
3136f3582630SMatthias Ringwald 
31373deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
31388314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
313942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
31403deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
31413deb3ec6SMatthias Ringwald     } else {
31423deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
31433deb3ec6SMatthias Ringwald     }
314470b44dd4SMatthias Ringwald     sm_trigger_run();
3145d1a1f6a4SMatthias Ringwald }
3146d1a1f6a4SMatthias Ringwald 
3147d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3148d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3149f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
315004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
315104678764SMatthias Ringwald 
3152f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3153f3582630SMatthias Ringwald     if (connection == NULL) return;
3154f3582630SMatthias Ringwald 
3155d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31563deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31573deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
31583deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
31593deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31603deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31613deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3162d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
316304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3164f3582630SMatthias Ringwald     btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph3_ltk, (void *)(uintptr_t) connection->sm_handle);
31653deb3ec6SMatthias Ringwald }
3166d1a1f6a4SMatthias Ringwald 
31672a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3168d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3169d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
317004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3171f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
317204678764SMatthias Ringwald 
3173f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3174f3582630SMatthias Ringwald     if (connection == NULL) return;
3175f3582630SMatthias Ringwald 
3176d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
31773deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
31783deb3ec6SMatthias Ringwald 
31793deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
31803deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
31813deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
31823deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
31833deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3184d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
318504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3186f3582630SMatthias Ringwald     btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph4_ltk, (void *)(uintptr_t) connection->sm_handle);
31873deb3ec6SMatthias Ringwald }
31882a526f21SMatthias Ringwald #endif
3189d1a1f6a4SMatthias Ringwald 
3190d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3191d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3192f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
319304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
319404678764SMatthias Ringwald 
3195f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3196f3582630SMatthias Ringwald     if (connection == NULL) return;
3197f3582630SMatthias Ringwald 
31988314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
31993deb3ec6SMatthias Ringwald     // calc CSRK next
3200d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
320104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3202f3582630SMatthias Ringwald     btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_local_csrk, sm_handle_encryption_result_enc_csrk, (void *)(uintptr_t) connection->sm_handle);
3203d1a1f6a4SMatthias Ringwald }
3204d1a1f6a4SMatthias Ringwald 
3205d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3206f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
320704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
320804678764SMatthias Ringwald 
3209f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3210f3582630SMatthias Ringwald     if (connection == NULL) return;
3211f3582630SMatthias Ringwald 
3212d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
32138314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
32143deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
32153deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
32163deb3ec6SMatthias Ringwald     } else {
32173deb3ec6SMatthias Ringwald         // no keys to send, just continue
321842134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
3219c5a72e35SMatthias Ringwald             if (sm_key_distribution_all_received(connection)){
3220c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3221c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3222c5a72e35SMatthias Ringwald             } else {
32233deb3ec6SMatthias Ringwald                 // slave -> receive master keys
32243deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3225c5a72e35SMatthias Ringwald             }
32263deb3ec6SMatthias Ringwald         } else {
3227af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
32283deb3ec6SMatthias Ringwald         }
32292bacf595SMatthias Ringwald     }
323070b44dd4SMatthias Ringwald     sm_trigger_run();
3231d1a1f6a4SMatthias Ringwald }
3232d1a1f6a4SMatthias Ringwald 
323342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3234d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3235f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323704678764SMatthias Ringwald 
3238f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3239f3582630SMatthias Ringwald     if (connection == NULL) return;
3240f3582630SMatthias Ringwald 
32413deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32428314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3243d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
324470b44dd4SMatthias Ringwald     sm_trigger_run();
3245d1a1f6a4SMatthias Ringwald }
3246d1a1f6a4SMatthias Ringwald #endif
3247d1a1f6a4SMatthias Ringwald 
3248d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3249d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3250d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325104678764SMatthias Ringwald 
3252d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3253d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3254d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3255d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3256d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3257a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
325870b44dd4SMatthias Ringwald         sm_trigger_run();
32593deb3ec6SMatthias Ringwald         return;
32603deb3ec6SMatthias Ringwald     }
3261d1a1f6a4SMatthias Ringwald     // no match, try next
3262d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
326370b44dd4SMatthias Ringwald     sm_trigger_run();
32643deb3ec6SMatthias Ringwald }
32653deb3ec6SMatthias Ringwald 
3266d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3267d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3268d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326904678764SMatthias Ringwald 
3270d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3271d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
327270b44dd4SMatthias Ringwald     sm_trigger_run();
32737df18c15SMatthias Ringwald }
3274d1a1f6a4SMatthias Ringwald 
3275d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3276d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3277d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327804678764SMatthias Ringwald 
3279d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3280d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
328170b44dd4SMatthias Ringwald     sm_trigger_run();
32827df18c15SMatthias Ringwald }
3283d1a1f6a4SMatthias Ringwald 
3284d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3285d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3286d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
328704678764SMatthias Ringwald 
32886535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3289d1a1f6a4SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
329070b44dd4SMatthias Ringwald     sm_trigger_run();
329151fa0b28SMatthias Ringwald }
32927df18c15SMatthias Ringwald 
3293d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3294d1a1f6a4SMatthias Ringwald     UNUSED(arg);
32953deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
32963deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
32973deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
32983deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
32993deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
33004ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33014ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
33023deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
33033deb3ec6SMatthias Ringwald             break;
33043deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
33053deb3ec6SMatthias Ringwald         default:
33063deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
33074ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
33083deb3ec6SMatthias Ringwald             rau_state = RAU_SET_ADDRESS;
33093deb3ec6SMatthias Ringwald             break;
33103deb3ec6SMatthias Ringwald     }
331170b44dd4SMatthias Ringwald     sm_trigger_run();
33123deb3ec6SMatthias Ringwald }
33133deb3ec6SMatthias Ringwald 
3314c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
33156ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3316f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3317f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3318f3582630SMatthias Ringwald     if (connection == NULL) return;
3319c59d0c92SMatthias Ringwald 
332065a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
332170b44dd4SMatthias Ringwald     sm_trigger_run();
332265a9a04eSMatthias Ringwald }
3323d1a1f6a4SMatthias Ringwald 
33246ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
33256ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
33266ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
33276ca80073SMatthias Ringwald     if (connection == NULL) return;
33286ca80073SMatthias Ringwald 
3329b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
333070b44dd4SMatthias Ringwald     sm_trigger_run();
3331d1a1f6a4SMatthias Ringwald }
3332f1c1783eSMatthias Ringwald #endif
3333f1c1783eSMatthias Ringwald 
3334d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3335f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3336f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3337f3582630SMatthias Ringwald     if (connection == NULL) return;
3338f3582630SMatthias Ringwald 
3339d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
334070b44dd4SMatthias Ringwald     sm_trigger_run();
3341d1a1f6a4SMatthias Ringwald }
3342d1a1f6a4SMatthias Ringwald 
3343d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3344f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3345f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3346f3582630SMatthias Ringwald     if (connection == NULL) return;
3347f3582630SMatthias Ringwald 
3348caf15bf3SMatthias Ringwald     sm_reset_tk();
3349caf15bf3SMatthias Ringwald     uint32_t tk;
33504b8c611fSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffff){
33513deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3352d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
33533deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
33544ea43905SMatthias Ringwald         if (tk >= 999999u){
33554ea43905SMatthias Ringwald             tk = tk - 999999u;
33563deb3ec6SMatthias Ringwald         }
3357caf15bf3SMatthias Ringwald     } else {
3358caf15bf3SMatthias Ringwald         // override with pre-defined passkey
33594b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3360caf15bf3SMatthias Ringwald     }
3361f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
336242134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33633deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
33643deb3ec6SMatthias Ringwald     } else {
3365b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3366b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3367b41539d5SMatthias Ringwald         } else {
33683deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
33693deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
33703deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
33713deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3372f3582630SMatthias Ringwald                 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) connection->sm_handle);
33733deb3ec6SMatthias Ringwald             }
33743deb3ec6SMatthias Ringwald         }
3375b41539d5SMatthias Ringwald     }
337670b44dd4SMatthias Ringwald     sm_trigger_run();
33773deb3ec6SMatthias Ringwald }
3378d1a1f6a4SMatthias Ringwald 
3379d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3380f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3381f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3382f3582630SMatthias Ringwald     if (connection == NULL) return;
3383f3582630SMatthias Ringwald 
3384d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3385d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3386d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3387d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
338870b44dd4SMatthias Ringwald     sm_trigger_run();
3389d1a1f6a4SMatthias Ringwald }
3390d1a1f6a4SMatthias Ringwald 
3391d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3392f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3393f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3394f3582630SMatthias Ringwald     if (connection == NULL) return;
3395f3582630SMatthias Ringwald 
3396d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
33973deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
33984ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
33993deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
34004ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
34018b3ffec5SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle);
34023deb3ec6SMatthias Ringwald }
3403899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3404899e6e02SMatthias Ringwald     // warn about default ER/IR
34051979f09cSMatthias Ringwald     bool warning = false;
3406899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
34071979f09cSMatthias Ringwald         warning = true;
3408899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3409899e6e02SMatthias Ringwald     }
3410899e6e02SMatthias Ringwald     if (sm_er_is_default()){
34111979f09cSMatthias Ringwald         warning = true;
3412899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3413899e6e02SMatthias Ringwald     }
341421045273SMatthias Ringwald     if (warning) {
3415899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3416899e6e02SMatthias Ringwald     }
341721045273SMatthias Ringwald }
3418899e6e02SMatthias Ringwald 
3419899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
34201979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34219305033eSMatthias Ringwald     if (arg != NULL){
3422899e6e02SMatthias Ringwald         // key generated, store in tlv
34234ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3424899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3425e0d13a19SMilanka Ringwald         UNUSED(status);
3426899e6e02SMatthias Ringwald     }
3427899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
34288d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3429841468bbSMatthias Ringwald 
3430841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3431841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3432841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3433841468bbSMatthias Ringwald     }
3434841468bbSMatthias Ringwald 
343570b44dd4SMatthias Ringwald     sm_trigger_run();
3436899e6e02SMatthias Ringwald }
3437899e6e02SMatthias Ringwald 
3438899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
34391979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
34409305033eSMatthias Ringwald     if (arg != 0){
3441899e6e02SMatthias Ringwald         // key generated, store in tlv
34424ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3443899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3444e0d13a19SMilanka Ringwald         UNUSED(status);
3445899e6e02SMatthias Ringwald     }
3446899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3447899e6e02SMatthias Ringwald 
3448899e6e02SMatthias Ringwald     // try load ir
34494ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3450899e6e02SMatthias Ringwald     if (key_size == 16){
3451899e6e02SMatthias Ringwald         // ok, let's continue
3452899e6e02SMatthias Ringwald         log_info("IR from TLV");
3453899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3454899e6e02SMatthias Ringwald     } else {
3455899e6e02SMatthias Ringwald         // invalid, generate new random one
34561979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3457899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3458899e6e02SMatthias Ringwald     }
3459899e6e02SMatthias Ringwald }
34603deb3ec6SMatthias Ringwald 
3461d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
34623deb3ec6SMatthias Ringwald 
3463cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3464cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
34659ec2630cSMatthias Ringwald 
34663deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3467711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3468fbe050beSMatthias Ringwald     uint8_t           status;
34693deb3ec6SMatthias Ringwald     switch (packet_type) {
34703deb3ec6SMatthias Ringwald 
34713deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
34720e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
34733deb3ec6SMatthias Ringwald 
34743deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
34753deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3476be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
34773deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3478899e6e02SMatthias Ringwald 
3479899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3480899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
34819305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
34824ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3483899e6e02SMatthias Ringwald                             if (key_size == 16){
3484899e6e02SMatthias Ringwald                                 // ok, let's continue
3485899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3486899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3487899e6e02SMatthias Ringwald                             } else {
3488899e6e02SMatthias Ringwald                                 // invalid, generate random one
34891979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3490899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3491899e6e02SMatthias Ringwald                             }
3492899e6e02SMatthias Ringwald                         } else {
3493899e6e02SMatthias Ringwald                             sm_validate_er_ir();
34948d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3495841468bbSMatthias Ringwald 
3496841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3497841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3498841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3499841468bbSMatthias Ringwald                             }
3500899e6e02SMatthias Ringwald                         }
35011bf086daSMatthias Ringwald 
35021bf086daSMatthias Ringwald                         // restart random address updates after power cycle
35031bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
35043deb3ec6SMatthias Ringwald 					}
35053deb3ec6SMatthias Ringwald 					break;
35063deb3ec6SMatthias Ringwald 
35073deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
35083deb3ec6SMatthias Ringwald                     switch (packet[2]) {
35093deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
35103deb3ec6SMatthias Ringwald 
35113deb3ec6SMatthias Ringwald                             log_info("sm: connected");
35123deb3ec6SMatthias Ringwald 
35133deb3ec6SMatthias Ringwald                             if (packet[3]) return; // connection failed
35143deb3ec6SMatthias Ringwald 
3515711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3516711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35173deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35183deb3ec6SMatthias Ringwald 
3519711e6c80SMatthias Ringwald                             sm_conn->sm_handle = con_handle;
35203deb3ec6SMatthias Ringwald                             sm_conn->sm_role = packet[6];
35213deb3ec6SMatthias Ringwald                             sm_conn->sm_peer_addr_type = packet[7];
352213377825SMatthias Ringwald                             reverse_bd_addr(&packet[8], sm_conn->sm_peer_address);
35233deb3ec6SMatthias Ringwald 
35243deb3ec6SMatthias Ringwald                             log_info("New sm_conn, role %s", sm_conn->sm_role ? "slave" : "master");
35253deb3ec6SMatthias Ringwald 
35263deb3ec6SMatthias Ringwald                             // reset security properties
35273deb3ec6SMatthias Ringwald                             sm_conn->sm_connection_encrypted = 0;
35283deb3ec6SMatthias Ringwald                             sm_conn->sm_connection_authenticated = 0;
35293deb3ec6SMatthias Ringwald                             sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
35303deb3ec6SMatthias Ringwald                             sm_conn->sm_le_db_index = -1;
35317b001f4eSMatthias Ringwald                             sm_conn->sm_reencryption_active = false;
35323deb3ec6SMatthias Ringwald 
35333deb3ec6SMatthias Ringwald                             // prepare CSRK lookup (does not involve setup)
35343deb3ec6SMatthias Ringwald                             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
35353deb3ec6SMatthias Ringwald 
35363deb3ec6SMatthias Ringwald                             // just connected -> everything else happens in sm_run()
353742134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
35387af5dcd5SMatthias Ringwald                                 // peripheral
35393deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
35403deb3ec6SMatthias Ringwald                                 break;
35413deb3ec6SMatthias Ringwald                             } else {
35423deb3ec6SMatthias Ringwald                                 // master
35433deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
35443deb3ec6SMatthias Ringwald                             }
35453deb3ec6SMatthias Ringwald                             break;
35463deb3ec6SMatthias Ringwald 
35473deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3548711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3549711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
35503deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
35513deb3ec6SMatthias Ringwald 
35523deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
35533deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
35543deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
35553deb3ec6SMatthias Ringwald                                 break;
35563deb3ec6SMatthias Ringwald                             }
3557c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3558778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3559778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3560e53be891SMatthias Ringwald                                 break;
3561e53be891SMatthias Ringwald                             }
35623deb3ec6SMatthias Ringwald 
35633deb3ec6SMatthias Ringwald                             // store rand and ediv
35649c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3565f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3566549ad5d2SMatthias Ringwald 
3567549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3568549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
35694ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
35706c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
357106cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3572549ad5d2SMatthias Ringwald                                     break;
3573549ad5d2SMatthias Ringwald                                 }
35746c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
35756c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
35766c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
35776c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
35786c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
35796c39055aSMatthias Ringwald                                         break;
35806c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
35816c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
35826c39055aSMatthias Ringwald                                         break;
35836c39055aSMatthias Ringwald                                     default:
35846c39055aSMatthias Ringwald                                         // wait for irk look doen
35856c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
35866c39055aSMatthias Ringwald                                         break;
35876c39055aSMatthias Ringwald                                 }
35886c39055aSMatthias Ringwald                                 break;
35896c39055aSMatthias Ringwald                             }
3590549ad5d2SMatthias Ringwald 
3591549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
359206cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3593549ad5d2SMatthias Ringwald #else
3594549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3595549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3596549ad5d2SMatthias Ringwald #endif
35973deb3ec6SMatthias Ringwald                             break;
3598804d3e67SMatthias Ringwald 
35993deb3ec6SMatthias Ringwald                         default:
36003deb3ec6SMatthias Ringwald                             break;
36013deb3ec6SMatthias Ringwald                     }
36023deb3ec6SMatthias Ringwald                     break;
36033deb3ec6SMatthias Ringwald 
36043deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
36053b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3606711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36073deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36083deb3ec6SMatthias Ringwald 
36093b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
36103deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
36113deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
36123deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
361303a9359aSMatthias Ringwald 
3614fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3615fbe050beSMatthias Ringwald 
36165567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
361703a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3618fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3619fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
36208d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
36218d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36228d4eef95SMatthias Ringwald                                 } else {
362303a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36248d4eef95SMatthias Ringwald                                 }
3625fbe050beSMatthias Ringwald                             } else {
3626e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3627cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
36283b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3629cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
36303b7fd749SMatthias Ringwald                             }
3631fbe050beSMatthias Ringwald 
3632fbe050beSMatthias Ringwald                             // emit re-encryption complete
363373102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3634fbe050beSMatthias Ringwald 
3635c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3636c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3637c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
36380ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
363903a9359aSMatthias Ringwald                             }
364003a9359aSMatthias Ringwald 
36413deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
36423deb3ec6SMatthias Ringwald                             break;
3643fbe050beSMatthias Ringwald 
36443deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3645fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3646dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
364742134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
36483deb3ec6SMatthias Ringwald                                 // slave
3649bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3650bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3651bbf8db22SMatthias Ringwald                                 } else {
3652f3582630SMatthias 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);
3653bbf8db22SMatthias Ringwald                                 }
36543deb3ec6SMatthias Ringwald                             } else {
36553deb3ec6SMatthias Ringwald                                 // master
36563deb3ec6SMatthias Ringwald                                 if (sm_key_distribution_all_received(sm_conn)){
36573deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
36583deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3659f3582630SMatthias 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);
36603deb3ec6SMatthias Ringwald                                 } else {
36613deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
36623deb3ec6SMatthias Ringwald                                 }
36633deb3ec6SMatthias Ringwald                             }
36643deb3ec6SMatthias Ringwald                             break;
36653deb3ec6SMatthias Ringwald                         default:
36663deb3ec6SMatthias Ringwald                             break;
36673deb3ec6SMatthias Ringwald                     }
36683deb3ec6SMatthias Ringwald                     break;
36693deb3ec6SMatthias Ringwald 
36703deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3671711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3672711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
36733deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
36743deb3ec6SMatthias Ringwald 
36753deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
36763deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
36773deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
36783deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
36795567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
36805567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
36815567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
36825567aa60SMatthias Ringwald                             } else {
36833deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
36845567aa60SMatthias Ringwald                             }
36853deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
36863deb3ec6SMatthias Ringwald                             break;
36873deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
368842134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
36893deb3ec6SMatthias Ringwald                                 // slave
3690f3582630SMatthias 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);
36913deb3ec6SMatthias Ringwald                             } else {
36923deb3ec6SMatthias Ringwald                                 // master
36933deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
36943deb3ec6SMatthias Ringwald                             }
36953deb3ec6SMatthias Ringwald                             break;
36963deb3ec6SMatthias Ringwald                         default:
36973deb3ec6SMatthias Ringwald                             break;
36983deb3ec6SMatthias Ringwald                     }
36993deb3ec6SMatthias Ringwald                     break;
37003deb3ec6SMatthias Ringwald 
37013deb3ec6SMatthias Ringwald 
37023deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3703711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3704711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3705711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37063deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37073deb3ec6SMatthias Ringwald 
370803f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
37097f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
37107f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
37117f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
37127f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
37137f3f442dSMatthias Ringwald                             break;
37147f3f442dSMatthias Ringwald                         default:
371568a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
37160ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
37177f3f442dSMatthias Ringwald                             break;
371803f736b1SMatthias Ringwald                     }
3719accbde80SMatthias Ringwald 
37203deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
37213deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
37223deb3ec6SMatthias Ringwald                     break;
37233deb3ec6SMatthias Ringwald 
37243deb3ec6SMatthias Ringwald 				case HCI_EVENT_COMMAND_COMPLETE:
372533373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
37269091c5f5SMatthias Ringwald                         // set local addr for le device db
372733373e40SMatthias Ringwald                         bd_addr_t addr;
372833373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
37290c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
373033373e40SMatthias Ringwald                     }
373165b44ffdSMatthias Ringwald                     break;
373265b44ffdSMatthias Ringwald                 default:
373365b44ffdSMatthias Ringwald                     break;
37343deb3ec6SMatthias Ringwald 			}
373565b44ffdSMatthias Ringwald             break;
373665b44ffdSMatthias Ringwald         default:
373765b44ffdSMatthias Ringwald             break;
37383deb3ec6SMatthias Ringwald 	}
37393deb3ec6SMatthias Ringwald 
37403deb3ec6SMatthias Ringwald     sm_run();
37413deb3ec6SMatthias Ringwald }
37423deb3ec6SMatthias Ringwald 
37433deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
37443deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
37453deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
37463deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
37473deb3ec6SMatthias Ringwald }
37483deb3ec6SMatthias Ringwald 
3749945888f5SMatthias Ringwald 
375031c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3751945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3752945888f5SMatthias Ringwald     switch (method){
3753945888f5SMatthias Ringwald         case JUST_WORKS:
375447fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3755945888f5SMatthias Ringwald             return 1;
3756945888f5SMatthias Ringwald         default:
3757945888f5SMatthias Ringwald             return 0;
3758945888f5SMatthias Ringwald     }
3759945888f5SMatthias Ringwald }
376007036a04SMatthias Ringwald // responder
3761945888f5SMatthias Ringwald 
3762688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3763688a08f9SMatthias Ringwald     switch (method){
3764688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3765688a08f9SMatthias Ringwald             return 1;
3766688a08f9SMatthias Ringwald         default:
3767688a08f9SMatthias Ringwald             return 0;
3768688a08f9SMatthias Ringwald     }
3769688a08f9SMatthias Ringwald }
377040c5d850SMatthias Ringwald 
377140c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
377240c5d850SMatthias Ringwald     switch (method){
377340c5d850SMatthias Ringwald         case PK_RESP_INPUT:
377440c5d850SMatthias Ringwald         case PK_INIT_INPUT:
377547fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
377640c5d850SMatthias Ringwald             return 1;
377740c5d850SMatthias Ringwald         default:
377840c5d850SMatthias Ringwald             return 0;
377940c5d850SMatthias Ringwald     }
378040c5d850SMatthias Ringwald }
378140c5d850SMatthias Ringwald 
378231c09488SMatthias Ringwald #endif
3783688a08f9SMatthias Ringwald 
37843deb3ec6SMatthias Ringwald /**
37853deb3ec6SMatthias Ringwald  * @return ok
37863deb3ec6SMatthias Ringwald  */
37873deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
37883deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
37893deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
37903deb3ec6SMatthias Ringwald         case JUST_WORKS:
37914ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
37923deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
37933deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
379447fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
37954ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
37963deb3ec6SMatthias Ringwald         case OOB:
37974ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
379847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
37994ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
38003deb3ec6SMatthias Ringwald         default:
38013deb3ec6SMatthias Ringwald             return 0;
38023deb3ec6SMatthias Ringwald     }
38033deb3ec6SMatthias Ringwald }
38043deb3ec6SMatthias Ringwald 
38058334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
38068334d3d8SMatthias Ringwald 
38074c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
38084c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
38094c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
38104c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
38114c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
38124c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
38134c1d1092SMatthias Ringwald             17, // 0x04 pairing random
38144c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
38154c1d1092SMatthias Ringwald             17, // 0x06 encryption information
38167a2e6387SMatthias Ringwald             11, // 0x07 master identification
38174c1d1092SMatthias Ringwald             17, // 0x08 identification information
38184c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
38194c1d1092SMatthias Ringwald             17, // 0x0a signing information
38204c1d1092SMatthias Ringwald             2,  // 0x0b security request
38214c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
38224c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
38234c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
38244c1d1092SMatthias Ringwald     };
38253deb3ec6SMatthias Ringwald 
3826c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3827b170b20fSMatthias Ringwald         sm_run();
3828b170b20fSMatthias Ringwald     }
3829b170b20fSMatthias Ringwald 
38303deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
38314ea43905SMatthias Ringwald     if (size == 0u) return;
38324c1d1092SMatthias Ringwald 
38334c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
38344c1d1092SMatthias Ringwald 
38354c1d1092SMatthias Ringwald     // validate pdu size
38364c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
38377a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
38383deb3ec6SMatthias Ringwald 
3839711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
38403deb3ec6SMatthias Ringwald     if (!sm_conn) return;
38413deb3ec6SMatthias Ringwald 
38424c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
384368a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
38440ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3845accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
38463deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
38473deb3ec6SMatthias Ringwald         return;
38483deb3ec6SMatthias Ringwald     }
38493deb3ec6SMatthias Ringwald 
38504c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
38513deb3ec6SMatthias Ringwald 
38523deb3ec6SMatthias Ringwald     int err;
385342134bc6SMatthias Ringwald     UNUSED(err);
38543deb3ec6SMatthias Ringwald 
38554c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
38563d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
38573d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
38583d7fe1e9SMatthias Ringwald         buffer[1] = 3;
38593d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
38603d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
38613d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
38623d7fe1e9SMatthias Ringwald         return;
38633d7fe1e9SMatthias Ringwald     }
38643d7fe1e9SMatthias Ringwald 
3865a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
3866212d735eSMatthias Ringwald     int have_ltk;
3867212d735eSMatthias Ringwald     uint8_t ltk[16];
3868a6ca6916SDavid Lechner #endif
3869212d735eSMatthias Ringwald 
38703deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
38713deb3ec6SMatthias Ringwald 
3872c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
38733deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
38743deb3ec6SMatthias Ringwald             return;
38753deb3ec6SMatthias Ringwald 
387642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
387742134bc6SMatthias Ringwald 
38783deb3ec6SMatthias Ringwald         // Initiator
38793deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
38804c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
38813deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
38823deb3ec6SMatthias Ringwald                 break;
38833deb3ec6SMatthias Ringwald             }
388434c39fbdSMatthias Ringwald 
3885*2c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3886*2c041b42SMatthias Ringwald             if (sm_sc_only_mode){
3887*2c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
3888*2c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
3889*2c041b42SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
3890*2c041b42SMatthias Ringwald                     break;
3891*2c041b42SMatthias Ringwald                 }
3892*2c041b42SMatthias Ringwald             }
3893*2c041b42SMatthias Ringwald #endif
3894*2c041b42SMatthias Ringwald 
389534c39fbdSMatthias Ringwald             // IRK complete?
389634c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
389734c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
3898dc8ca372SMatthias Ringwald                     // start pairing
38993deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
39003deb3ec6SMatthias Ringwald                     break;
3901e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
3902e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3903e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
39048549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
39058549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
39068549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
39075567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
3908e061bbd4SMatthias Ringwald                     } else {
3909dc8ca372SMatthias Ringwald                         // start pairing
3910e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3911e061bbd4SMatthias Ringwald                     }
3912e061bbd4SMatthias Ringwald                     break;
391334c39fbdSMatthias Ringwald                 default:
39143deb3ec6SMatthias Ringwald                     // otherwise, store security request
39153deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
39163deb3ec6SMatthias Ringwald                     break;
3917dc8ca372SMatthias Ringwald             }
3918dc8ca372SMatthias Ringwald             break;
39193deb3ec6SMatthias Ringwald 
39203deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3921aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
3922aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3923aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3924aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3925aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
3926aacfafc3SMatthias Ringwald                 break;
3927aacfafc3SMatthias Ringwald             }
3928aacfafc3SMatthias Ringwald 
3929aacfafc3SMatthias Ringwald             // all other pdus are incorrect
39304c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
39313deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39323deb3ec6SMatthias Ringwald                 break;
39333deb3ec6SMatthias Ringwald             }
39340af429c6SMatthias Ringwald 
39353deb3ec6SMatthias Ringwald             // store pairing request
39366535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
39376535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
39383deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
39390af429c6SMatthias Ringwald 
39400af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
39410af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
39420af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
39430af429c6SMatthias Ringwald                 err = test_pairing_failure;
39440af429c6SMatthias Ringwald             }
39450af429c6SMatthias Ringwald #endif
39460af429c6SMatthias Ringwald 
39479305033eSMatthias Ringwald             if (err != 0){
39483deb3ec6SMatthias Ringwald                 setup->sm_pairing_failed_reason = err;
39493deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
39503deb3ec6SMatthias Ringwald                 break;
39513deb3ec6SMatthias Ringwald             }
3952b41539d5SMatthias Ringwald 
3953b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
3954b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3955f3582630SMatthias 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);
3956b41539d5SMatthias Ringwald                 break;
3957b41539d5SMatthias Ringwald             }
3958b41539d5SMatthias Ringwald 
3959136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3960136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
39618cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
39628cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
3963136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3964136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
3965136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3966c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3967136d331aSMatthias Ringwald                     }
39688cba5ca3SMatthias Ringwald                 } else {
3969c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
39708cba5ca3SMatthias Ringwald                 }
3971136d331aSMatthias Ringwald                 break;
3972136d331aSMatthias Ringwald             }
3973136d331aSMatthias Ringwald #endif
39743deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
39753deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
39763deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
39773deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3978f3582630SMatthias 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);
39793deb3ec6SMatthias Ringwald             }
39803deb3ec6SMatthias Ringwald             break;
39813deb3ec6SMatthias Ringwald 
39823deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
39834c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
39843deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
39853deb3ec6SMatthias Ringwald                 break;
39863deb3ec6SMatthias Ringwald             }
39873deb3ec6SMatthias Ringwald 
39883deb3ec6SMatthias Ringwald             // store s_confirm
39899c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
3990192365feSMatthias Ringwald 
3991aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
3992aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
3993aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
3994aa9b34e5SMatthias Ringwald                 break;
3995aa9b34e5SMatthias Ringwald             }
3996aa9b34e5SMatthias Ringwald 
3997192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
3998192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3999192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4000192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4001192365feSMatthias Ringwald             }
4002192365feSMatthias Ringwald #endif
40033deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
40043deb3ec6SMatthias Ringwald             break;
40053deb3ec6SMatthias Ringwald 
40063deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
40074c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
40083deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40093deb3ec6SMatthias Ringwald                 break;;
40103deb3ec6SMatthias Ringwald             }
40113deb3ec6SMatthias Ringwald 
40123deb3ec6SMatthias Ringwald             // received random value
40139c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
40143deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
40153deb3ec6SMatthias Ringwald             break;
401642134bc6SMatthias Ringwald #endif
40173deb3ec6SMatthias Ringwald 
401842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
40193deb3ec6SMatthias Ringwald         // Responder
40203deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
40213deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
40223deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
40234c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
40243deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40253deb3ec6SMatthias Ringwald                 break;;
40263deb3ec6SMatthias Ringwald             }
40273deb3ec6SMatthias Ringwald 
40283deb3ec6SMatthias Ringwald             // store pairing request
4029212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4030212d735eSMatthias Ringwald 
4031212d735eSMatthias Ringwald             // check if IRK completed
4032212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4033212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4034212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
40353deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
40363deb3ec6SMatthias Ringwald                     break;
4037212d735eSMatthias Ringwald                 default:
4038212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4039212d735eSMatthias Ringwald                     break;
4040212d735eSMatthias Ringwald             }
4041212d735eSMatthias Ringwald             break;
404242134bc6SMatthias Ringwald #endif
40433deb3ec6SMatthias Ringwald 
404427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4045c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
40464c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
404727c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
404827c32905SMatthias Ringwald                 break;
404927c32905SMatthias Ringwald             }
4050bccf5e67SMatthias Ringwald 
4051e53be891SMatthias Ringwald             // store public key for DH Key calculation
4052fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4053fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4054bccf5e67SMatthias Ringwald 
4055d1a1f6a4SMatthias Ringwald             // validate public key
4056d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
40579305033eSMatthias Ringwald             if (err != 0){
4058bccf5e67SMatthias Ringwald                 log_error("sm: peer public key invalid %x", err);
4059349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4060bccf5e67SMatthias Ringwald                 break;
4061bccf5e67SMatthias Ringwald             }
4062891bb64aSMatthias Ringwald 
4063d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4064f3582630SMatthias 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);
40653cf37b8cSMatthias Ringwald 
406665a9a04eSMatthias Ringwald 
406765a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
406842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4069136d331aSMatthias Ringwald                 // responder
4070c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4071136d331aSMatthias Ringwald             } else {
4072136d331aSMatthias Ringwald                 // initiator
4073a1e31e9cSMatthias Ringwald                 // stk generation method
4074a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4075a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4076a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
407747fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4078c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4079a1e31e9cSMatthias Ringwald                         break;
4080a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
408107036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
408207036a04SMatthias Ringwald                         break;
408307036a04SMatthias Ringwald                     case PK_INIT_INPUT:
408447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
408507036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
408607036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
408707036a04SMatthias Ringwald                             break;
408807036a04SMatthias Ringwald                         }
4089b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4090a1e31e9cSMatthias Ringwald                         break;
4091a1e31e9cSMatthias Ringwald                     case OOB:
4092d1a1f6a4SMatthias Ringwald                         // generate Nx
40934acf7b7bSMatthias Ringwald                         log_info("Generate Na");
40946ca80073SMatthias 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);
4095a1e31e9cSMatthias Ringwald                         break;
40967bbeb3adSMilanka Ringwald                     default:
40977bbeb3adSMilanka Ringwald                         btstack_assert(false);
40987bbeb3adSMilanka Ringwald                         break;
4099a1e31e9cSMatthias Ringwald                 }
4100136d331aSMatthias Ringwald             }
410127c32905SMatthias Ringwald             break;
4102e53be891SMatthias Ringwald 
4103c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
41044c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
410545a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
410645a61d50SMatthias Ringwald                 break;
410745a61d50SMatthias Ringwald             }
410845a61d50SMatthias Ringwald             // received confirm value
410945a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
411045a61d50SMatthias Ringwald 
4111192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4112192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4113192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4114192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4115192365feSMatthias Ringwald             }
4116192365feSMatthias Ringwald #endif
411742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
411845a61d50SMatthias Ringwald                 // responder
411907036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
412007036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
412107036a04SMatthias Ringwald                         // still waiting for passkey
412207036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
412307036a04SMatthias Ringwald                         break;
412407036a04SMatthias Ringwald                     }
412507036a04SMatthias Ringwald                 }
4126b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
412745a61d50SMatthias Ringwald             } else {
412845a61d50SMatthias Ringwald                 // initiator
4129945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
41306ca80073SMatthias 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);
4131f1c1783eSMatthias Ringwald                 } else {
4132c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
413345a61d50SMatthias Ringwald                 }
4134f1c1783eSMatthias Ringwald             }
413545a61d50SMatthias Ringwald             break;
413645a61d50SMatthias Ringwald 
4137c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
41384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4139e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4140136d331aSMatthias Ringwald                 break;
4141e53be891SMatthias Ringwald             }
4142e53be891SMatthias Ringwald 
4143e53be891SMatthias Ringwald             // received random value
4144e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4145e53be891SMatthias Ringwald 
41465a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4147ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4148d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4149d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4150d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
415165a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4152d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4153688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4154ae451ec5SMatthias Ringwald                  break;
41555a293e6eSMatthias Ringwald             }
41566f52a196SMatthias Ringwald 
41574acf7b7bSMatthias Ringwald             // OOB
41584acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
41594acf7b7bSMatthias Ringwald 
41604acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
41614acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
41624acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
41634ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
41644acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
41654acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
41664acf7b7bSMatthias Ringwald                     } else {
41676535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
41684acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
41694acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
41704acf7b7bSMatthias Ringwald                     }
41714acf7b7bSMatthias Ringwald                 }  else {
41724ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
41734acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
41744acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
41754acf7b7bSMatthias Ringwald                     } else {
41766535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
41774acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
41784acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
41794acf7b7bSMatthias Ringwald                     }
41804acf7b7bSMatthias Ringwald                 }
41814acf7b7bSMatthias Ringwald 
4182a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
41834acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4184a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4185a680ba6bSMatthias Ringwald                      break;
4186a680ba6bSMatthias Ringwald                 }
41874acf7b7bSMatthias Ringwald             }
4188a680ba6bSMatthias Ringwald 
4189a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4190688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4191e53be891SMatthias Ringwald             break;
4192e53be891SMatthias Ringwald 
4193901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4194901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
41953cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4196901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4197901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4198901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4199901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4200901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4201901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4202901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4203c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4204901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4205d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
42064c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4207e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4208e53be891SMatthias Ringwald                 break;
4209e53be891SMatthias Ringwald             }
4210e53be891SMatthias Ringwald             // store DHKey Check
4211901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4212e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4213446a8c36SMatthias Ringwald 
4214901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4215901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4216019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4217bd57ffebSMatthias Ringwald             }
4218bd57ffebSMatthias Ringwald             break;
421927c32905SMatthias Ringwald #endif
422027c32905SMatthias Ringwald 
422142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42223deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
42234c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42243deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
422527c32905SMatthias Ringwald                 break;
42263deb3ec6SMatthias Ringwald             }
42273deb3ec6SMatthias Ringwald 
42283deb3ec6SMatthias Ringwald             // received confirm value
42299c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
42303deb3ec6SMatthias Ringwald 
4231192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4232192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4233192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4234192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4235192365feSMatthias Ringwald             }
4236192365feSMatthias Ringwald #endif
42373deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
42383deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
42395611a760SMatthias 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);
42403deb3ec6SMatthias Ringwald             }
42413deb3ec6SMatthias Ringwald 
42423deb3ec6SMatthias Ringwald             // handle user cancel pairing?
42433deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
424416a1a3e5SMatthias Ringwald                 setup->sm_pairing_failed_reason = SM_REASON_PASSKEY_ENTRY_FAILED;
42453deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
42463deb3ec6SMatthias Ringwald                 break;
42473deb3ec6SMatthias Ringwald             }
42483deb3ec6SMatthias Ringwald 
42493deb3ec6SMatthias Ringwald             // wait for user action?
42503deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
42513deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42523deb3ec6SMatthias Ringwald                 break;
42533deb3ec6SMatthias Ringwald             }
42543deb3ec6SMatthias Ringwald 
42553deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4256f3582630SMatthias 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);
42573deb3ec6SMatthias Ringwald             break;
42583deb3ec6SMatthias Ringwald 
42593deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
42604c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42613deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42623deb3ec6SMatthias Ringwald                 break;;
42633deb3ec6SMatthias Ringwald             }
42643deb3ec6SMatthias Ringwald 
42653deb3ec6SMatthias Ringwald             // received random value
42669c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42673deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42683deb3ec6SMatthias Ringwald             break;
426942134bc6SMatthias Ringwald #endif
42703deb3ec6SMatthias Ringwald 
42713deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
42724c1d1092SMatthias Ringwald             switch(sm_pdu_code){
42733deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
42743deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
42759c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
42763deb3ec6SMatthias Ringwald                     break;
42773deb3ec6SMatthias Ringwald 
42783deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
42793deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4280f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
42819c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
42823deb3ec6SMatthias Ringwald                     break;
42833deb3ec6SMatthias Ringwald 
42843deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
42853deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
42869c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
42873deb3ec6SMatthias Ringwald                     break;
42883deb3ec6SMatthias Ringwald 
42893deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
42903deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
42913deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4292724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
42933deb3ec6SMatthias Ringwald                     break;
42943deb3ec6SMatthias Ringwald 
42953deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
42963deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
42979c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
42983deb3ec6SMatthias Ringwald                     break;
42993deb3ec6SMatthias Ringwald                 default:
43003deb3ec6SMatthias Ringwald                     // Unexpected PDU
43013deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
43023deb3ec6SMatthias Ringwald                     break;
43033deb3ec6SMatthias Ringwald             }
43043deb3ec6SMatthias Ringwald             // done with key distribution?
43053deb3ec6SMatthias Ringwald             if (sm_key_distribution_all_received(sm_conn)){
43063deb3ec6SMatthias Ringwald 
43073deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
43083deb3ec6SMatthias Ringwald 
430942134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43106f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
43113deb3ec6SMatthias Ringwald                 } else {
4312625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4313625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4314bbf8db22SMatthias Ringwald                     } else {
4315f3582630SMatthias 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);
4316625f00b2SMatthias Ringwald                     }
43173deb3ec6SMatthias Ringwald                 }
43183deb3ec6SMatthias Ringwald             }
43193deb3ec6SMatthias Ringwald             break;
43203deb3ec6SMatthias Ringwald         default:
43213deb3ec6SMatthias Ringwald             // Unexpected PDU
43223deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
43233deb3ec6SMatthias Ringwald             break;
43243deb3ec6SMatthias Ringwald     }
43253deb3ec6SMatthias Ringwald 
432670b44dd4SMatthias Ringwald     // try to send next pdu
432770b44dd4SMatthias Ringwald     sm_trigger_run();
43283deb3ec6SMatthias Ringwald }
43293deb3ec6SMatthias Ringwald 
43303deb3ec6SMatthias Ringwald // Security Manager Client API
4331a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
43323deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
43333deb3ec6SMatthias Ringwald }
43343deb3ec6SMatthias Ringwald 
43354acf7b7bSMatthias 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)){
4336a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4337a680ba6bSMatthias Ringwald }
4338a680ba6bSMatthias Ringwald 
433989a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
434089a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
434189a78d34SMatthias Ringwald }
434289a78d34SMatthias Ringwald 
43433deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
43443deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
43453deb3ec6SMatthias Ringwald }
43463deb3ec6SMatthias Ringwald 
43473deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
43483deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
43493deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
43503deb3ec6SMatthias Ringwald }
43513deb3ec6SMatthias Ringwald 
43523deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
435398d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
435498d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
435598d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
435698d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
435798d95509SMatthias Ringwald     }
435898d95509SMatthias Ringwald #endif
43593deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
43603deb3ec6SMatthias Ringwald }
43613deb3ec6SMatthias Ringwald 
43623deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
43633deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
43643deb3ec6SMatthias Ringwald }
43653deb3ec6SMatthias Ringwald 
436642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43673deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
43683deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
43693deb3ec6SMatthias Ringwald }
437042134bc6SMatthias Ringwald #endif
43713deb3ec6SMatthias Ringwald 
43723deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
43736535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
43743deb3ec6SMatthias Ringwald }
43753deb3ec6SMatthias Ringwald 
43763deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
43776535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
43783deb3ec6SMatthias Ringwald }
43793deb3ec6SMatthias Ringwald 
43803deb3ec6SMatthias Ringwald // Testing support only
43813deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
43826535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4383103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4384841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
43853deb3ec6SMatthias Ringwald }
43863deb3ec6SMatthias Ringwald 
43873deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4388841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
43893deb3ec6SMatthias Ringwald }
43903deb3ec6SMatthias Ringwald 
4391d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4392d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4393d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4394d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
439534b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
439670b44dd4SMatthias Ringwald     sm_trigger_run();
4397d1a1f6a4SMatthias Ringwald }
4398674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
439934b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4400674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4401674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4402674e5b4aSMatthias Ringwald }
4403d1a1f6a4SMatthias Ringwald #endif
4404d1a1f6a4SMatthias Ringwald 
4405192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4406192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4407192365feSMatthias Ringwald     test_pairing_failure = reason;
4408192365feSMatthias Ringwald }
4409192365feSMatthias Ringwald #endif
4410192365feSMatthias Ringwald 
44113deb3ec6SMatthias Ringwald void sm_init(void){
44122d2d4d3cSMatthias Ringwald 
44132d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
44142d2d4d3cSMatthias Ringwald 
4415899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4416899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4417899e6e02SMatthias Ringwald 
44183deb3ec6SMatthias Ringwald     // defaults
44193deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
44203deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4421b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4422b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4423b4343428SMatthias Ringwald 
44243deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
44253deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
44263deb3ec6SMatthias Ringwald 
44274b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffff;
44281979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4429caf15bf3SMatthias Ringwald 
4430d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4431d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
44327a766ebfSMatthias Ringwald #endif
44338d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4434fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
44353deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
44363deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
44373deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
44383deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
44393deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
44403deb3ec6SMatthias Ringwald 
44413deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
44427149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
44433deb3ec6SMatthias Ringwald 
4444841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
44453deb3ec6SMatthias Ringwald 
444684c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
444784c0c5c7SMatthias Ringwald 
4448e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4449e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4450e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4451e03e489aSMatthias Ringwald 
4452d1a1f6a4SMatthias Ringwald     //
4453d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4454d1a1f6a4SMatthias Ringwald 
445551bd74d1SMatthias Ringwald     // init le_device_db
445651bd74d1SMatthias Ringwald     le_device_db_init();
445751bd74d1SMatthias Ringwald 
4458b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4459e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
446027c32905SMatthias Ringwald 
446109e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4462674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4463a3aba2f9SMatthias Ringwald #endif
44642d2d4d3cSMatthias Ringwald 
44652d2d4d3cSMatthias Ringwald     sm_initialized = true;
44663deb3ec6SMatthias Ringwald }
44673deb3ec6SMatthias Ringwald 
44684b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
44694b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4470caf15bf3SMatthias Ringwald }
4471caf15bf3SMatthias Ringwald 
44726c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
44731979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
44746c39055aSMatthias Ringwald }
44756c39055aSMatthias Ringwald 
4476711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4477711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
44783deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
44793deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
44803deb3ec6SMatthias Ringwald }
44813deb3ec6SMatthias Ringwald 
44826bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4483711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4484711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
44853deb3ec6SMatthias Ringwald     if (!sm_conn) return;
44866bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
44876bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
44883deb3ec6SMatthias Ringwald }
44893deb3ec6SMatthias Ringwald 
44903deb3ec6SMatthias Ringwald // request pairing
4491711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4492711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
44933deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
44943deb3ec6SMatthias Ringwald 
44957af5dcd5SMatthias Ringwald     bool have_ltk;
44967af5dcd5SMatthias Ringwald     uint8_t ltk[16];
44973deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
449842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
449924c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
450024c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
450124c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
45027af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45037af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45047af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
45057af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
45067af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
45077af5dcd5SMatthias Ringwald                         if (have_ltk){
45087af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
450924c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45107af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
45117af5dcd5SMatthias Ringwald                             break;
45127af5dcd5SMatthias Ringwald                         }
45137af5dcd5SMatthias Ringwald                         /* fall through */
45147af5dcd5SMatthias Ringwald 
45157af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45167af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45177af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
45187af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
45197af5dcd5SMatthias Ringwald                         break;
45207af5dcd5SMatthias Ringwald                     default:
45217af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
45227af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45237af5dcd5SMatthias Ringwald                         break;
45247af5dcd5SMatthias Ringwald                 }
452524c20dc4SMatthias Ringwald                 break;
452624c20dc4SMatthias Ringwald             default:
452724c20dc4SMatthias Ringwald                 break;
452824c20dc4SMatthias Ringwald         }
45293deb3ec6SMatthias Ringwald     } else {
45303deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4531175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4532175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
45333deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
45343deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
45353dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4536f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4537f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4538f53ec649SMatthias Ringwald                         if (have_ltk){
4539c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
45405567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4541c245ca32SMatthias Ringwald                             break;
4542f53ec649SMatthias Ringwald                         }
4543cf373d3aSMatthias Ringwald                         /* fall through */
4544c245ca32SMatthias Ringwald 
454534c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
45463deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
45473deb3ec6SMatthias Ringwald                         break;
45483deb3ec6SMatthias Ringwald                     default:
4549d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
455009ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
45513deb3ec6SMatthias Ringwald                         break;
45523deb3ec6SMatthias Ringwald                 }
4553175b7faaSMatthias Ringwald                 break;
4554cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4555cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4556cb6d7eb0SMatthias Ringwald                 break;
4557175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
455809ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4559175b7faaSMatthias Ringwald                 break;
4560175b7faaSMatthias Ringwald             default:
4561175b7faaSMatthias Ringwald                 break;
45623deb3ec6SMatthias Ringwald         }
45633deb3ec6SMatthias Ringwald     }
456470b44dd4SMatthias Ringwald     sm_trigger_run();
45653deb3ec6SMatthias Ringwald }
45663deb3ec6SMatthias Ringwald 
45673deb3ec6SMatthias Ringwald // called by client app on authorization request
4568711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4569711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45703deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45713deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4572589f5a99SMatthias 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);
45733deb3ec6SMatthias Ringwald }
45743deb3ec6SMatthias Ringwald 
4575711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4576711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45773deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45783deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4579589f5a99SMatthias 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);
45803deb3ec6SMatthias Ringwald }
45813deb3ec6SMatthias Ringwald 
45823deb3ec6SMatthias Ringwald // GAP Bonding API
45833deb3ec6SMatthias Ringwald 
4584711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4585711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
45863deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
45873deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
45880af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
45890af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
45900af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
45910af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
45920af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
45930af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
45940af429c6SMatthias Ringwald #endif
45950af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4596de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4597de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4598de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
459947fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
46000af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4601de2fd182SMatthias Ringwald                     break;
460247fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4603de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4604de2fd182SMatthias Ringwald                     break;
4605de2fd182SMatthias Ringwald                 case JUST_WORKS:
4606de2fd182SMatthias Ringwald                 case OOB:
4607de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4608de2fd182SMatthias Ringwald                     break;
46097bbeb3adSMilanka Ringwald                 default:
46107bbeb3adSMilanka Ringwald                     btstack_assert(false);
46117bbeb3adSMilanka Ringwald                     break;
4612de2fd182SMatthias Ringwald             }
46130af429c6SMatthias Ringwald             break;
46140af429c6SMatthias Ringwald         default:
46150af429c6SMatthias Ringwald             break;
46163deb3ec6SMatthias Ringwald     }
461770b44dd4SMatthias Ringwald     sm_trigger_run();
46183deb3ec6SMatthias Ringwald }
46193deb3ec6SMatthias Ringwald 
4620711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4621711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46223deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46233deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
46243deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4625136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4626c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4627bbf8db22SMatthias Ringwald         } else {
4628f3582630SMatthias 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);
4629136d331aSMatthias Ringwald         }
46303deb3ec6SMatthias Ringwald     }
46310346c37cSMatthias Ringwald 
46320346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4633c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4634dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4635446a8c36SMatthias Ringwald     }
46360346c37cSMatthias Ringwald #endif
46370346c37cSMatthias Ringwald 
463870b44dd4SMatthias Ringwald     sm_trigger_run();
46393deb3ec6SMatthias Ringwald }
46403deb3ec6SMatthias Ringwald 
4641c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4642c8c46d51SMatthias Ringwald     // for now, it's the same
4643c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4644c8c46d51SMatthias Ringwald }
4645c8c46d51SMatthias Ringwald 
4646711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4647711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46483deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46493deb3ec6SMatthias Ringwald     sm_reset_tk();
4650f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
46513deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
46523deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4653f3582630SMatthias 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);
46543deb3ec6SMatthias Ringwald     }
46551c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
46566535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
46576535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
465807036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
465907036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
466007036a04SMatthias Ringwald     }
46611c516d8fSMatthias Ringwald #endif
466270b44dd4SMatthias Ringwald     sm_trigger_run();
46633deb3ec6SMatthias Ringwald }
46643deb3ec6SMatthias Ringwald 
46653d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
46663d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
46673d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
46683d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4669dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
46704ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4671dd4a08fbSMatthias Ringwald     switch (action){
4672dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4673dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
46744ea43905SMatthias Ringwald             flags |= (1u << action);
4675dd4a08fbSMatthias Ringwald             break;
4676dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4677dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
46784ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4679dd4a08fbSMatthias Ringwald             break;
4680dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
46814ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4682dd4a08fbSMatthias Ringwald                 // erase actions queued
4683dd4a08fbSMatthias Ringwald                 num_actions--;
46844ea43905SMatthias Ringwald                 if (num_actions == 0u){
4685dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
46864ea43905SMatthias Ringwald                     flags &= 0x19u;
4687dd4a08fbSMatthias Ringwald                 }
4688dd4a08fbSMatthias Ringwald                 break;
4689dd4a08fbSMatthias Ringwald             }
4690dd4a08fbSMatthias Ringwald             num_actions++;
46914ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4692dd4a08fbSMatthias Ringwald             break;
4693dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
46944ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4695dd4a08fbSMatthias Ringwald                 // enter actions queued
4696dd4a08fbSMatthias Ringwald                 num_actions--;
46974ea43905SMatthias Ringwald                 if (num_actions == 0u){
4698dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
46994ea43905SMatthias Ringwald                     flags &= 0x19u;
4700dd4a08fbSMatthias Ringwald                 }
4701dd4a08fbSMatthias Ringwald                 break;
4702dd4a08fbSMatthias Ringwald             }
4703dd4a08fbSMatthias Ringwald             num_actions++;
47044ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4705dd4a08fbSMatthias Ringwald             break;
4706dd4a08fbSMatthias Ringwald         default:
4707dd4a08fbSMatthias Ringwald             break;
4708dd4a08fbSMatthias Ringwald     }
4709dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
471070b44dd4SMatthias Ringwald     sm_trigger_run();
47113d7fe1e9SMatthias Ringwald }
47123d7fe1e9SMatthias Ringwald 
4713c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4714d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
4715d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4716d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
471770b44dd4SMatthias Ringwald     sm_trigger_run();
4718d1a1f6a4SMatthias Ringwald }
4719c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
47208334d3d8SMatthias Ringwald 
47218334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
47228334d3d8SMatthias Ringwald 
4723c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4724c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
4725d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4726d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4727c59d0c92SMatthias Ringwald     return 0;
4728c59d0c92SMatthias Ringwald }
4729c59d0c92SMatthias Ringwald #endif
4730c59d0c92SMatthias Ringwald 
47313deb3ec6SMatthias Ringwald /**
4732ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
4733ba394633SMatthias Ringwald  * @param con_handle
4734ba394633SMatthias Ringwald  * @return irk_lookup_state_t
4735ba394633SMatthias Ringwald  */
4736ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4737ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4738ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
4739ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
4740ba394633SMatthias Ringwald }
4741ba394633SMatthias Ringwald 
4742ba394633SMatthias Ringwald /**
47433deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
47443deb3ec6SMatthias Ringwald  * @param handle
47453deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
47463deb3ec6SMatthias Ringwald  */
4747711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
4748711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47493deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
47503deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
47513deb3ec6SMatthias Ringwald }
47523deb3ec6SMatthias Ringwald 
47538f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
475447ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
475547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
475647ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
475747ba4de1SMatthias Ringwald             return 0;
475847ba4de1SMatthias Ringwald         default:
47598f57b085SMatthias Ringwald             return 1;
47608f57b085SMatthias Ringwald     }
476147ba4de1SMatthias Ringwald }
4762d70217a2SMatthias Ringwald 
476333373e40SMatthias Ringwald static uint8_t own_address_type(void){
4764b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
4765b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4766b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
4767b95a5a35SMatthias Ringwald         default:
4768b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
4769b95a5a35SMatthias Ringwald     }
477033373e40SMatthias Ringwald }
47718f57b085SMatthias Ringwald 
47723deb3ec6SMatthias Ringwald // GAP LE API
47733deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
47743deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
47753deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
4776b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
47778f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
47783deb3ec6SMatthias Ringwald     gap_random_address_update_start();
47793deb3ec6SMatthias Ringwald     gap_random_address_trigger();
47803deb3ec6SMatthias Ringwald }
47813deb3ec6SMatthias Ringwald 
47823deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
47833deb3ec6SMatthias Ringwald     return gap_random_adress_type;
47843deb3ec6SMatthias Ringwald }
47853deb3ec6SMatthias Ringwald 
47863deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
47873deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
47888f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
47893deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
47903deb3ec6SMatthias Ringwald     gap_random_address_update_start();
47913deb3ec6SMatthias Ringwald }
47923deb3ec6SMatthias Ringwald 
4793667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
47948f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
47956535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
47967e252622SMatthias Ringwald     rau_state = RAU_SET_ADDRESS;
479770b44dd4SMatthias Ringwald     sm_trigger_run();
47987e252622SMatthias Ringwald }
47997e252622SMatthias Ringwald 
4800d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48013deb3ec6SMatthias Ringwald /*
48023deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
48033deb3ec6SMatthias Ringwald  * @param adv_int_min
48043deb3ec6SMatthias Ringwald  * @param adv_int_max
48053deb3ec6SMatthias Ringwald  * @param adv_type
48063deb3ec6SMatthias Ringwald  * @param direct_address_type
48073deb3ec6SMatthias Ringwald  * @param direct_address
48083deb3ec6SMatthias Ringwald  * @param channel_map
48093deb3ec6SMatthias Ringwald  * @param filter_policy
48103deb3ec6SMatthias Ringwald  *
48113deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
48123deb3ec6SMatthias Ringwald  */
48133deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
48143deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4815b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
48163deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
48173deb3ec6SMatthias Ringwald }
4818d70217a2SMatthias Ringwald #endif
4819dcd6c9b5SMatthias Ringwald 
4820dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4821dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4822dcd6c9b5SMatthias Ringwald      // wrong connection
4823dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
4824dcd6c9b5SMatthias Ringwald     // already encrypted
4825dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
4826dcd6c9b5SMatthias Ringwald     // irk status?
4827dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
4828dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
4829dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
4830dcd6c9b5SMatthias Ringwald             return 0;
4831dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
4832dcd6c9b5SMatthias Ringwald             break;
4833dcd6c9b5SMatthias Ringwald         default:
4834dcd6c9b5SMatthias Ringwald             // IR Lookup pending
4835dcd6c9b5SMatthias Ringwald             return 1;
4836dcd6c9b5SMatthias Ringwald     }
4837f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
4838f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
4839b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
4840b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
4841b15d5ceaSMatthias Ringwald     } else {
4842dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4843dcd6c9b5SMatthias Ringwald     }
4844b15d5ceaSMatthias Ringwald }
48453cdbe9dbSMatthias Ringwald 
48463cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
48473cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
48483cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
48493cdbe9dbSMatthias Ringwald #else
48503cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
48513cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
48523cdbe9dbSMatthias Ringwald #endif
48533cdbe9dbSMatthias Ringwald }
4854052bbdc5SMatthias Ringwald 
4855052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
4856052bbdc5SMatthias Ringwald     return sm_persistent_irk;
4857052bbdc5SMatthias Ringwald }
48584f384501SMatthias Ringwald 
48594f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
48604f384501SMatthias Ringwald     uint16_t i;
48614f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
48624f384501SMatthias Ringwald         bd_addr_t entry_address;
48634f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
48644f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
48654f384501SMatthias Ringwald         // skip unused entries
48664f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
48674f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
48684f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
48694f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
48704f384501SMatthias Ringwald #endif
48714f384501SMatthias Ringwald             le_device_db_remove(i);
48724f384501SMatthias Ringwald             break;
48734f384501SMatthias Ringwald         }
48744f384501SMatthias Ringwald     }
48754f384501SMatthias Ringwald }
4876