xref: /btstack/src/ble/sm.c (revision d552970049ccdca208bf91acaa0fe25593be0fac)
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
232fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
242fca4dadSMilanka Ringwald  * GMBH 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 } random_address_update_t;
1113deb3ec6SMatthias Ringwald 
1123deb3ec6SMatthias Ringwald typedef enum {
1133deb3ec6SMatthias Ringwald     CMAC_IDLE,
1143deb3ec6SMatthias Ringwald     CMAC_CALC_SUBKEYS,
1153deb3ec6SMatthias Ringwald     CMAC_W4_SUBKEYS,
1163deb3ec6SMatthias Ringwald     CMAC_CALC_MI,
1173deb3ec6SMatthias Ringwald     CMAC_W4_MI,
1183deb3ec6SMatthias Ringwald     CMAC_CALC_MLAST,
1193deb3ec6SMatthias Ringwald     CMAC_W4_MLAST
1203deb3ec6SMatthias Ringwald } cmac_state_t;
1213deb3ec6SMatthias Ringwald 
1223deb3ec6SMatthias Ringwald typedef enum {
1233deb3ec6SMatthias Ringwald     JUST_WORKS,
12427c32905SMatthias Ringwald     PK_RESP_INPUT,       // Initiator displays PK, responder inputs PK
12527c32905SMatthias Ringwald     PK_INIT_INPUT,       // Responder displays PK, initiator inputs PK
12647fb4255SMatthias Ringwald     PK_BOTH_INPUT,       // Only input on both, both input PK
12747fb4255SMatthias Ringwald     NUMERIC_COMPARISON,  // Only numerical compparison (yes/no) on on both sides
12847fb4255SMatthias Ringwald     OOB                  // OOB available on one (SC) or both sides (legacy)
1293deb3ec6SMatthias Ringwald } stk_generation_method_t;
1303deb3ec6SMatthias Ringwald 
1313deb3ec6SMatthias Ringwald typedef enum {
1323deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_IDLE,
1333deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PENDING,
1343deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_CONFIRM,
1353deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PASSKEY,
1363deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_DECLINE
1373deb3ec6SMatthias Ringwald } sm_user_response_t;
1383deb3ec6SMatthias Ringwald 
1393deb3ec6SMatthias Ringwald typedef enum {
1403deb3ec6SMatthias Ringwald     SM_AES128_IDLE,
1413deb3ec6SMatthias Ringwald     SM_AES128_ACTIVE
1423deb3ec6SMatthias Ringwald } sm_aes128_state_t;
1433deb3ec6SMatthias Ringwald 
1443deb3ec6SMatthias Ringwald typedef enum {
1453deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_IDLE,
1463deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_GENERAL,
1473deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FOR_CONNECTION,
1483deb3ec6SMatthias Ringwald } address_resolution_mode_t;
1493deb3ec6SMatthias Ringwald 
1503deb3ec6SMatthias Ringwald typedef enum {
151a66b030fSMatthias Ringwald     ADDRESS_RESOLUTION_SUCCEEDED,
1523deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FAILED,
1533deb3ec6SMatthias Ringwald } address_resolution_event_t;
154901c000fSMatthias Ringwald 
155901c000fSMatthias Ringwald typedef enum {
15634b6528fSMatthias Ringwald     EC_KEY_GENERATION_IDLE,
1577df18c15SMatthias Ringwald     EC_KEY_GENERATION_ACTIVE,
1587df18c15SMatthias Ringwald     EC_KEY_GENERATION_DONE,
1597df18c15SMatthias Ringwald } ec_key_generation_state_t;
1607df18c15SMatthias Ringwald 
1617df18c15SMatthias Ringwald typedef enum {
1623cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_NEEDED = 1 << 0,
1633cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1,
1643cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2,
165901c000fSMatthias Ringwald } sm_state_var_t;
166901c000fSMatthias Ringwald 
167c59d0c92SMatthias Ringwald typedef enum {
168c59d0c92SMatthias Ringwald     SM_SC_OOB_IDLE,
169d1a1f6a4SMatthias Ringwald     SM_SC_OOB_W4_RANDOM,
170c59d0c92SMatthias Ringwald     SM_SC_OOB_W2_CALC_CONFIRM,
171c59d0c92SMatthias Ringwald     SM_SC_OOB_W4_CONFIRM,
172c59d0c92SMatthias Ringwald } sm_sc_oob_state_t;
173c59d0c92SMatthias Ringwald 
1746420f61eSMatthias Ringwald typedef uint8_t sm_key24_t[3];
1756420f61eSMatthias Ringwald typedef uint8_t sm_key56_t[7];
1766420f61eSMatthias Ringwald typedef uint8_t sm_key256_t[32];
1776420f61eSMatthias Ringwald 
1783deb3ec6SMatthias Ringwald //
1793deb3ec6SMatthias Ringwald // GLOBAL DATA
1803deb3ec6SMatthias Ringwald //
1813deb3ec6SMatthias Ringwald 
1822d2d4d3cSMatthias Ringwald static bool sm_initialized;
1832d2d4d3cSMatthias Ringwald 
184841468bbSMatthias Ringwald static bool test_use_fixed_local_csrk;
185841468bbSMatthias Ringwald static bool test_use_fixed_local_irk;
1863deb3ec6SMatthias Ringwald 
187192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
188192365feSMatthias Ringwald static uint8_t test_pairing_failure;
189192365feSMatthias Ringwald #endif
190192365feSMatthias Ringwald 
1913deb3ec6SMatthias Ringwald // configuration
1923deb3ec6SMatthias Ringwald static uint8_t sm_accepted_stk_generation_methods;
1933deb3ec6SMatthias Ringwald static uint8_t sm_max_encryption_key_size;
1943deb3ec6SMatthias Ringwald static uint8_t sm_min_encryption_key_size;
1953deb3ec6SMatthias Ringwald static uint8_t sm_auth_req = 0;
1963deb3ec6SMatthias Ringwald static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1974b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
1981979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
1993deb3ec6SMatthias Ringwald 
200b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
201b6f39a74SMatthias Ringwald static uint8_t sm_slave_request_security;
202b6f39a74SMatthias Ringwald #endif
203b6f39a74SMatthias Ringwald 
204c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
205c123d999SMatthias Ringwald static bool sm_sc_only_mode;
206c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
207c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
208c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
209c59d0c92SMatthias Ringwald #endif
210c59d0c92SMatthias Ringwald 
211899e6e02SMatthias Ringwald 
2121979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
213899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
214899e6e02SMatthias Ringwald static void *                sm_tlv_context;
215899e6e02SMatthias Ringwald 
2163deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2173deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2183deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2193deb3ec6SMatthias Ringwald 
2203deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2213deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2223deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2233deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2243deb3ec6SMatthias Ringwald 
2253deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2263deb3ec6SMatthias Ringwald // ..
2273deb3ec6SMatthias Ringwald 
2283deb3ec6SMatthias Ringwald // random address update
2293deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2303deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2313deb3ec6SMatthias Ringwald 
232d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
233514d35fcSMatthias Ringwald // CMAC Calculation: General
234d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
235d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
236d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
237d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2387a766ebfSMatthias Ringwald #endif
239514d35fcSMatthias Ringwald 
240514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2417a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
242d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
243d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
244d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
245d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2467a766ebfSMatthias Ringwald #endif
247514d35fcSMatthias Ringwald 
248514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
249514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
250aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
251514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
252514d35fcSMatthias Ringwald #endif
2533deb3ec6SMatthias Ringwald 
2543deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2553deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2563deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2573deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2583deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2593deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2608f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2613deb3ec6SMatthias Ringwald 
262d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2633deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2643deb3ec6SMatthias Ringwald 
265d1a1f6a4SMatthias Ringwald // crypto
266d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
267d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
268d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
269d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2707df1ef2fSMatthias Ringwald #endif
2717df1ef2fSMatthias Ringwald 
272d1a1f6a4SMatthias Ringwald // temp storage for random data
273d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
274d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
275d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
276d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2773deb3ec6SMatthias Ringwald 
278a036ae12SMatthias Ringwald // to receive events
279e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
280c5b6ce22SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
281a036ae12SMatthias Ringwald static btstack_packet_callback_registration_t l2cap_event_callback_registration;
282c5b6ce22SMatthias Ringwald #endif
283e03e489aSMatthias Ringwald 
28489a78d34SMatthias Ringwald /* to dispatch sm event */
28589a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28689a78d34SMatthias Ringwald 
287ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
288ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
289ece00d2dSMatthias Ringwald 
29009e4d397SMatthias Ringwald // LE Secure Connections
29109e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
29209e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
293fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
29409e4d397SMatthias Ringwald #endif
295df86eb96SMatthias Ringwald 
2963deb3ec6SMatthias Ringwald //
2973deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2983deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2993deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
3003deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
3013deb3ec6SMatthias Ringwald //
3023deb3ec6SMatthias Ringwald 
3033deb3ec6SMatthias Ringwald // data needed for security setup
3043deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3053deb3ec6SMatthias Ringwald 
306ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3073deb3ec6SMatthias Ringwald 
3083deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3093deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
310dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3113deb3ec6SMatthias Ringwald 
3123deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
313715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
314715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3159a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
316715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3173deb3ec6SMatthias Ringwald 
3183deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3193deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3203deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
321a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
32227c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3233deb3ec6SMatthias Ringwald 
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3253deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3263deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3273deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3283deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3293deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3303deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3313deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3323deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3333deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3343deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3353deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3363deb3ec6SMatthias Ringwald 
33768437d83SMatthias Ringwald     uint8_t   sm_state_vars;
338e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
339fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
340446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
341446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
342d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
343e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
344e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
345446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
346446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3472bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
348a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3497df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
350e53be891SMatthias Ringwald #endif
35127c32905SMatthias Ringwald 
3523deb3ec6SMatthias Ringwald     // Phase 3
3533deb3ec6SMatthias Ringwald 
3543deb3ec6SMatthias Ringwald     // key distribution, we generate
3553deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3563deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3573deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3583deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3593deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3603deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3613deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3623deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3633deb3ec6SMatthias Ringwald 
3643deb3ec6SMatthias Ringwald     // key distribution, received from peer
3653deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3663deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3673deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3683deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3693deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3703deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3713deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3723deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3733deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
374715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
375715a43d1SMatthias Ringwald     int       sm_le_device_index;
376715a43d1SMatthias Ringwald #endif
377e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
378e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
379e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
380e0a03c85SMatthias Ringwald #endif
3813deb3ec6SMatthias Ringwald } sm_setup_context_t;
3823deb3ec6SMatthias Ringwald 
3833deb3ec6SMatthias Ringwald //
3843deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3853deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3863deb3ec6SMatthias Ringwald 
3873deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3887149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3893deb3ec6SMatthias Ringwald 
3906b65794dSMilanka Ringwald // @return 1 if oob data is available
3913deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3923deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3934acf7b7bSMatthias 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);
394b96d60a6SMatthias Ringwald static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk);
3953deb3ec6SMatthias Ringwald 
3963deb3ec6SMatthias Ringwald static void sm_run(void);
3977887cd92SMatthias Ringwald static void sm_state_reset(void);
398711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
399711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
400916ea5b2SMatthias Ringwald static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk);
40177e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
40277e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
40377e2e5edSMatthias Ringwald #endif
4043deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
4053deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
412d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
415d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4162a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
417d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
418d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4192a526f21SMatthias Ringwald #endif
420d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
421d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
422d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
423d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
424d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4256d80b495SMatthias 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));
42634b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4276ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4286ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4292a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
430d1a1f6a4SMatthias Ringwald #endif
4310ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4323deb3ec6SMatthias Ringwald 
4333deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4343deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4353deb3ec6SMatthias Ringwald }
4363deb3ec6SMatthias Ringwald 
4371fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4381fbd72c5SMatthias Ringwald //     return packet[0];
4391fbd72c5SMatthias Ringwald // }
4401fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4411fbd72c5SMatthias Ringwald     return packet[1];
4421fbd72c5SMatthias Ringwald }
4431fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4441fbd72c5SMatthias Ringwald     return packet[2];
4451fbd72c5SMatthias Ringwald }
4461fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4471fbd72c5SMatthias Ringwald     return packet[3];
4481fbd72c5SMatthias Ringwald }
4491fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4501fbd72c5SMatthias Ringwald     return packet[4];
4511fbd72c5SMatthias Ringwald }
4521fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4531fbd72c5SMatthias Ringwald     return packet[5];
4541fbd72c5SMatthias Ringwald }
4551fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4561fbd72c5SMatthias Ringwald     return packet[6];
4571fbd72c5SMatthias Ringwald }
4581fbd72c5SMatthias Ringwald 
4591fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4601fbd72c5SMatthias Ringwald     packet[0] = code;
4611fbd72c5SMatthias Ringwald }
4621fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4631fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4641fbd72c5SMatthias Ringwald }
4651fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4661fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4671fbd72c5SMatthias Ringwald }
4681fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4691fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4701fbd72c5SMatthias Ringwald }
4711fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4721fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4731fbd72c5SMatthias Ringwald }
4741fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4751fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4761fbd72c5SMatthias Ringwald }
4771fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4781fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4791fbd72c5SMatthias Ringwald }
4801fbd72c5SMatthias Ringwald 
4811979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
48224c4191dSMatthias Ringwald     return btstack_is_null(random, 8);
4833764b551SMatthias Ringwald }
4843764b551SMatthias Ringwald 
4851979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
48624c4191dSMatthias Ringwald     return btstack_is_null(key, 16);
4873764b551SMatthias Ringwald }
4883764b551SMatthias Ringwald 
48970b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49070b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49170b44dd4SMatthias Ringwald 	UNUSED(ts);
49270b44dd4SMatthias Ringwald 	sm_run();
49370b44dd4SMatthias Ringwald }
49470b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4952d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49684c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49770b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49870b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49970b44dd4SMatthias Ringwald }
50070b44dd4SMatthias Ringwald 
5013deb3ec6SMatthias Ringwald // Key utils
5023deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5033deb3ec6SMatthias Ringwald     int i;
5043deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5053deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5063deb3ec6SMatthias Ringwald     }
5073deb3ec6SMatthias Ringwald }
5083deb3ec6SMatthias Ringwald 
5093deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5103deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5113deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5123deb3ec6SMatthias Ringwald     int i;
5133deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5143deb3ec6SMatthias Ringwald         key[15-i] = 0;
5153deb3ec6SMatthias Ringwald     }
5163deb3ec6SMatthias Ringwald }
5173deb3ec6SMatthias Ringwald 
518899e6e02SMatthias Ringwald // ER / IR checks
51921045273SMatthias Ringwald static void sm_er_ir_set_default(void){
520899e6e02SMatthias Ringwald     int i;
521899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
522899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
523899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
524899e6e02SMatthias Ringwald     }
525899e6e02SMatthias Ringwald }
526899e6e02SMatthias Ringwald 
527899e6e02SMatthias Ringwald static int sm_er_is_default(void){
528899e6e02SMatthias Ringwald     int i;
529899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
530899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
531899e6e02SMatthias Ringwald     }
532899e6e02SMatthias Ringwald     return 1;
533899e6e02SMatthias Ringwald }
534899e6e02SMatthias Ringwald 
535899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
536899e6e02SMatthias Ringwald     int i;
537899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
538899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
539899e6e02SMatthias Ringwald     }
540899e6e02SMatthias Ringwald     return 1;
541899e6e02SMatthias Ringwald }
542899e6e02SMatthias Ringwald 
54373102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54473102768SMatthias Ringwald     UNUSED(channel);
54573102768SMatthias Ringwald 
54673102768SMatthias Ringwald     // log event
54773102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54873102768SMatthias Ringwald     // dispatch to all event handlers
54973102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55073102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55173102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55273102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55373102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55473102768SMatthias Ringwald     }
55573102768SMatthias Ringwald }
55673102768SMatthias Ringwald 
55773102768SMatthias 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){
55873102768SMatthias Ringwald     event[0] = type;
55973102768SMatthias Ringwald     event[1] = event_size - 2;
56073102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56173102768SMatthias Ringwald     event[4] = addr_type;
56273102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56373102768SMatthias Ringwald }
56473102768SMatthias Ringwald 
56573102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56673102768SMatthias Ringwald     uint8_t event[11];
56773102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56873102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56973102768SMatthias Ringwald }
57073102768SMatthias Ringwald 
57173102768SMatthias 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){
57273102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57373102768SMatthias Ringwald     bd_addr_t identity_address;
57473102768SMatthias Ringwald     int identity_address_type;
57573102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
57673102768SMatthias Ringwald 
57773102768SMatthias Ringwald     uint8_t event[20];
57873102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57973102768SMatthias Ringwald     event[11] = identity_address_type;
58073102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58173102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58373102768SMatthias Ringwald }
58473102768SMatthias Ringwald 
58573102768SMatthias 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){
58673102768SMatthias Ringwald     uint8_t event[12];
58773102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58873102768SMatthias Ringwald     event[11] = status;
58973102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59073102768SMatthias Ringwald }
59173102768SMatthias Ringwald 
59273102768SMatthias Ringwald 
59373102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
59473102768SMatthias Ringwald 
5953ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
5963ab61f77SMatthias Ringwald 
5977b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
59873102768SMatthias Ringwald 
59973102768SMatthias Ringwald     int       identity_addr_type;
60073102768SMatthias Ringwald     bd_addr_t identity_addr;
6013c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6023c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60373102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6043c0e26deSMatthias Ringwald     } else {
6053c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6063c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
607*d5529700SMatthias Ringwald         // cppcheck-suppress uninitvar ; identity_addr is reported as uninitialized although it's the destination of the memcpy
6083c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6093c0e26deSMatthias Ringwald     }
61073102768SMatthias Ringwald 
61173102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61273102768SMatthias Ringwald }
61373102768SMatthias Ringwald 
61473102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
61573102768SMatthias Ringwald 
61660be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
61760be5b21SMatthias Ringwald 
6187b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
61973102768SMatthias Ringwald 
62073102768SMatthias Ringwald     int       identity_addr_type;
62173102768SMatthias Ringwald     bd_addr_t identity_addr;
6223c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6233c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62473102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6253c0e26deSMatthias Ringwald     } else {
6263c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6273c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
628*d5529700SMatthias Ringwald         // cppcheck-suppress uninitvar ; identity_addr is reported as uninitialized although it's the destination of the memcpy
6293c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6303c0e26deSMatthias Ringwald     }
63173102768SMatthias Ringwald 
63273102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63373102768SMatthias Ringwald }
63473102768SMatthias Ringwald 
635d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
636d3c12277SMatthias Ringwald 
637d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
638d3c12277SMatthias Ringwald 
639d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
640d3c12277SMatthias Ringwald 
641d3c12277SMatthias Ringwald     uint8_t event[11];
642d3c12277SMatthias 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);
643d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
644d3c12277SMatthias Ringwald }
645d3c12277SMatthias Ringwald 
6460ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
647f61072f5SMatthias Ringwald 
648d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
649d77906ffSMatthias Ringwald 
65069f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65169f82ad8SMatthias Ringwald 
6520ccf6c9cSMatthias Ringwald     uint8_t event[13];
6530ccf6c9cSMatthias 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);
6540ccf6c9cSMatthias Ringwald     event[11] = status;
6550ccf6c9cSMatthias Ringwald     event[12] = reason;
6560ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6570ccf6c9cSMatthias Ringwald }
6580ccf6c9cSMatthias Ringwald 
6593deb3ec6SMatthias Ringwald // SMP Timeout implementation
6603deb3ec6SMatthias Ringwald 
6613deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6623deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6633deb3ec6SMatthias Ringwald //
6643deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6653deb3ec6SMatthias Ringwald //
6663deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6673deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6683deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6693deb3ec6SMatthias Ringwald // established.
6703deb3ec6SMatthias Ringwald 
671ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6723deb3ec6SMatthias Ringwald     log_info("SM timeout");
673c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6743deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67568a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6760ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6773deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6783deb3ec6SMatthias Ringwald 
6793deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6803deb3ec6SMatthias Ringwald     sm_run();
6813deb3ec6SMatthias Ringwald }
6823deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
683528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68491a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
685528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
686528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
687528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6883deb3ec6SMatthias Ringwald }
6893deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
690528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6913deb3ec6SMatthias Ringwald }
6923deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6933deb3ec6SMatthias Ringwald     sm_timeout_stop();
6943deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6953deb3ec6SMatthias Ringwald }
6963deb3ec6SMatthias Ringwald 
6973deb3ec6SMatthias Ringwald // end of sm timeout
6983deb3ec6SMatthias Ringwald 
6993deb3ec6SMatthias Ringwald // GAP Random Address updates
7003deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
701ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7023deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7033deb3ec6SMatthias Ringwald 
7043deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
705899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
706d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
707fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
70870b44dd4SMatthias Ringwald     sm_trigger_run();
7093deb3ec6SMatthias Ringwald }
7103deb3ec6SMatthias Ringwald 
711ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7129ec2630cSMatthias Ringwald     UNUSED(timer);
7139ec2630cSMatthias Ringwald 
7143deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
715528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
716528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7173deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7183deb3ec6SMatthias Ringwald }
7193deb3ec6SMatthias Ringwald 
7203deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
721528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
722528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
723528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7243deb3ec6SMatthias Ringwald }
7253deb3ec6SMatthias Ringwald 
7263deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
727528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7283deb3ec6SMatthias Ringwald }
7293deb3ec6SMatthias Ringwald 
7303deb3ec6SMatthias Ringwald // ah(k,r) helper
7313deb3ec6SMatthias Ringwald // r = padding || r
7323deb3ec6SMatthias Ringwald // r - 24 bit value
7334a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7343deb3ec6SMatthias Ringwald     // r'= padding || r
7353deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7366535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7373deb3ec6SMatthias Ringwald }
7383deb3ec6SMatthias Ringwald 
7393deb3ec6SMatthias Ringwald // d1 helper
7403deb3ec6SMatthias Ringwald // d' = padding || r || d
7413deb3ec6SMatthias Ringwald // d,r - 16 bit values
7424a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7433deb3ec6SMatthias Ringwald     // d'= padding || r || d
7443deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
745f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
746f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7473deb3ec6SMatthias Ringwald }
7483deb3ec6SMatthias Ringwald 
7493deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7504a6806f3SMatthias 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){
7513deb3ec6SMatthias Ringwald 
7523deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7533deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7543deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7553deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7563deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7573deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7583deb3ec6SMatthias Ringwald 
7593deb3ec6SMatthias Ringwald     sm_key_t p1;
7609c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7619c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7623deb3ec6SMatthias Ringwald     p1[14] = rat;
7633deb3ec6SMatthias Ringwald     p1[15] = iat;
7648314c363SMatthias Ringwald     log_info_key("p1", p1);
7658314c363SMatthias Ringwald     log_info_key("r", r);
7663deb3ec6SMatthias Ringwald 
7673deb3ec6SMatthias Ringwald     // t1 = r xor p1
7683deb3ec6SMatthias Ringwald     int i;
7693deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7703deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7713deb3ec6SMatthias Ringwald     }
7728314c363SMatthias Ringwald     log_info_key("t1", t1);
7733deb3ec6SMatthias Ringwald }
7743deb3ec6SMatthias Ringwald 
7753deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7764a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7773deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7783deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7793deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7803deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7813deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7823deb3ec6SMatthias Ringwald 
7833deb3ec6SMatthias Ringwald     sm_key_t p2;
784*d5529700SMatthias Ringwald     // cppcheck-suppress uninitvar ; p2 is reported as uninitialized
7853deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7866535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7876535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7888314c363SMatthias Ringwald     log_info_key("p2", p2);
7893deb3ec6SMatthias Ringwald 
7903deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7913deb3ec6SMatthias Ringwald     int i;
7923deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7933deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7943deb3ec6SMatthias Ringwald     }
7958314c363SMatthias Ringwald     log_info_key("t3", t3);
7963deb3ec6SMatthias Ringwald }
7973deb3ec6SMatthias Ringwald 
7984a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
7998314c363SMatthias Ringwald     log_info_key("r1", r1);
8008314c363SMatthias Ringwald     log_info_key("r2", r2);
8016535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8026535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8033deb3ec6SMatthias Ringwald }
8043deb3ec6SMatthias Ringwald 
805fbe050beSMatthias Ringwald 
8063deb3ec6SMatthias Ringwald // decide on stk generation based on
8073deb3ec6SMatthias Ringwald // - pairing request
8083deb3ec6SMatthias Ringwald // - io capabilities
8093deb3ec6SMatthias Ringwald // - OOB data availability
8103deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8113deb3ec6SMatthias Ringwald 
8128334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8138334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8148334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8158334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8168334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8178334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8188334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8198334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8208334d3d8SMatthias Ringwald     };
8218334d3d8SMatthias Ringwald 
8228334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8238334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8248334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8258334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8278334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8288334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8298334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8308334d3d8SMatthias Ringwald     };
8318334d3d8SMatthias Ringwald #endif
8328334d3d8SMatthias Ringwald 
8333deb3ec6SMatthias Ringwald     // default: just works
8343deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8353deb3ec6SMatthias Ringwald 
83627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83727c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83827c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8394ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84027c32905SMatthias Ringwald #else
84127c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84227c32905SMatthias Ringwald #endif
84398d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84427c32905SMatthias Ringwald 
84565a9a04eSMatthias Ringwald 
84665a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8471979f09cSMatthias Ringwald     bool use_oob;
84865a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
84965a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85065a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8511979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85265a9a04eSMatthias Ringwald     } else {
85365a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85465a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8551979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85665a9a04eSMatthias Ringwald     }
85765a9a04eSMatthias Ringwald     if (use_oob){
85865a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
85965a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86065a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86165a9a04eSMatthias Ringwald         return;
86265a9a04eSMatthias Ringwald     }
86365a9a04eSMatthias Ringwald 
86427c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86527c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86627c32905SMatthias Ringwald     // model shall be used.
8674ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8684ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
86927c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87027c32905SMatthias Ringwald         return;
87127c32905SMatthias Ringwald     }
87227c32905SMatthias Ringwald 
8733deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8743deb3ec6SMatthias Ringwald     sm_reset_tk();
8753deb3ec6SMatthias Ringwald 
8763deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8778da2e96dSMatthias Ringwald     if ((sm_pairing_packet_get_io_capability(setup->sm_m_preq) > IO_CAPABILITY_KEYBOARD_DISPLAY) || (sm_pairing_packet_get_io_capability(setup->sm_s_pres) > IO_CAPABILITY_KEYBOARD_DISPLAY)){
8783deb3ec6SMatthias Ringwald         return;
8793deb3ec6SMatthias Ringwald     }
8803deb3ec6SMatthias Ringwald 
8813deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8823deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88327c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88427c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88527c32905SMatthias Ringwald 
88627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
887c6b7cbd9SMatthias Ringwald     // table not define by default
88827c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
88927c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89027c32905SMatthias Ringwald     }
89127c32905SMatthias Ringwald #endif
89227c32905SMatthias Ringwald     setup->sm_stk_generation_method = generation_method[sm_pairing_packet_get_io_capability(setup->sm_s_pres)][sm_pairing_packet_get_io_capability(setup->sm_m_preq)];
89327c32905SMatthias Ringwald 
8943deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8951ad129beSMatthias Ringwald         sm_pairing_packet_get_io_capability(setup->sm_m_preq), sm_pairing_packet_get_io_capability(setup->sm_s_pres), setup->sm_stk_generation_method);
8963deb3ec6SMatthias Ringwald }
8973deb3ec6SMatthias Ringwald 
8983deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
8993deb3ec6SMatthias Ringwald     int flags = 0;
9003deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9013deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9023deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9033deb3ec6SMatthias Ringwald     }
9043deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9053deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9073deb3ec6SMatthias Ringwald     }
9083deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9103deb3ec6SMatthias Ringwald     }
9113deb3ec6SMatthias Ringwald     return flags;
9123deb3ec6SMatthias Ringwald }
9133deb3ec6SMatthias Ringwald 
9149a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9153deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9169a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9179a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
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 
1025ea9b6796SMatthias Ringwald static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){
1026ea9b6796SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10275baa755bSMatthias Ringwald     uint8_t event[12];
1028f6a153d5SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10295baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
1030f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1031ea9b6796SMatthias Ringwald }
1032ea9b6796SMatthias Ringwald 
103374b4d42aSMatthias Ringwald static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn, uint8_t event_type){
10345baa755bSMatthias Ringwald     uint8_t event[16];
1035f6a153d5SMatthias Ringwald     uint32_t passkey = big_endian_read_32(setup->sm_tk, 12);
103674b4d42aSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle,
1037f6a153d5SMatthias Ringwald                         sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10385baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
10395baa755bSMatthias Ringwald     little_endian_store_32(event, 12, passkey);
1040f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1041ea9b6796SMatthias Ringwald }
1042ea9b6796SMatthias Ringwald 
10433deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1044446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10453deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1046d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10473deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10483deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
104942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1050ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10513deb3ec6SMatthias Ringwald             } else {
105274b4d42aSMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER);
10533deb3ec6SMatthias Ringwald             }
10543deb3ec6SMatthias Ringwald             break;
10553deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
105642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
105774b4d42aSMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER);
10583deb3ec6SMatthias Ringwald             } else {
1059ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10603deb3ec6SMatthias Ringwald             }
10613deb3ec6SMatthias Ringwald             break;
106247fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
1063ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10643deb3ec6SMatthias Ringwald             break;
106547fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
106674b4d42aSMatthias Ringwald             sm_trigger_user_response_passkey(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST);
106727c32905SMatthias Ringwald             break;
10683deb3ec6SMatthias Ringwald         case JUST_WORKS:
1069ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST);
10703deb3ec6SMatthias Ringwald             break;
10713deb3ec6SMatthias Ringwald         case OOB:
10723deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10733deb3ec6SMatthias Ringwald             break;
10747bbeb3adSMilanka Ringwald         default:
10757bbeb3adSMilanka Ringwald             btstack_assert(false);
10767bbeb3adSMilanka Ringwald             break;
10773deb3ec6SMatthias Ringwald     }
10783deb3ec6SMatthias Ringwald }
10793deb3ec6SMatthias Ringwald 
108061d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
10815fa700b1SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, setup->sm_key_distribution_expected_set);
1082b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10833deb3ec6SMatthias Ringwald }
10843deb3ec6SMatthias Ringwald 
1085711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10867149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10873deb3ec6SMatthias Ringwald         sm_timeout_stop();
10887149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1089711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1090c085d9ffSMatthias Ringwald 
1091c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1092c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1093c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1094c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1095c085d9ffSMatthias Ringwald         }
1096c085d9ffSMatthias Ringwald #endif
10973deb3ec6SMatthias Ringwald     }
10983deb3ec6SMatthias Ringwald }
10993deb3ec6SMatthias Ringwald 
11007d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11011dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11020ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11031dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11041dca9d8aSMatthias Ringwald }
11051dca9d8aSMatthias Ringwald 
11063deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1107bb09604fSMatthias Ringwald 
1108bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11093deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1110bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11113deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1112bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1113bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1114bb09604fSMatthias Ringwald #endif
11157ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11167ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11177ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11187ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11197ece0eaaSMatthias Ringwald         }
11207ece0eaaSMatthias Ringwald #endif
11213deb3ec6SMatthias Ringwald     }
11223deb3ec6SMatthias Ringwald     return flags;
11233deb3ec6SMatthias Ringwald }
11243deb3ec6SMatthias Ringwald 
1125d7471931SMatthias Ringwald static void sm_reset_setup(void){
11263deb3ec6SMatthias Ringwald     // fill in sm setup
1127901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1128dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1129d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11303deb3ec6SMatthias Ringwald     sm_reset_tk();
1131d7471931SMatthias Ringwald }
1132d7471931SMatthias Ringwald 
1133d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1134d7471931SMatthias Ringwald     // fill in sm setup
11353deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11366535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11373deb3ec6SMatthias Ringwald 
1138a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11399305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1140a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11413deb3ec6SMatthias Ringwald     }
11423deb3ec6SMatthias Ringwald 
1143a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1144a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11454acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11464acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1147a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11489305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11494acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1150a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1151a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1152a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1153a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11544acf7b7bSMatthias Ringwald                     setup->sm_ra);
11554acf7b7bSMatthias Ringwald             } else {
11564acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11574acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11584acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11594acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11604acf7b7bSMatthias Ringwald                     setup->sm_rb);
11614acf7b7bSMatthias Ringwald             }
1162a680ba6bSMatthias Ringwald         } else {
1163a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1164a680ba6bSMatthias Ringwald         }
1165a680ba6bSMatthias Ringwald     }
1166a680ba6bSMatthias Ringwald #endif
1167a680ba6bSMatthias Ringwald 
11683deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
116942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11703deb3ec6SMatthias Ringwald         // slave
11713deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11723deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1173d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11746535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1175d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11763deb3ec6SMatthias Ringwald     } else {
11773deb3ec6SMatthias Ringwald         // master
11783deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11793deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1180d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11816535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1182d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11833deb3ec6SMatthias Ringwald 
1184d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11851ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11861ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11873deb3ec6SMatthias Ringwald     }
11883deb3ec6SMatthias Ringwald 
118957132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1190d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11912c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11922c041b42SMatthias Ringwald     // enable SC for SC only mode
11932c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11942c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1195d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
11962c041b42SMatthias Ringwald     }
11972c041b42SMatthias Ringwald #endif
119857132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
119957132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120057132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120157132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120257132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120357132f12SMatthias Ringwald 	}
120457132f12SMatthias Ringwald #endif
12051ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1206a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1207df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1208d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12093deb3ec6SMatthias Ringwald }
12103deb3ec6SMatthias Ringwald 
12113deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12123deb3ec6SMatthias Ringwald 
12133deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12149a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12159a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
121642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121752f9cf63SMatthias Ringwald         // slave / responder
12183deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12199a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12209a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12213deb3ec6SMatthias Ringwald     } else {
12223deb3ec6SMatthias Ringwald         // master / initiator
12233deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12249a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12259a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12263deb3ec6SMatthias Ringwald     }
12273deb3ec6SMatthias Ringwald 
12283deb3ec6SMatthias Ringwald     // check key size
12292c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12302c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12312c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12322c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12332c041b42SMatthias Ringwald     }
12342c041b42SMatthias Ringwald #endif
12351ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12364ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12373deb3ec6SMatthias Ringwald 
1238eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12393deb3ec6SMatthias Ringwald     sm_setup_tk();
12403deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12413deb3ec6SMatthias Ringwald 
12423deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12433deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12443deb3ec6SMatthias Ringwald 
1245eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12462c041b42SMatthias Ringwald     // Check LE SC Only mode
12473cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12483cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12493cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12503cdbe9dbSMatthias Ringwald     }
12513cdbe9dbSMatthias Ringwald 
12529a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1253eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12549a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12559a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1256eddc894fSMatthias Ringwald     }
1257eddc894fSMatthias Ringwald #endif
1258eddc894fSMatthias Ringwald 
125952f9cf63SMatthias Ringwald     // identical to responder
12609a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
126152f9cf63SMatthias Ringwald 
12623deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1263c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12643deb3ec6SMatthias Ringwald 
12653deb3ec6SMatthias Ringwald     return 0;
12663deb3ec6SMatthias Ringwald }
12673deb3ec6SMatthias Ringwald 
12683deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     // cache and reset context
12713deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12723deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12733deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12743deb3ec6SMatthias Ringwald 
12753deb3ec6SMatthias Ringwald     // reset context
12763deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12773deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12783deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1279711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12803deb3ec6SMatthias Ringwald 
12813deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1282d2e90122SMatthias Ringwald     sm_key_t ltk;
12831979f09cSMatthias Ringwald     bool have_ltk;
12846c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12851979f09cSMatthias Ringwald     bool trigger_pairing;
128642134bc6SMatthias Ringwald #endif
12873deb3ec6SMatthias Ringwald     switch (mode){
12883deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12893deb3ec6SMatthias Ringwald             break;
12903deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12913deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1292711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12936c44b759SMatthias Ringwald 
12946c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12956c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12966c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12976c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12986c44b759SMatthias Ringwald 
12993deb3ec6SMatthias Ringwald             switch (event){
1300a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13013deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13023deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1303a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13046c44b759SMatthias Ringwald 
13056c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13066c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13076c44b759SMatthias Ringwald 
13086c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13096c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1310212d735eSMatthias Ringwald                         // IRK required before, continue
13116c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13126c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13136c39055aSMatthias Ringwald                             break;
13146c39055aSMatthias Ringwald                         }
1315212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1316212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1317212d735eSMatthias Ringwald                             break;
1318212d735eSMatthias Ringwald                         }
13197af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13207af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13216c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13227af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13237af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13246c44b759SMatthias Ringwald #endif
13257af5dcd5SMatthias Ringwald 
13267af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13271979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13287af5dcd5SMatthias Ringwald 
13297af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13307af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13317af5dcd5SMatthias Ringwald                             if (have_ltk){
13327af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13337af5dcd5SMatthias Ringwald                             } else {
13347af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13357af5dcd5SMatthias Ringwald                             }
13367af5dcd5SMatthias Ringwald                             sm_trigger_run();
13376c44b759SMatthias Ringwald                         }
13386c44b759SMatthias Ringwald #endif
13396c44b759SMatthias Ringwald                     } else {
13406c44b759SMatthias Ringwald 
134142134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13426c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13436c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13446c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13451979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13463deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134709ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134832bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1349c245ca32SMatthias Ringwald 
1350d4af1595SMatthias Ringwald                         if (have_ltk){
13516a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1352b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135332bc5d65SMatthias Ringwald #else
135432bc5d65SMatthias Ringwald                             if (trigger_pairing){
135532bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135632bc5d65SMatthias Ringwald                             } else {
135732bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135832bc5d65SMatthias Ringwald                             }
135932bc5d65SMatthias Ringwald #endif
136032bc5d65SMatthias Ringwald                         }
136132bc5d65SMatthias Ringwald 
136232bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13636c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13645567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1365d4af1595SMatthias Ringwald                             break;
1366d4af1595SMatthias Ringwald                         }
13676c44b759SMatthias Ringwald 
13686c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13696c44b759SMatthias Ringwald                         if (trigger_pairing){
13703deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1371d4af1595SMatthias Ringwald                             break;
13723deb3ec6SMatthias Ringwald                         }
137342134bc6SMatthias Ringwald #endif
1374298ab52bSMatthias Ringwald                     }
13753deb3ec6SMatthias Ringwald                     break;
13763deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13773deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13786c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13797af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13806c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13816c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13826c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13836c39055aSMatthias Ringwald                         }
13847af5dcd5SMatthias Ringwald                         // send security request if requested
13857af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13867af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13877af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13887af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13897af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13907af5dcd5SMatthias Ringwald                         }
13916c39055aSMatthias Ringwald                         break;
13927af5dcd5SMatthias Ringwald #endif
13936c39055aSMatthias Ringwald                     }
139442134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139509ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13963deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139709ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13983deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139942134bc6SMatthias Ringwald #endif
14003deb3ec6SMatthias Ringwald                     break;
14017bbeb3adSMilanka Ringwald 
14027bbeb3adSMilanka Ringwald                 default:
14037bbeb3adSMilanka Ringwald                     btstack_assert(false);
14047bbeb3adSMilanka Ringwald                     break;
14053deb3ec6SMatthias Ringwald             }
14063deb3ec6SMatthias Ringwald             break;
14073deb3ec6SMatthias Ringwald         default:
14083deb3ec6SMatthias Ringwald             break;
14093deb3ec6SMatthias Ringwald     }
14103deb3ec6SMatthias Ringwald 
14113deb3ec6SMatthias Ringwald     switch (event){
1412a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1413711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14143deb3ec6SMatthias Ringwald             break;
14153deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1416711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14173deb3ec6SMatthias Ringwald             break;
14187bbeb3adSMilanka Ringwald         default:
14197bbeb3adSMilanka Ringwald             btstack_assert(false);
14207bbeb3adSMilanka Ringwald             break;
14213deb3ec6SMatthias Ringwald     }
14223deb3ec6SMatthias Ringwald }
14233deb3ec6SMatthias Ringwald 
142455f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14253deb3ec6SMatthias Ringwald     int le_db_index = -1;
14263deb3ec6SMatthias Ringwald 
14273deb3ec6SMatthias Ringwald     // lookup device based on IRK
14283deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14293deb3ec6SMatthias Ringwald         int i;
1430092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14313deb3ec6SMatthias Ringwald             sm_key_t irk;
14323deb3ec6SMatthias Ringwald             bd_addr_t address;
1433c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14343deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1435adf5eaa9SMatthias Ringwald             // skip unused entries
1436c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
143711d10bdaSMatthias Ringwald             // compare Identity Address
143811d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
143911d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1440c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1441c7e2c1a5SMatthias Ringwald 
14423deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14433deb3ec6SMatthias Ringwald             le_db_index = i;
14443deb3ec6SMatthias Ringwald             break;
14453deb3ec6SMatthias Ringwald         }
1446c7e2c1a5SMatthias Ringwald     } else {
1447c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1448c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14493deb3ec6SMatthias Ringwald     }
14503deb3ec6SMatthias Ringwald 
14513deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14523deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1453c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14543deb3ec6SMatthias Ringwald         int i;
1455092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14563deb3ec6SMatthias Ringwald             bd_addr_t address;
1457adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14583deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1459adf5eaa9SMatthias Ringwald             // skip unused entries
1460adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14613deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14625df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14633deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14643deb3ec6SMatthias Ringwald                 le_db_index = i;
14653deb3ec6SMatthias Ringwald                 break;
14663deb3ec6SMatthias Ringwald             }
14673deb3ec6SMatthias Ringwald         }
14683deb3ec6SMatthias Ringwald     }
14693deb3ec6SMatthias Ringwald 
14703deb3ec6SMatthias Ringwald     // if not found, add to db
147102b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14723deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14733deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147402b02cffSMatthias Ringwald         new_to_le_device_db = true;
14753deb3ec6SMatthias Ringwald     }
14763deb3ec6SMatthias Ringwald 
14773deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14783deb3ec6SMatthias Ringwald 
147902b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148002b02cffSMatthias Ringwald         if (!new_to_le_device_db){
148102b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148202b02cffSMatthias Ringwald         }
148302b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148402b02cffSMatthias Ringwald #else
148502b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
148602b02cffSMatthias Ringwald #endif
148702b02cffSMatthias Ringwald 
148848163929SMatthias 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);
1489e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14907710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
149148163929SMatthias Ringwald 
1492eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14933deb3ec6SMatthias Ringwald         // store local CSRK
1494715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1495715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14963deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
14973deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14983deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
14993deb3ec6SMatthias Ringwald         }
15003deb3ec6SMatthias Ringwald 
15013deb3ec6SMatthias Ringwald         // store remote CSRK
15023deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15033deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
15043deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15053deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15063deb3ec6SMatthias Ringwald         }
1507eda85fbfSMatthias Ringwald #endif
150878f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
150978f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1510e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151178f44163SMatthias Ringwald             uint8_t zero_rand[8];
151278f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
151378f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15143dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151578f44163SMatthias Ringwald         }
151678f44163SMatthias Ringwald 
1517e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151878f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151978f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1520e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15213deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15223dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152378f44163SMatthias Ringwald 
15243deb3ec6SMatthias Ringwald         }
15253deb3ec6SMatthias Ringwald     }
152655f09f49SMatthias Ringwald }
152755f09f49SMatthias Ringwald 
15288980298aSMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
15298980298aSMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
15308980298aSMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
15318980298aSMatthias Ringwald }
15328980298aSMatthias Ringwald 
1533321397a4SMatthias Ringwald static int sm_lookup_by_address(void) {
15341a55487aSMatthias Ringwald     int i;
15351a55487aSMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
15361a55487aSMatthias Ringwald         bd_addr_t address;
15371a55487aSMatthias Ringwald         int address_type = BD_ADDR_TYPE_UNKNOWN;
15381a55487aSMatthias Ringwald         le_device_db_info(i, &address_type, address, NULL);
15391a55487aSMatthias Ringwald         // skip unused entries
15401a55487aSMatthias Ringwald         if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
15411a55487aSMatthias Ringwald         if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
15421a55487aSMatthias Ringwald             return i;
15431a55487aSMatthias Ringwald         }
15441a55487aSMatthias Ringwald     }
15451a55487aSMatthias Ringwald     return -1;
15461a55487aSMatthias Ringwald }
15471a55487aSMatthias Ringwald 
15482e08b70bSMatthias Ringwald static void sm_remove_le_device_db_entry(uint16_t i) {
15492e08b70bSMatthias Ringwald     le_device_db_remove(i);
1550672dc582SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1551672dc582SMatthias Ringwald     // to remove an entry from the resolving list requires its identity address, which was already deleted
1552672dc582SMatthias Ringwald     // fully reload resolving list instead
1553672dc582SMatthias Ringwald     gap_load_resolving_list_from_le_device_db();
1554672dc582SMatthias Ringwald #endif
15552e08b70bSMatthias Ringwald }
15562e08b70bSMatthias Ringwald 
15578980298aSMatthias Ringwald static uint8_t sm_key_distribution_validate_received(sm_connection_t * sm_conn){
15581a55487aSMatthias Ringwald     // if identity is provided, abort if we have bonding with same address but different irk
15591a55487aSMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
1560321397a4SMatthias Ringwald         int index = sm_lookup_by_address();
15611a55487aSMatthias Ringwald         if (index >= 0){
15621a55487aSMatthias Ringwald             sm_key_t irk;
15631a55487aSMatthias Ringwald             le_device_db_info(index, NULL, NULL, irk);
15641a55487aSMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0){
15651a55487aSMatthias Ringwald                 // IRK doesn't match, delete bonding information
15661a55487aSMatthias Ringwald                 log_info("New IRK for %s (type %u) does not match stored IRK -> delete bonding information", bd_addr_to_str(sm_conn->sm_peer_address), sm_conn->sm_peer_addr_type);
15679202d845SMatthias Ringwald                 sm_remove_le_device_db_entry(index);
15681a55487aSMatthias Ringwald             }
15691a55487aSMatthias Ringwald         }
15701a55487aSMatthias Ringwald     }
15718980298aSMatthias Ringwald     return 0;
15728980298aSMatthias Ringwald }
15738980298aSMatthias Ringwald 
157455f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
157555f09f49SMatthias Ringwald 
15768980298aSMatthias Ringwald     // abort pairing if received keys are not valid
15778980298aSMatthias Ringwald     uint8_t reason = sm_key_distribution_validate_received(sm_conn);
15788980298aSMatthias Ringwald     if (reason != 0){
15798980298aSMatthias Ringwald         sm_pairing_error(sm_conn, reason);
15808980298aSMatthias Ringwald         return;
15818980298aSMatthias Ringwald     }
15828980298aSMatthias Ringwald 
158355f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
158455f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
158555f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
158655f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
158755f09f49SMatthias Ringwald 
158855f09f49SMatthias Ringwald     if (bonding_enabled){
158955f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
159027ef8bc8SMatthias Ringwald     } else {
159127ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
159227ef8bc8SMatthias Ringwald     }
15933deb3ec6SMatthias Ringwald }
15943deb3ec6SMatthias Ringwald 
1595688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1596688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1597688a08f9SMatthias Ringwald }
1598688a08f9SMatthias Ringwald 
15999af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1600688a08f9SMatthias Ringwald 
1601dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1602945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1603f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1604dc300847SMatthias Ringwald 
1605b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1606b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
16071f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1608b90c4e75SMatthias Ringwald     } else {
1609b90c4e75SMatthias 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);
1610b35a3de2SMatthias Ringwald     }
1611b35a3de2SMatthias Ringwald }
1612b35a3de2SMatthias Ringwald 
1613688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
161442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1615688a08f9SMatthias Ringwald         // Responder
16164acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
16174acf7b7bSMatthias Ringwald             // generate Nb
16184acf7b7bSMatthias Ringwald             log_info("Generate Nb");
16196ca80073SMatthias 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);
16204acf7b7bSMatthias Ringwald         } else {
1621688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
16224acf7b7bSMatthias Ringwald         }
1623688a08f9SMatthias Ringwald     } else {
1624688a08f9SMatthias Ringwald         // Initiator role
1625688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1626688a08f9SMatthias Ringwald             case JUST_WORKS:
1627dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1628688a08f9SMatthias Ringwald                 break;
1629688a08f9SMatthias Ringwald 
163047fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1631bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1632688a08f9SMatthias Ringwald                 break;
1633688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1634688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
163547fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
16364ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1637b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1638688a08f9SMatthias Ringwald                 } else {
1639dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1640688a08f9SMatthias Ringwald                 }
1641688a08f9SMatthias Ringwald                 break;
1642688a08f9SMatthias Ringwald             case OOB:
164365a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1644688a08f9SMatthias Ringwald                 break;
16457bbeb3adSMilanka Ringwald             default:
16467bbeb3adSMilanka Ringwald                 btstack_assert(false);
16477bbeb3adSMilanka Ringwald                 break;
1648688a08f9SMatthias Ringwald         }
1649688a08f9SMatthias Ringwald     }
1650688a08f9SMatthias Ringwald }
1651688a08f9SMatthias Ringwald 
1652aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1653688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1654688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1655688a08f9SMatthias Ringwald 
1656c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1657c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1658a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1659c59d0c92SMatthias Ringwald         return;
1660c59d0c92SMatthias Ringwald     }
1661c59d0c92SMatthias Ringwald 
1662bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1663bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16646857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16652bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1666b4f65634SMatthias Ringwald #endif
1667bd57ffebSMatthias Ringwald 
1668bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1669aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16706535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1671bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1672aec94140SMatthias Ringwald             break;
1673688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1674688a08f9SMatthias Ringwald             // check
1675688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1676bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1677688a08f9SMatthias Ringwald                 break;
1678688a08f9SMatthias Ringwald             }
1679bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1680688a08f9SMatthias Ringwald             break;
1681901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1682901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1683901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1684901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1685901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1686019005a0SMatthias Ringwald             break;
1687019005a0SMatthias Ringwald         }
16880346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16896535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1690bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16910346c37cSMatthias Ringwald             break;
16920346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16936535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1694bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16950346c37cSMatthias Ringwald             break;
16960346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1697b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1698b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1699b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1700b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
17016535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
17026535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1703893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1704bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1705019005a0SMatthias Ringwald             break;
1706901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
17076535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
170842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1709901c000fSMatthias Ringwald                 // responder
1710901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1711901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1712901c000fSMatthias Ringwald                 } else {
1713901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1714901c000fSMatthias Ringwald                 }
1715901c000fSMatthias Ringwald             } else {
1716901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1717901c000fSMatthias Ringwald             }
1718901c000fSMatthias Ringwald             break;
1719901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1720901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1721901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1722aec94140SMatthias Ringwald                 break;
1723aec94140SMatthias Ringwald             }
172442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1725901c000fSMatthias Ringwald                 // responder
1726901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1727901c000fSMatthias Ringwald             } else {
1728901c000fSMatthias Ringwald                 // initiator
1729901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1730bd57ffebSMatthias Ringwald             }
1731901c000fSMatthias Ringwald             break;
17326857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
173357132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
17346535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
173557132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
17362bacf595SMatthias Ringwald             break;
173757132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
17382bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
17392bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
17402bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
17418974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
174255160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
17438974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
17442bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
17452bacf595SMatthias Ringwald             } else {
17462bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
17472bacf595SMatthias Ringwald             }
17480ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17492bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17502bacf595SMatthias Ringwald             break;
1751e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1752e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1753e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1754e0a03c85SMatthias Ringwald             break;
1755e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1756e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1757e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1758e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1759e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1760e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1761e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1762c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1763e0a03c85SMatthias Ringwald             break;
1764bdb14b0eSMatthias Ringwald #endif
1765bd57ffebSMatthias Ringwald         default:
1766bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1767bd57ffebSMatthias Ringwald             break;
1768bd57ffebSMatthias Ringwald     }
176970b44dd4SMatthias Ringwald     sm_trigger_run();
1770aec94140SMatthias Ringwald }
1771aec94140SMatthias Ringwald 
1772688a08f9SMatthias 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){
1773dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1774aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17756535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17766535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1777aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1778aec94140SMatthias Ringwald     log_info("f4 key");
1779aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1780aec94140SMatthias Ringwald     log_info("f4 message");
1781dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1782d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1783aec94140SMatthias Ringwald }
1784aec94140SMatthias Ringwald 
17850346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17860346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17870346c37cSMatthias Ringwald 
17880346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17898334d3d8SMatthias Ringwald 
17908334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17918334d3d8SMatthias Ringwald 
179240c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17930346c37cSMatthias Ringwald     // calculate salt for f5
17940346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17950346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17966535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1797d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17980346c37cSMatthias Ringwald }
17990346c37cSMatthias Ringwald 
18000346c37cSMatthias 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){
18010346c37cSMatthias Ringwald     const uint16_t message_len = 53;
18020346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18030346c37cSMatthias Ringwald 
18040346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
18050346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
18066535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
18076535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
18086535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
18096535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
18106535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
18120346c37cSMatthias Ringwald     log_info("f5 key");
18130346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18140346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
18150346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1816d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18170346c37cSMatthias Ringwald }
18180346c37cSMatthias Ringwald 
18190346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
18200346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
18210346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
18220346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18236535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18246535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
182542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
18260346c37cSMatthias Ringwald         // responder
18270346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
18280346c37cSMatthias Ringwald     } else {
18290346c37cSMatthias Ringwald         // initiator
18300346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
18310346c37cSMatthias Ringwald     }
18320346c37cSMatthias Ringwald }
18330346c37cSMatthias Ringwald 
18340346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
18350346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
18360346c37cSMatthias Ringwald     const uint16_t message_len = 53;
18370346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18380346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
18390346c37cSMatthias Ringwald     // 1..52 setup before
18400346c37cSMatthias Ringwald     log_info("f5 key");
18410346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18420346c37cSMatthias Ringwald     log_info("f5 message for LTK");
18430346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1844d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18450346c37cSMatthias Ringwald }
1846f92edc8eSMatthias Ringwald 
18470346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
18480346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
18490346c37cSMatthias Ringwald }
18500346c37cSMatthias Ringwald 
185131f061fbSMatthias 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){
18526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18566535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18576535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
185831f061fbSMatthias Ringwald }
185931f061fbSMatthias Ringwald 
186031f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
186131f061fbSMatthias Ringwald     const uint16_t message_len = 65;
186231f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1863dc300847SMatthias Ringwald     log_info("f6 key");
1864dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1865dc300847SMatthias Ringwald     log_info("f6 message");
1866dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1867d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1868dc300847SMatthias Ringwald }
1869dc300847SMatthias Ringwald 
1870f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1871f92edc8eSMatthias Ringwald // - U is 256 bits
1872f92edc8eSMatthias Ringwald // - V is 256 bits
1873f92edc8eSMatthias Ringwald // - X is 128 bits
1874f92edc8eSMatthias Ringwald // - Y is 128 bits
1875bd57ffebSMatthias 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){
1876bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1877bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18786535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18796535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18806535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1881f92edc8eSMatthias Ringwald     log_info("g2 key");
1882f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1883f92edc8eSMatthias Ringwald     log_info("g2 message");
18842bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1885d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1886f92edc8eSMatthias Ringwald }
1887f92edc8eSMatthias Ringwald 
1888b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1889f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
189042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1891f92edc8eSMatthias Ringwald         // responder
1892fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1893f92edc8eSMatthias Ringwald     } else {
1894f92edc8eSMatthias Ringwald         // initiator
1895fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1896f92edc8eSMatthias Ringwald     }
1897f92edc8eSMatthias Ringwald }
1898f92edc8eSMatthias Ringwald 
1899945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
19009af0f475SMatthias Ringwald     uint8_t z = 0;
190140c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
19029af0f475SMatthias Ringwald         // some form of passkey
19039af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
19044ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
19059af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
19069af0f475SMatthias Ringwald     }
1907fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
19089af0f475SMatthias Ringwald }
1909688a08f9SMatthias Ringwald 
1910688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1911a680ba6bSMatthias Ringwald     // OOB
1912a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
19134acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
19144acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
19154acf7b7bSMatthias Ringwald         } else {
19164acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
19174acf7b7bSMatthias Ringwald         }
1918a680ba6bSMatthias Ringwald         return;
1919a680ba6bSMatthias Ringwald     }
1920a680ba6bSMatthias Ringwald 
1921688a08f9SMatthias Ringwald     uint8_t z = 0;
192240c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1923688a08f9SMatthias Ringwald         // some form of passkey
1924688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1925688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
19264ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1927688a08f9SMatthias Ringwald     }
1928fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1929688a08f9SMatthias Ringwald }
1930688a08f9SMatthias Ringwald 
19310346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1932505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
19333cf37b8cSMatthias Ringwald 
19343cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
19353cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
19363cf37b8cSMatthias Ringwald         return;
19373cf37b8cSMatthias Ringwald     } else {
19383cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
19393cf37b8cSMatthias Ringwald     }
1940d1a1f6a4SMatthias Ringwald }
19413cf37b8cSMatthias Ringwald 
1942d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1943f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1944f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1945f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1946f3582630SMatthias Ringwald 
1947d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1948d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1949d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1950d1a1f6a4SMatthias Ringwald     // trigger next step
1951d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1952d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1953d1a1f6a4SMatthias Ringwald     }
195470b44dd4SMatthias Ringwald     sm_trigger_run();
1955dc300847SMatthias Ringwald }
1956dc300847SMatthias Ringwald 
1957dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1958dc300847SMatthias Ringwald     // calculate DHKCheck
1959dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1960dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1961dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19626535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19636535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1964dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1965dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1966dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1967dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1968dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1969dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1970dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1971dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
197242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1973dc300847SMatthias Ringwald         // responder
197431f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
197531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1976dc300847SMatthias Ringwald     } else {
1977dc300847SMatthias Ringwald         // initiator
197831f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
197931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1980dc300847SMatthias Ringwald     }
1981dc300847SMatthias Ringwald }
1982dc300847SMatthias Ringwald 
1983019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1984019005a0SMatthias Ringwald     // validate E = f6()
1985019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1986019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1987019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19886535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19896535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1990019005a0SMatthias Ringwald 
1991019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1992019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1993019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1994019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1995019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1996019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1997019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1998019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
199942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
2000019005a0SMatthias Ringwald         // responder
200131f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
200231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
2003019005a0SMatthias Ringwald     } else {
2004019005a0SMatthias Ringwald         // initiator
200531f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
200631f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
2007019005a0SMatthias Ringwald     }
2008019005a0SMatthias Ringwald }
20092bacf595SMatthias Ringwald 
201055c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
20112bacf595SMatthias Ringwald 
20122bacf595SMatthias Ringwald //
20132bacf595SMatthias Ringwald // Link Key Conversion Function h6
20142bacf595SMatthias Ringwald //
201557132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
20162bacf595SMatthias Ringwald // - W is 128 bits
20172bacf595SMatthias Ringwald // - keyID is 32 bits
20182bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
20192bacf595SMatthias Ringwald     const uint16_t message_len = 4;
20202bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
20212bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
20222bacf595SMatthias Ringwald     log_info("h6 key");
20232bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
20242bacf595SMatthias Ringwald     log_info("h6 message");
20252bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
2026d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
20272bacf595SMatthias Ringwald }
202857132f12SMatthias Ringwald //
202957132f12SMatthias Ringwald // Link Key Conversion Function h7
203057132f12SMatthias Ringwald //
203157132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
203257132f12SMatthias Ringwald // - SALT is 128 bits
203357132f12SMatthias Ringwald // - W    is 128 bits
203457132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
203557132f12SMatthias Ringwald 	const uint16_t message_len = 16;
203657132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
203757132f12SMatthias Ringwald 	log_info("h7 key");
203857132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
203957132f12SMatthias Ringwald 	log_info("h7 message");
204057132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
204157132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
204257132f12SMatthias Ringwald }
20432bacf595SMatthias Ringwald 
2044b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
2045b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
2046b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
2047b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
204857132f12SMatthias Ringwald 
2049c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
2050b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
20512bacf595SMatthias Ringwald }
20522bacf595SMatthias Ringwald 
2053e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2054e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2055e0a03c85SMatthias Ringwald }
2056e0a03c85SMatthias Ringwald 
20572bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20582bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20592bacf595SMatthias Ringwald }
20602bacf595SMatthias Ringwald 
2061e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2062e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2063e0a03c85SMatthias Ringwald }
2064e0a03c85SMatthias Ringwald 
2065c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
206657132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
206757132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
206857132f12SMatthias Ringwald }
2069e0a03c85SMatthias Ringwald 
2070e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2071e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2072e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2073e0a03c85SMatthias Ringwald }
2074e0a03c85SMatthias Ringwald 
2075c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2076e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2077e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2078e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2079e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2080e0a03c85SMatthias Ringwald }
2081e0a03c85SMatthias Ringwald 
2082c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2083c18be159SMatthias 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;
2084c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2085c18be159SMatthias Ringwald }
2086c18be159SMatthias Ringwald 
20879af0f475SMatthias Ringwald #endif
20889af0f475SMatthias Ringwald 
208955c62cf5SMatthias Ringwald #endif
209055c62cf5SMatthias Ringwald 
2091613da3deSMatthias Ringwald // key management legacy connections:
2092613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2093613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2094613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2095613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2096613da3deSMatthias Ringwald 
2097613da3deSMatthias Ringwald // key management secure connections:
2098613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2099613da3deSMatthias Ringwald 
210042134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
21015829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
21025829ebe2SMatthias Ringwald     int encryption_key_size;
21035829ebe2SMatthias Ringwald     int authenticated;
21045829ebe2SMatthias Ringwald     int authorized;
21053dc3a67dSMatthias Ringwald     int secure_connection;
21065829ebe2SMatthias Ringwald 
21075829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
21085829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
21093dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
21103dc3a67dSMatthias 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);
21115829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
21125829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
21135829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
21143dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
21155829ebe2SMatthias Ringwald }
211642134bc6SMatthias Ringwald #endif
2117bd57ffebSMatthias Ringwald 
211842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
211959066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
21206535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
212159066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
212259066796SMatthias Ringwald     // re-establish used key encryption size
212359066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
21244ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
212559066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
21264ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
21273dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
21283dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
212959066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
213059066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
213159066796SMatthias Ringwald }
213242134bc6SMatthias Ringwald #endif
213359066796SMatthias Ringwald 
21343deb3ec6SMatthias Ringwald // distributed key generation
2135d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
21363deb3ec6SMatthias Ringwald     switch (dkg_state){
21373deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
21383deb3ec6SMatthias Ringwald             // already busy?
21393deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2140d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
21413deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2142d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2143d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2144d1a1f6a4SMatthias 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);
2145d7f1c72eSMatthias Ringwald                 return true;
21463deb3ec6SMatthias Ringwald             }
21473deb3ec6SMatthias Ringwald             break;
21483deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
21493deb3ec6SMatthias Ringwald             // already busy?
21503deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2151d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
21523deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2153d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2154d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2155d1a1f6a4SMatthias 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);
2156d7f1c72eSMatthias Ringwald                 return true;
21573deb3ec6SMatthias Ringwald             }
21583deb3ec6SMatthias Ringwald             break;
21593deb3ec6SMatthias Ringwald         default:
21603deb3ec6SMatthias Ringwald             break;
21613deb3ec6SMatthias Ringwald     }
2162d7f1c72eSMatthias Ringwald     return false;
2163d7f1c72eSMatthias Ringwald }
21643deb3ec6SMatthias Ringwald 
21653deb3ec6SMatthias Ringwald // random address updates
2166d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21673deb3ec6SMatthias Ringwald     switch (rau_state){
2168fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2169fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21705b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2171d7f1c72eSMatthias Ringwald             return true;
21723deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21733deb3ec6SMatthias Ringwald             // already busy?
21743deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2175d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2176d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2177d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2178d7f1c72eSMatthias Ringwald                 return true;
21793deb3ec6SMatthias Ringwald             }
21803deb3ec6SMatthias Ringwald             break;
21813deb3ec6SMatthias Ringwald         default:
21823deb3ec6SMatthias Ringwald             break;
21833deb3ec6SMatthias Ringwald     }
2184d7f1c72eSMatthias Ringwald     return false;
2185d7f1c72eSMatthias Ringwald }
21863deb3ec6SMatthias Ringwald 
21873deb3ec6SMatthias Ringwald // CSRK Lookup
2188d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2189d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2190d7f1c72eSMatthias Ringwald 
21913deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21923deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21933deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2194665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2195665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21963deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21973deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21983deb3ec6SMatthias Ringwald                 // and start lookup
21993deb3ec6SMatthias 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);
22003deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
22013deb3ec6SMatthias Ringwald                 break;
22023deb3ec6SMatthias Ringwald             }
22033deb3ec6SMatthias Ringwald         }
22043deb3ec6SMatthias Ringwald     }
22053deb3ec6SMatthias Ringwald 
22063deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
22073deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2208665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
22093deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2210665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
22113deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
22123deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
22133deb3ec6SMatthias Ringwald         }
22143deb3ec6SMatthias Ringwald     }
22153deb3ec6SMatthias Ringwald 
2216ca685291SMatthias Ringwald     // -- Continue with device lookup by public or resolvable private address
22173deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2218092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2219adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
22203deb3ec6SMatthias Ringwald             bd_addr_t addr;
22213deb3ec6SMatthias Ringwald             sm_key_t irk;
22223deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
22233deb3ec6SMatthias Ringwald 
2224adf5eaa9SMatthias Ringwald             // skip unused entries
2225adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2226adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2227adf5eaa9SMatthias Ringwald                 continue;
2228adf5eaa9SMatthias Ringwald             }
2229adf5eaa9SMatthias Ringwald 
2230ca685291SMatthias Ringwald             log_info("LE Device Lookup: device %u of %u", sm_address_resolution_test, le_device_db_max_count());
2231ca685291SMatthias Ringwald 
22325df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
2233ca685291SMatthias Ringwald                 log_info("LE Device Lookup: found by { addr_type, address} ");
2234a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
22353deb3ec6SMatthias Ringwald                 break;
22363deb3ec6SMatthias Ringwald             }
22373deb3ec6SMatthias Ringwald 
2238a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2239a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
22403deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
22413deb3ec6SMatthias Ringwald                 continue;
22423deb3ec6SMatthias Ringwald             }
22433deb3ec6SMatthias Ringwald 
22448cc81b50SMatthias Ringwald             // skip AH if no IRK
22458cc81b50SMatthias Ringwald             if (sm_is_null_key(irk)){
22468cc81b50SMatthias Ringwald                 sm_address_resolution_test++;
22478cc81b50SMatthias Ringwald                 continue;
22488cc81b50SMatthias Ringwald             }
22498cc81b50SMatthias Ringwald 
22503deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
22513deb3ec6SMatthias Ringwald 
22523deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
22538314c363SMatthias Ringwald             log_info_key("IRK", irk);
22543deb3ec6SMatthias Ringwald 
22556535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2256d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
2257d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2258d1a1f6a4SMatthias 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);
2259d7f1c72eSMatthias Ringwald             return true;
22603deb3ec6SMatthias Ringwald         }
22613deb3ec6SMatthias Ringwald 
2262092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22633deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22643deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22653deb3ec6SMatthias Ringwald         }
22663deb3ec6SMatthias Ringwald     }
2267d7f1c72eSMatthias Ringwald     return false;
2268d7f1c72eSMatthias Ringwald }
22693deb3ec6SMatthias Ringwald 
2270d7f1c72eSMatthias Ringwald // SC OOB
2271d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2272c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2273c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2274c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2275c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2276c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2277c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2278d7f1c72eSMatthias Ringwald             return true;
2279c59d0c92SMatthias Ringwald         default:
2280c59d0c92SMatthias Ringwald             break;
2281c59d0c92SMatthias Ringwald     }
2282c59d0c92SMatthias Ringwald #endif
2283d7f1c72eSMatthias Ringwald     return false;
2284d7f1c72eSMatthias Ringwald }
2285275aafe8SMatthias Ringwald 
2286687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2287687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2288687a03c8SMatthias Ringwald }
2289687a03c8SMatthias Ringwald 
229041d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2291d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2292d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
229341d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2294e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
229541d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
229641d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
229741d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2298f4935286SMatthias Ringwald 
2299f4935286SMatthias Ringwald             // general
2300f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2301f4935286SMatthias Ringwald                 uint8_t buffer[2];
2302f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2303f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2304f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2305687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2306f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2307f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2308f4935286SMatthias Ringwald                 break;
2309f4935286SMatthias Ringwald             }
2310f4935286SMatthias Ringwald 
231141d32297SMatthias Ringwald             // responder side
231241d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
231341d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
231441d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2315d7f1c72eSMatthias Ringwald                 return true;
23164b8b5afeSMatthias Ringwald 
23174b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
23184b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
23194b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
23204b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2321e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
23224b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
23234b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2324d7f1c72eSMatthias Ringwald                         return true;
23254b8b5afeSMatthias Ringwald                     default:
23264b8b5afeSMatthias Ringwald                         break;
23274b8b5afeSMatthias Ringwald                 }
23284b8b5afeSMatthias Ringwald                 break;
23294b8b5afeSMatthias Ringwald #endif
233041d32297SMatthias Ringwald             default:
233141d32297SMatthias Ringwald                 break;
233241d32297SMatthias Ringwald         }
233341d32297SMatthias Ringwald     }
2334d7f1c72eSMatthias Ringwald     return false;
2335d7f1c72eSMatthias Ringwald }
23363deb3ec6SMatthias Ringwald 
2337d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
23383deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2339d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
23403deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
23417149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2342665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
23433deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
23443deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
23451979f09cSMatthias Ringwald         bool done = true;
23463deb3ec6SMatthias Ringwald         int err;
234742134bc6SMatthias Ringwald         UNUSED(err);
234834b6528fSMatthias Ringwald 
234934b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
235034b6528fSMatthias Ringwald         // assert ec key is ready
2351505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2352178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2353178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
235434b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
235534b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
235634b6528fSMatthias Ringwald             }
235734b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
235834b6528fSMatthias Ringwald                 continue;
235934b6528fSMatthias Ringwald             }
236034b6528fSMatthias Ringwald         }
236134b6528fSMatthias Ringwald #endif
236234b6528fSMatthias Ringwald 
23633deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
236442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23653deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23663deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
236742134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2368549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
236906cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
237087014f74SMatthias Ringwald #endif
237187014f74SMatthias Ringwald #endif
237234c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23735567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
237434c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2375549ad5d2SMatthias Ringwald #endif
2376c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2377c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2378c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2379c18be159SMatthias Ringwald #endif
238087014f74SMatthias Ringwald 				// just lock context
238187014f74SMatthias Ringwald 				break;
23823deb3ec6SMatthias Ringwald             default:
23831979f09cSMatthias Ringwald                 done = false;
23843deb3ec6SMatthias Ringwald                 break;
23853deb3ec6SMatthias Ringwald         }
23863deb3ec6SMatthias Ringwald         if (done){
23877149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23887149bde5SMatthias 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);
23893deb3ec6SMatthias Ringwald         }
23903deb3ec6SMatthias Ringwald     }
2391d7f1c72eSMatthias Ringwald }
2392d7f1c72eSMatthias Ringwald 
2393403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2394403280b9SMatthias Ringwald     int i;
2395403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2396403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2397403280b9SMatthias Ringwald     uint8_t action = 0;
2398403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2399403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2400403280b9SMatthias Ringwald             bool clear_flag = true;
2401403280b9SMatthias Ringwald             switch (i){
2402403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2403403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2404403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2405403280b9SMatthias Ringwald                 default:
2406403280b9SMatthias Ringwald                     break;
2407403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2408403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2409403280b9SMatthias Ringwald                     num_actions--;
2410403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2411403280b9SMatthias Ringwald                     break;
2412403280b9SMatthias Ringwald             }
2413403280b9SMatthias Ringwald             if (clear_flag){
2414403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2415403280b9SMatthias Ringwald             }
2416403280b9SMatthias Ringwald             action = i;
2417403280b9SMatthias Ringwald             break;
2418403280b9SMatthias Ringwald         }
2419403280b9SMatthias Ringwald     }
2420403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2421403280b9SMatthias Ringwald 
2422403280b9SMatthias Ringwald     // send keypress notification
2423403280b9SMatthias Ringwald     uint8_t buffer[2];
2424403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2425403280b9SMatthias Ringwald     buffer[1] = action;
2426687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2427403280b9SMatthias Ringwald 
2428403280b9SMatthias Ringwald     // try
2429384eabd3SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2430403280b9SMatthias Ringwald }
2431403280b9SMatthias Ringwald 
2432403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2433403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2434403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2435403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2436403280b9SMatthias Ringwald         uint8_t buffer[17];
2437403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2438403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2439687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2440403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2441403280b9SMatthias Ringwald         return;
2442403280b9SMatthias Ringwald     }
2443403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2444403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2445403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2446403280b9SMatthias Ringwald         uint8_t buffer[11];
2447403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2448403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2449403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2450687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2451403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2452403280b9SMatthias Ringwald         return;
2453403280b9SMatthias Ringwald     }
2454403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2455403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2456403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2457403280b9SMatthias Ringwald         uint8_t buffer[17];
2458403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2459403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2460687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2461403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2462403280b9SMatthias Ringwald         return;
2463403280b9SMatthias Ringwald     }
2464403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2465403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2466403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2467403280b9SMatthias Ringwald         bd_addr_t local_address;
2468403280b9SMatthias Ringwald         uint8_t buffer[8];
2469403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2470403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2471403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2472403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2473403280b9SMatthias Ringwald                 // public or static random
2474403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2475403280b9SMatthias Ringwald                 break;
2476403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2477403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2478403280b9SMatthias Ringwald                 // fallback to public
2479403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2480403280b9SMatthias Ringwald                 buffer[1] = 0;
2481403280b9SMatthias Ringwald                 break;
2482403280b9SMatthias Ringwald             default:
2483403280b9SMatthias Ringwald                 btstack_assert(false);
2484403280b9SMatthias Ringwald                 break;
2485403280b9SMatthias Ringwald         }
2486403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2487687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2488403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2489403280b9SMatthias Ringwald         return;
2490403280b9SMatthias Ringwald     }
2491403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2492403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2493403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2494403280b9SMatthias Ringwald 
2495403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2496403280b9SMatthias Ringwald         // hack to reproduce test runs
2497403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2498403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2499403280b9SMatthias Ringwald                     }
2500403280b9SMatthias Ringwald 
2501403280b9SMatthias Ringwald                     // store local CSRK
2502403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2503403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2504403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2505403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2506403280b9SMatthias Ringwald                     }
2507403280b9SMatthias Ringwald #endif
2508403280b9SMatthias Ringwald 
2509403280b9SMatthias Ringwald         uint8_t buffer[17];
2510403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2511403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2512687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2513403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2514403280b9SMatthias Ringwald         return;
2515403280b9SMatthias Ringwald     }
2516403280b9SMatthias Ringwald     btstack_assert(false);
2517403280b9SMatthias Ringwald }
2518403280b9SMatthias Ringwald 
2519bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2520bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2521bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2522bbd73538SMatthias Ringwald     // - use secure connections
2523bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2524bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2525bbd73538SMatthias 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;
2526bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2527bbd73538SMatthias Ringwald     // - need identity address / public addr
2528bbd73538SMatthias 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);
2529bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2530bbd73538SMatthias 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)
2531bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2532bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2533bbd73538SMatthias 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.
2534bbd73538SMatthias Ringwald     uint8_t link_key[16];
2535bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2536bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
25377040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2538bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2539bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2540bbd73538SMatthias Ringwald         return false;
2541bbd73538SMatthias Ringwald     }
2542bbd73538SMatthias Ringwald     // get started (all of the above are true)
2543bbd73538SMatthias Ringwald     return true;
2544bbd73538SMatthias Ringwald #else
2545bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2546bbd73538SMatthias Ringwald 	return false;
2547bbd73538SMatthias Ringwald #endif
2548bbd73538SMatthias Ringwald }
2549bbd73538SMatthias Ringwald 
25506f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
25516f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
25526f7422f1SMatthias 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;
25536f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
25546f7422f1SMatthias Ringwald     } else {
25556f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25566f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25576f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25586f7422f1SMatthias Ringwald     }
25596f7422f1SMatthias Ringwald }
25606f7422f1SMatthias Ringwald 
2561af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2562af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2563af7ef9d1SMatthias 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;
2564af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2565af7ef9d1SMatthias Ringwald     } else {
2566af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2567af7ef9d1SMatthias Ringwald     }
2568af7ef9d1SMatthias Ringwald }
2569af7ef9d1SMatthias Ringwald 
2570b919f264SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2571b919f264SMatthias Ringwald static void sm_run_state_sc_send_confirmation(sm_connection_t *connection) {
2572b919f264SMatthias Ringwald     uint8_t buffer[17];
2573b919f264SMatthias Ringwald     buffer[0] = SM_CODE_PAIRING_CONFIRM;
2574b919f264SMatthias Ringwald     reverse_128(setup->sm_local_confirm, &buffer[1]);
2575b919f264SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
2576b919f264SMatthias Ringwald         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2577b919f264SMatthias Ringwald     } else {
2578b919f264SMatthias Ringwald         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2579b919f264SMatthias Ringwald     }
2580b919f264SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2581b919f264SMatthias Ringwald     sm_timeout_reset(connection);
2582b919f264SMatthias Ringwald }
2583b919f264SMatthias Ringwald 
2584b919f264SMatthias Ringwald static void sm_run_state_sc_send_pairing_random(sm_connection_t *connection) {
2585b919f264SMatthias Ringwald     uint8_t buffer[17];
2586b919f264SMatthias Ringwald     buffer[0] = SM_CODE_PAIRING_RANDOM;
2587b919f264SMatthias Ringwald     reverse_128(setup->sm_local_nonce, &buffer[1]);
2588b919f264SMatthias Ringwald     log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
2589b919f264SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
2590b919f264SMatthias Ringwald         log_info("SM_SC_SEND_PAIRING_RANDOM A");
2591b919f264SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
2592b919f264SMatthias Ringwald             // responder
2593b919f264SMatthias Ringwald             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2594b919f264SMatthias Ringwald         } else {
2595b919f264SMatthias Ringwald             // initiator
2596b919f264SMatthias Ringwald             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2597b919f264SMatthias Ringwald         }
2598b919f264SMatthias Ringwald     } else {
2599b919f264SMatthias Ringwald         log_info("SM_SC_SEND_PAIRING_RANDOM B");
2600b919f264SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
2601b919f264SMatthias Ringwald             // responder
2602b919f264SMatthias Ringwald             if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
2603b919f264SMatthias Ringwald                 log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2604b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
2605b919f264SMatthias Ringwald             } else {
2606b919f264SMatthias Ringwald                 log_info("SM_SC_SEND_PAIRING_RANDOM B2");
2607b919f264SMatthias Ringwald                 sm_sc_prepare_dhkey_check(connection);
2608b919f264SMatthias Ringwald             }
2609b919f264SMatthias Ringwald         } else {
2610b919f264SMatthias Ringwald             // initiator
2611b919f264SMatthias Ringwald             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2612b919f264SMatthias Ringwald         }
2613b919f264SMatthias Ringwald     }
2614b919f264SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2615b919f264SMatthias Ringwald     sm_timeout_reset(connection);
2616b919f264SMatthias Ringwald }
2617b919f264SMatthias Ringwald 
2618b919f264SMatthias Ringwald static void sm_run_state_sc_send_dhkey_check_command(sm_connection_t *connection) {
2619b919f264SMatthias Ringwald     uint8_t buffer[17];
2620b919f264SMatthias Ringwald     buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2621b919f264SMatthias Ringwald     reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2622b919f264SMatthias Ringwald 
2623b919f264SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
2624b919f264SMatthias Ringwald         connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2625b919f264SMatthias Ringwald     } else {
2626b919f264SMatthias Ringwald         connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2627b919f264SMatthias Ringwald     }
2628b919f264SMatthias Ringwald 
2629b919f264SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2630b919f264SMatthias Ringwald     sm_timeout_reset(connection);
2631b919f264SMatthias Ringwald }
2632b919f264SMatthias Ringwald 
2633b919f264SMatthias Ringwald static void sm_run_state_sc_send_public_key_command(sm_connection_t *connection) {
2634b919f264SMatthias Ringwald     bool trigger_user_response   = false;
2635b919f264SMatthias Ringwald     bool trigger_start_calculating_local_confirm = false;
2636b919f264SMatthias Ringwald     uint8_t buffer[65];
2637b919f264SMatthias Ringwald     buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
2638b919f264SMatthias Ringwald     //
2639b919f264SMatthias Ringwald     reverse_256(&ec_q[0],  &buffer[1]);
2640b919f264SMatthias Ringwald     reverse_256(&ec_q[32], &buffer[33]);
2641b919f264SMatthias Ringwald 
2642b919f264SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2643b919f264SMatthias Ringwald     if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2644b919f264SMatthias Ringwald             log_info("testing_support: invalidating public key");
2645b919f264SMatthias Ringwald             // flip single bit of public key coordinate
2646b919f264SMatthias Ringwald             buffer[1] ^= 1;
2647b919f264SMatthias Ringwald         }
2648b919f264SMatthias Ringwald #endif
2649b919f264SMatthias Ringwald 
2650b919f264SMatthias Ringwald     // stk generation method
2651b919f264SMatthias Ringwald // passkey entry: notify app to show passkey or to request passkey
2652b919f264SMatthias Ringwald     switch (setup->sm_stk_generation_method){
2653b919f264SMatthias Ringwald         case JUST_WORKS:
2654b919f264SMatthias Ringwald         case NUMERIC_COMPARISON:
2655b919f264SMatthias Ringwald             if (IS_RESPONDER(connection->sm_role)){
2656b919f264SMatthias Ringwald                 // responder
2657b919f264SMatthias Ringwald                 trigger_start_calculating_local_confirm = true;
2658b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
2659b919f264SMatthias Ringwald             } else {
2660b919f264SMatthias Ringwald                 // initiator
2661b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2662b919f264SMatthias Ringwald             }
2663b919f264SMatthias Ringwald             break;
2664b919f264SMatthias Ringwald         case PK_INIT_INPUT:
2665b919f264SMatthias Ringwald         case PK_RESP_INPUT:
2666b919f264SMatthias Ringwald         case PK_BOTH_INPUT:
2667b919f264SMatthias Ringwald             // use random TK for display
2668b919f264SMatthias Ringwald             (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
2669b919f264SMatthias Ringwald             (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
2670b919f264SMatthias Ringwald             setup->sm_passkey_bit = 0;
2671b919f264SMatthias Ringwald 
2672b919f264SMatthias Ringwald             if (IS_RESPONDER(connection->sm_role)){
2673b919f264SMatthias Ringwald                 // responder
2674b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2675b919f264SMatthias Ringwald             } else {
2676b919f264SMatthias Ringwald                 // initiator
2677b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2678b919f264SMatthias Ringwald             }
2679b919f264SMatthias Ringwald             trigger_user_response = true;
2680b919f264SMatthias Ringwald             break;
2681b919f264SMatthias Ringwald         case OOB:
2682b919f264SMatthias Ringwald             if (IS_RESPONDER(connection->sm_role)){
2683b919f264SMatthias Ringwald                 // responder
2684b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2685b919f264SMatthias Ringwald             } else {
2686b919f264SMatthias Ringwald                 // initiator
2687b919f264SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2688b919f264SMatthias Ringwald             }
2689b919f264SMatthias Ringwald             break;
2690b919f264SMatthias Ringwald         default:
2691b919f264SMatthias Ringwald             btstack_assert(false);
2692b919f264SMatthias Ringwald             break;
2693b919f264SMatthias Ringwald     }
2694b919f264SMatthias Ringwald 
2695b919f264SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2696b919f264SMatthias Ringwald     sm_timeout_reset(connection);
2697b919f264SMatthias Ringwald 
2698b919f264SMatthias Ringwald     // trigger user response and calc confirm after sending pdu
2699b919f264SMatthias Ringwald     if (trigger_user_response){
2700b919f264SMatthias Ringwald         sm_trigger_user_response(connection);
2701b919f264SMatthias Ringwald     }
2702b919f264SMatthias Ringwald     if (trigger_start_calculating_local_confirm){
2703b919f264SMatthias Ringwald         sm_sc_start_calculating_local_confirm(connection);
2704b919f264SMatthias Ringwald     }
2705b919f264SMatthias Ringwald }
2706b919f264SMatthias Ringwald #endif
2707b919f264SMatthias Ringwald 
2708de42cac5SMatthias Ringwald static bool sm_run_non_connection_logic(void){
2709de42cac5SMatthias Ringwald     bool done;;
2710de42cac5SMatthias Ringwald 
2711de42cac5SMatthias Ringwald     done = sm_run_dpkg();
2712de42cac5SMatthias Ringwald     if (done) return true;
2713de42cac5SMatthias Ringwald 
2714de42cac5SMatthias Ringwald     done = sm_run_rau();
2715de42cac5SMatthias Ringwald     if (done) return true;
2716de42cac5SMatthias Ringwald 
2717de42cac5SMatthias Ringwald     done = sm_run_csrk();
2718de42cac5SMatthias Ringwald     if (done) return true;
2719de42cac5SMatthias Ringwald 
2720de42cac5SMatthias Ringwald     done = sm_run_oob();
2721de42cac5SMatthias Ringwald     return done;
2722de42cac5SMatthias Ringwald }
2723b919f264SMatthias Ringwald 
2724d7f1c72eSMatthias Ringwald static void sm_run(void){
2725d7f1c72eSMatthias Ringwald 
2726d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2727d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2728d7f1c72eSMatthias Ringwald 
2729d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2730d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2731d7f1c72eSMatthias Ringwald 
2732d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2733d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2734d7f1c72eSMatthias Ringwald 
2735d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2736de42cac5SMatthias Ringwald     bool done = sm_run_non_connection_logic();
2737d7f1c72eSMatthias Ringwald     if (done) return;
2738d7f1c72eSMatthias Ringwald 
2739d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2740d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2741d7f1c72eSMatthias Ringwald 
2742d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2743d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2744d7f1c72eSMatthias Ringwald     if (done) return;
2745d7f1c72eSMatthias Ringwald 
2746d7f1c72eSMatthias Ringwald     //
2747d7f1c72eSMatthias Ringwald     // active connection handling
2748d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2749d7f1c72eSMatthias Ringwald 
2750d7f1c72eSMatthias Ringwald     while (true) {
2751d7f1c72eSMatthias Ringwald 
2752d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2753d7f1c72eSMatthias Ringwald 
2754d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
27553deb3ec6SMatthias Ringwald 
27563deb3ec6SMatthias Ringwald         //
27573deb3ec6SMatthias Ringwald         // active connection handling
27583deb3ec6SMatthias Ringwald         //
27593deb3ec6SMatthias Ringwald 
27603cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
27613cf37b8cSMatthias Ringwald         if (!connection) {
27623cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
27633cf37b8cSMatthias Ringwald             return;
27643cf37b8cSMatthias Ringwald         }
27653cf37b8cSMatthias Ringwald 
27663deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
2767384eabd3SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) {
27687149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
2769384eabd3SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2770b170b20fSMatthias Ringwald             return;
2771b170b20fSMatthias Ringwald         }
27723deb3ec6SMatthias Ringwald 
27733d7fe1e9SMatthias Ringwald         // send keypress notifications
2774dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2775403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2776d7471931SMatthias Ringwald             return;
27773d7fe1e9SMatthias Ringwald         }
27783d7fe1e9SMatthias Ringwald 
2779f7ea4423SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2780234022e5SMatthias Ringwald         // assert that sm cmac engine is ready
2781234022e5SMatthias Ringwald         if (sm_cmac_ready() == false){
2782234022e5SMatthias Ringwald             break;
2783234022e5SMatthias Ringwald         }
2784f7ea4423SMatthias Ringwald #endif
2785234022e5SMatthias Ringwald 
27863deb3ec6SMatthias Ringwald         int key_distribution_flags;
278742134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2788b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2789b6afa23eSMatthias Ringwald         int err;
27909b75de03SMatthias Ringwald         bool have_ltk;
27919b75de03SMatthias Ringwald         uint8_t ltk[16];
2792b6f39a74SMatthias Ringwald #endif
27933deb3ec6SMatthias Ringwald 
27943deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
27953deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
27963deb3ec6SMatthias Ringwald 
2797f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2798aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2799aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2800aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2801aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2802aec94140SMatthias Ringwald                 break;
2803688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2804688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2805688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2806688a08f9SMatthias Ringwald                 break;
2807dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2808dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2809dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2810dc300847SMatthias Ringwald                 break;
2811019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2812019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
28130346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
28140346c37cSMatthias Ringwald                 break;
28150346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
28160346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
28170346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
28180346c37cSMatthias Ringwald                 break;
28190346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
28200346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
28210346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
28220346c37cSMatthias Ringwald                 break;
28230346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
28240346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
28250346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2826019005a0SMatthias Ringwald                 break;
2827bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2828bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2829b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2830bd57ffebSMatthias Ringwald                 break;
2831e0a03c85SMatthias Ringwald #endif
2832e0a03c85SMatthias Ringwald 
283342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
28343deb3ec6SMatthias Ringwald             // initiator side
2835f32b7a88SMatthias Ringwald 
28365567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2837f32b7a88SMatthias Ringwald 				sm_reset_setup();
2838f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2839f32b7a88SMatthias Ringwald 
28403deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
28419c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
28425567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
28433deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2844c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2845c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
28463deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
284749c9e430SMatthias Ringwald 
284849c9e430SMatthias Ringwald                 // notify after sending
284949c9e430SMatthias Ringwald                 sm_reencryption_started(connection);
28503deb3ec6SMatthias Ringwald                 return;
28513deb3ec6SMatthias Ringwald             }
28523deb3ec6SMatthias Ringwald 
2853b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2854b26f445fSMatthias Ringwald 				sm_reset_setup();
2855b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2856b26f445fSMatthias Ringwald 
28571ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
28583deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2859687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
28603deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
286149c9e430SMatthias Ringwald 
286249c9e430SMatthias Ringwald                 // notify after sending
286349c9e430SMatthias Ringwald                 sm_pairing_started(connection);
28643deb3ec6SMatthias Ringwald                 break;
286542134bc6SMatthias Ringwald #endif
28663deb3ec6SMatthias Ringwald 
286727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2868b919f264SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND:
2869b919f264SMatthias Ringwald                 sm_run_state_sc_send_public_key_command(connection);
287045a61d50SMatthias Ringwald                 break;
2871b919f264SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION:
2872b919f264SMatthias Ringwald                 sm_run_state_sc_send_confirmation(connection);
287345a61d50SMatthias Ringwald                 break;
2874b919f264SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM:
2875b919f264SMatthias Ringwald                 sm_run_state_sc_send_pairing_random(connection);
287645a61d50SMatthias Ringwald                 break;
2877b919f264SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND:
2878b919f264SMatthias Ringwald                 sm_run_state_sc_send_dhkey_check_command(connection);
28797bbeb3adSMilanka Ringwald                 break;
2880e53be891SMatthias Ringwald #endif
288142134bc6SMatthias Ringwald 
288242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2883dd12a62bSMatthias Ringwald 
288487014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
288587014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
288687014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2887687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2888c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
288987014f74SMatthias Ringwald 				break;
289087014f74SMatthias Ringwald 			}
289187014f74SMatthias Ringwald 
289238196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
289338196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
289438196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
289538196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
289638196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
289738196718SMatthias Ringwald 						// start using context by loading security info
289838196718SMatthias Ringwald 						sm_reset_setup();
289938196718SMatthias Ringwald 						sm_load_security_info(connection);
290038196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
290138196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
290238196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
290342646f38SMatthias Ringwald                             sm_reencryption_started(connection);
290438196718SMatthias Ringwald                             sm_trigger_run();
290538196718SMatthias Ringwald 							break;
290638196718SMatthias Ringwald 						}
290738196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
290838196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
290938196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
291038196718SMatthias Ringwald 						return;
291138196718SMatthias Ringwald 					default:
291238196718SMatthias Ringwald 						// just wait until IRK lookup is completed
291338196718SMatthias Ringwald 						break;
291438196718SMatthias Ringwald 				}
291538196718SMatthias Ringwald 				break;
291638196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
291738196718SMatthias Ringwald 
2918b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2919b6afa23eSMatthias Ringwald                 sm_reset_setup();
29209b75de03SMatthias Ringwald 
29219b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
29229b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
29239b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
29249b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
29259b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
29269b75de03SMatthias Ringwald                         if (have_ltk){
29279b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
292819a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
29299b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
29309b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
29319b75de03SMatthias Ringwald                         }
29329b75de03SMatthias Ringwald                         break;
29339b75de03SMatthias Ringwald                     default:
29349b75de03SMatthias Ringwald                         break;
29359b75de03SMatthias Ringwald                 }
29369b75de03SMatthias Ringwald 
2937b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
293839543d07SMatthias Ringwald 
2939b6afa23eSMatthias Ringwald 				// recover pairing request
2940b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2941b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2942b6afa23eSMatthias Ringwald 
2943b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2944b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2945b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2946b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2947b6afa23eSMatthias Ringwald                     }
2948b6afa23eSMatthias Ringwald #endif
29499305033eSMatthias Ringwald 				if (err != 0){
295049c9e430SMatthias Ringwald                     // emit pairing started/failed sequence
295149c9e430SMatthias Ringwald                     sm_pairing_started(connection);
2952f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2953b6afa23eSMatthias Ringwald 					sm_trigger_run();
2954b6afa23eSMatthias Ringwald 					break;
2955b6afa23eSMatthias Ringwald 				}
2956b6afa23eSMatthias Ringwald 
2957b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2958b6afa23eSMatthias Ringwald 
2959b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2960b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2961b6afa23eSMatthias 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);
2962b6afa23eSMatthias Ringwald 					break;
2963b6afa23eSMatthias Ringwald 				}
2964b6afa23eSMatthias Ringwald 
2965b6afa23eSMatthias Ringwald 				/* fall through */
2966b6afa23eSMatthias Ringwald 
29673deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29681ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2969f55bd529SMatthias Ringwald 
2970f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29713deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29721ad129beSMatthias Ringwald 
2973f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2974f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2975f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2976f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2977f55bd529SMatthias Ringwald                 }
2978f55bd529SMatthias Ringwald #endif
2979f55bd529SMatthias Ringwald                 // setup in response
2980f55bd529SMatthias 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);
2981f55bd529SMatthias 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);
2982f55bd529SMatthias Ringwald 
2983f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29849a90d41aSMatthias Ringwald                 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres), sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres));
2985f55bd529SMatthias Ringwald 
298627c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2987c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29880b8af2a5SMatthias Ringwald                 } else {
29890b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
299027c32905SMatthias Ringwald                 }
29910b8af2a5SMatthias Ringwald 
2992687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29933deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
299449c9e430SMatthias Ringwald 
299549c9e430SMatthias Ringwald                 // notify after sending
299649c9e430SMatthias Ringwald                 sm_pairing_started(connection);
299749c9e430SMatthias Ringwald 
2998446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2999c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
30003deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
3001446a8c36SMatthias Ringwald                 }
30023deb3ec6SMatthias Ringwald                 return;
300342134bc6SMatthias Ringwald #endif
30043deb3ec6SMatthias Ringwald 
30053deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
30063deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30073deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
30089c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
300942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30103deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
30113deb3ec6SMatthias Ringwald                 } else {
30123deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
30133deb3ec6SMatthias Ringwald                 }
3014687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30153deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30163deb3ec6SMatthias Ringwald                 break;
30173deb3ec6SMatthias Ringwald             }
30183deb3ec6SMatthias Ringwald 
3019d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
30203deb3ec6SMatthias Ringwald                 // already busy?
30213deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3022d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
3023d1a1f6a4SMatthias 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);
3024d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
3025d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3026f3582630SMatthias 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);
30273deb3ec6SMatthias Ringwald                 break;
30283deb3ec6SMatthias Ringwald 
30293deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
30303deb3ec6SMatthias Ringwald                 // already busy?
30313deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30323deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
3033d1a1f6a4SMatthias 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);
3034d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
3035d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3036f3582630SMatthias 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);
30373deb3ec6SMatthias Ringwald                 break;
3038d1a1f6a4SMatthias Ringwald 
30393deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
30403deb3ec6SMatthias Ringwald                 // already busy?
30413deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30423deb3ec6SMatthias Ringwald                 // calculate STK
304342134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
3044d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
30453deb3ec6SMatthias Ringwald                 } else {
3046d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
30473deb3ec6SMatthias Ringwald                 }
3048d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
3049d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3050f3582630SMatthias 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);
30513deb3ec6SMatthias Ringwald                 break;
3052d1a1f6a4SMatthias Ringwald 
30533deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
30543deb3ec6SMatthias Ringwald                 // already busy?
30553deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30563deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
30579ad0dd7cSMatthias Ringwald 
30589ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
30599ad0dd7cSMatthias Ringwald                 // r' = padding || r
30609ad0dd7cSMatthias Ringwald                 // r - 64 bit value
30619ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30626535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
30639ad0dd7cSMatthias Ringwald 
30643deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3065d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
3066d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3067f3582630SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_dhk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_ph3_y, (void *)(uintptr_t) connection->sm_handle);
3068d1a1f6a4SMatthias Ringwald                 break;
3069d1a1f6a4SMatthias Ringwald 
30703deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30713deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30723deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30739c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
307442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30753deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30763deb3ec6SMatthias Ringwald                 } else {
30773deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30783deb3ec6SMatthias Ringwald                 }
3079687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30803deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30813deb3ec6SMatthias Ringwald                 return;
30823deb3ec6SMatthias Ringwald             }
308342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30843deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
3085916ea5b2SMatthias Ringwald                 // cache key before using
3086916ea5b2SMatthias Ringwald                 sm_cache_ltk(connection, setup->sm_ltk);
30873deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30889c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30893deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30903deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30913deb3ec6SMatthias Ringwald                 return;
30923deb3ec6SMatthias Ringwald             }
3093d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3094b96d60a6SMatthias Ringwald                 // allow to override LTK
3095b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3096b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3097b96d60a6SMatthias Ringwald                 }
3098916ea5b2SMatthias Ringwald                 // cache key before using
3099916ea5b2SMatthias Ringwald                 sm_cache_ltk(connection, setup->sm_ltk);
31003deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
31019c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
31025567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
31033deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
31043deb3ec6SMatthias Ringwald                 return;
31053deb3ec6SMatthias Ringwald             }
3106dd12a62bSMatthias Ringwald 
3107dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
31083deb3ec6SMatthias Ringwald                 // already busy?
31093deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
31103deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3111c61cfe5aSMatthias Ringwald 
3112dd12a62bSMatthias Ringwald 				sm_reset_setup();
3113dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3114dd12a62bSMatthias Ringwald 
311542646f38SMatthias Ringwald 				sm_reencryption_started(connection);
311642646f38SMatthias Ringwald 
3117c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3118c61cfe5aSMatthias Ringwald                 // r' = padding || r
3119c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3120c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
31216535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3122c61cfe5aSMatthias Ringwald 
31233deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3124d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3125d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3126f3582630SMatthias 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);
31273deb3ec6SMatthias Ringwald                 return;
312842134bc6SMatthias Ringwald #endif
312942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
313042134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
313142134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
313242134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
313342134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
313442134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
313542134bc6SMatthias Ringwald                 return;
313642134bc6SMatthias Ringwald             }
313742134bc6SMatthias Ringwald #endif
31383deb3ec6SMatthias Ringwald 
31393deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3140e94757aeSMatthias Ringwald                 // send next key
3141403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3142403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
3143e94757aeSMatthias Ringwald                 }
3144e94757aeSMatthias Ringwald 
3145e94757aeSMatthias Ringwald                 // more to send?
3146e94757aeSMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
31473deb3ec6SMatthias Ringwald                     return;
31483deb3ec6SMatthias Ringwald                 }
31493deb3ec6SMatthias Ringwald 
31503deb3ec6SMatthias Ringwald                 // keys are sent
315142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
31523deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
315361d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
31543deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3155f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3156f5020412SMatthias Ringwald                         // start CTKD right away
3157f5020412SMatthias Ringwald                         continue;
31583deb3ec6SMatthias Ringwald                     } else {
31593deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
31603deb3ec6SMatthias Ringwald                     }
31613deb3ec6SMatthias Ringwald                 } else {
31621dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
31633deb3ec6SMatthias Ringwald                 }
31643deb3ec6SMatthias Ringwald                 break;
31653deb3ec6SMatthias Ringwald 
3166c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3167c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3168c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3169c18be159SMatthias Ringwald                 sm_reset_setup();
3170c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3171c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3172c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3173c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3174c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3175c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3176c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3177c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3178c18be159SMatthias Ringwald 
3179c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3180c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3181c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3182c18be159SMatthias Ringwald                 // Plus signing key if supported
3183c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3184c18be159SMatthias Ringwald #endif
3185c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3186c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3187c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3188c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3189c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3190c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3191c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3192c18be159SMatthias Ringwald 
3193c18be159SMatthias Ringwald                 // set state and send pairing response
3194c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3195c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3196c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3197c18be159SMatthias Ringwald                 break;
3198c18be159SMatthias Ringwald 
3199c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3200c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3201c18be159SMatthias Ringwald                 sm_reset_setup();
3202c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3203c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3204c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3205c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3206c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3207c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3208c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3209c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3210c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3211c18be159SMatthias Ringwald 
3212c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3213c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3214c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3215c18be159SMatthias Ringwald                 // Plus signing key if supported
3216c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3217c18be159SMatthias Ringwald #endif
3218c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3219c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3220c18be159SMatthias Ringwald 
3221c18be159SMatthias Ringwald                 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use:
3222c18be159SMatthias Ringwald                 // - the IO Capability field,
3223c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3224c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3225c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3226c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3227c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3228c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3229c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3230c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3231c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3232c18be159SMatthias Ringwald 
3233c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3234c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3235c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3236c18be159SMatthias Ringwald 
3237c18be159SMatthias Ringwald                 // set state and send pairing response
3238c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3239c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3240c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3241c18be159SMatthias Ringwald                 break;
3242c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3243c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3244c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3245c18be159SMatthias Ringwald                     return;
3246c18be159SMatthias Ringwald                 }
3247c18be159SMatthias Ringwald                 // keys are sent
3248c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3249c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
325061d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3251c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3252c18be159SMatthias Ringwald                         break;
3253c18be159SMatthias Ringwald                     }
3254c18be159SMatthias Ringwald                 }
3255c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3256c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3257c18be159SMatthias Ringwald                 continue;
3258c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3259c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3260c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3261c18be159SMatthias Ringwald                 break;
3262c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3263c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3264c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3265c18be159SMatthias Ringwald                 break;
3266c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3267c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3268c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3269c18be159SMatthias Ringwald                 break;
3270c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3271c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3272c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3273c18be159SMatthias Ringwald                 break;
3274c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3275c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3276c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3277c18be159SMatthias Ringwald                 break;
3278c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3279c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3280c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3281c18be159SMatthias Ringwald                 break;
3282c18be159SMatthias Ringwald #endif
3283c18be159SMatthias Ringwald 
32843deb3ec6SMatthias Ringwald             default:
32853deb3ec6SMatthias Ringwald                 break;
32863deb3ec6SMatthias Ringwald         }
32873deb3ec6SMatthias Ringwald 
32883deb3ec6SMatthias Ringwald         // check again if active connection was released
32897149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32903deb3ec6SMatthias Ringwald     }
32913deb3ec6SMatthias Ringwald }
32923deb3ec6SMatthias Ringwald 
3293d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3294d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3295f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
329604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329704678764SMatthias Ringwald 
3298f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3299f3582630SMatthias Ringwald     if (connection == NULL) return;
3300f3582630SMatthias Ringwald 
3301d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
330204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3303f3582630SMatthias 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);
3304d1a1f6a4SMatthias Ringwald }
33053deb3ec6SMatthias Ringwald 
3306d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3307f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
330804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
330904678764SMatthias Ringwald 
3310f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3311f3582630SMatthias Ringwald     if (connection == NULL) return;
3312f3582630SMatthias Ringwald 
33138314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
33143deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
331570b44dd4SMatthias Ringwald     sm_trigger_run();
3316d1a1f6a4SMatthias Ringwald }
3317d1a1f6a4SMatthias Ringwald 
3318d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3319d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3320f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
332104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
332204678764SMatthias Ringwald 
3323f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3324f3582630SMatthias Ringwald     if (connection == NULL) return;
3325f3582630SMatthias Ringwald 
3326d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
332704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3328f3582630SMatthias 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);
3329d1a1f6a4SMatthias Ringwald }
3330d1a1f6a4SMatthias Ringwald 
3331d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3332f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
333404678764SMatthias Ringwald 
3335f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3336f3582630SMatthias Ringwald     if (connection == NULL) return;
3337f3582630SMatthias Ringwald 
3338d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3339d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3340f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
334170b44dd4SMatthias Ringwald         sm_trigger_run();
33423deb3ec6SMatthias Ringwald         return;
33433deb3ec6SMatthias Ringwald     }
334442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33453deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
334670b44dd4SMatthias Ringwald         sm_trigger_run();
33473deb3ec6SMatthias Ringwald     } else {
3348d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3349d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3350f3582630SMatthias 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);
33513deb3ec6SMatthias Ringwald     }
33523deb3ec6SMatthias Ringwald }
3353d1a1f6a4SMatthias Ringwald 
3354d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
335504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3356f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
335704678764SMatthias Ringwald 
3358f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3359f3582630SMatthias Ringwald     if (connection == NULL) return;
3360f3582630SMatthias Ringwald 
33613deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33628314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
336342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33643deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
33653deb3ec6SMatthias Ringwald     } else {
33663deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
33673deb3ec6SMatthias Ringwald     }
336870b44dd4SMatthias Ringwald     sm_trigger_run();
3369d1a1f6a4SMatthias Ringwald }
3370d1a1f6a4SMatthias Ringwald 
3371d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3372d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3373f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
337404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
337504678764SMatthias Ringwald 
3376f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3377f3582630SMatthias Ringwald     if (connection == NULL) return;
3378f3582630SMatthias Ringwald 
3379d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33803deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33813deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33823deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33833deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33843deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33853deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3386d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
338704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3388f3582630SMatthias 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);
33893deb3ec6SMatthias Ringwald }
3390d1a1f6a4SMatthias Ringwald 
33912a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3392d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3393d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
339404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3395f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
339604678764SMatthias Ringwald 
3397f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3398f3582630SMatthias Ringwald     if (connection == NULL) return;
3399f3582630SMatthias Ringwald 
3400d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
34013deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
34023deb3ec6SMatthias Ringwald 
34033deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
34043deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
34053deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
34063deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
34073deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3408d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
340904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3410f3582630SMatthias 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);
34113deb3ec6SMatthias Ringwald }
34122a526f21SMatthias Ringwald #endif
3413d1a1f6a4SMatthias Ringwald 
3414d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3415d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3416f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
341704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341804678764SMatthias Ringwald 
3419f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3420f3582630SMatthias Ringwald     if (connection == NULL) return;
3421f3582630SMatthias Ringwald 
34228314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
34233deb3ec6SMatthias Ringwald     // calc CSRK next
3424d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
342504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3426f3582630SMatthias 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);
3427d1a1f6a4SMatthias Ringwald }
3428d1a1f6a4SMatthias Ringwald 
3429d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3430f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
343104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
343204678764SMatthias Ringwald 
3433f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3434f3582630SMatthias Ringwald     if (connection == NULL) return;
3435f3582630SMatthias Ringwald 
3436d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
34378314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
34383deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
34393deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
34403deb3ec6SMatthias Ringwald     } else {
34413deb3ec6SMatthias Ringwald         // no keys to send, just continue
344242134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
344361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3444c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3445c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3446c5a72e35SMatthias Ringwald             } else {
34473deb3ec6SMatthias Ringwald                 // slave -> receive master keys
34483deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3449c5a72e35SMatthias Ringwald             }
34503deb3ec6SMatthias Ringwald         } else {
3451af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
34523deb3ec6SMatthias Ringwald         }
34532bacf595SMatthias Ringwald     }
345470b44dd4SMatthias Ringwald     sm_trigger_run();
3455d1a1f6a4SMatthias Ringwald }
3456d1a1f6a4SMatthias Ringwald 
345742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3458d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3459f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
346004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
346104678764SMatthias Ringwald 
3462f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3463f3582630SMatthias Ringwald     if (connection == NULL) return;
3464f3582630SMatthias Ringwald 
34653deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
34668314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3467d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
346870b44dd4SMatthias Ringwald     sm_trigger_run();
3469d1a1f6a4SMatthias Ringwald }
3470d1a1f6a4SMatthias Ringwald #endif
3471d1a1f6a4SMatthias Ringwald 
3472d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3473d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3474d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
347504678764SMatthias Ringwald 
3476d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3477d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3478d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3479d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3480a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
348170b44dd4SMatthias Ringwald         sm_trigger_run();
34823deb3ec6SMatthias Ringwald         return;
34833deb3ec6SMatthias Ringwald     }
3484d1a1f6a4SMatthias Ringwald     // no match, try next
3485d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
348670b44dd4SMatthias Ringwald     sm_trigger_run();
34873deb3ec6SMatthias Ringwald }
34883deb3ec6SMatthias Ringwald 
3489d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3490d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3491d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
349204678764SMatthias Ringwald 
3493d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3494d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
349570b44dd4SMatthias Ringwald     sm_trigger_run();
34967df18c15SMatthias Ringwald }
3497d1a1f6a4SMatthias Ringwald 
3498d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3499d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3500d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
350104678764SMatthias Ringwald 
3502d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3503d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
350470b44dd4SMatthias Ringwald     sm_trigger_run();
35057df18c15SMatthias Ringwald }
3506d1a1f6a4SMatthias Ringwald 
3507d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3508d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3509d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
351004678764SMatthias Ringwald 
35116535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3512e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3513e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3514e91ddb40SMatthias Ringwald 
351570b44dd4SMatthias Ringwald     sm_trigger_run();
351651fa0b28SMatthias Ringwald }
35177df18c15SMatthias Ringwald 
3518d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3519d1a1f6a4SMatthias Ringwald     UNUSED(arg);
35203deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
35213deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
35223deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
35233deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
35243deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
35254ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35264ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
35273deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
35283deb3ec6SMatthias Ringwald             break;
35293deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
35303deb3ec6SMatthias Ringwald         default:
35313deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
35324ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35332954e6c6SMatthias Ringwald             rau_state = RAU_IDLE;
3534e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
35353deb3ec6SMatthias Ringwald             break;
35363deb3ec6SMatthias Ringwald     }
353770b44dd4SMatthias Ringwald     sm_trigger_run();
35383deb3ec6SMatthias Ringwald }
35393deb3ec6SMatthias Ringwald 
3540c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
35416ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3542f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3543f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3544f3582630SMatthias Ringwald     if (connection == NULL) return;
3545c59d0c92SMatthias Ringwald 
354665a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
354770b44dd4SMatthias Ringwald     sm_trigger_run();
354865a9a04eSMatthias Ringwald }
3549d1a1f6a4SMatthias Ringwald 
35506ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
35516ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
35526ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
35536ca80073SMatthias Ringwald     if (connection == NULL) return;
35546ca80073SMatthias Ringwald 
3555b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
355670b44dd4SMatthias Ringwald     sm_trigger_run();
3557d1a1f6a4SMatthias Ringwald }
3558f1c1783eSMatthias Ringwald #endif
3559f1c1783eSMatthias Ringwald 
3560d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3561f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3562f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3563f3582630SMatthias Ringwald     if (connection == NULL) return;
3564f3582630SMatthias Ringwald 
3565d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
356670b44dd4SMatthias Ringwald     sm_trigger_run();
3567d1a1f6a4SMatthias Ringwald }
3568d1a1f6a4SMatthias Ringwald 
3569d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3570f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3571f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3572f3582630SMatthias Ringwald     if (connection == NULL) return;
3573f3582630SMatthias Ringwald 
3574caf15bf3SMatthias Ringwald     sm_reset_tk();
3575caf15bf3SMatthias Ringwald     uint32_t tk;
35765ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
35773deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3578d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
35793deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35804ea43905SMatthias Ringwald         if (tk >= 999999u){
35814ea43905SMatthias Ringwald             tk = tk - 999999u;
35823deb3ec6SMatthias Ringwald         }
3583caf15bf3SMatthias Ringwald     } else {
3584caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35854b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3586caf15bf3SMatthias Ringwald     }
3587f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
358842134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35893deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35903deb3ec6SMatthias Ringwald     } else {
3591b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3592b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3593b41539d5SMatthias Ringwald         } else {
35943deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35953deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35963deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35973deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3598f3582630SMatthias 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);
35993deb3ec6SMatthias Ringwald             }
36003deb3ec6SMatthias Ringwald         }
3601b41539d5SMatthias Ringwald     }
360270b44dd4SMatthias Ringwald     sm_trigger_run();
36033deb3ec6SMatthias Ringwald }
3604d1a1f6a4SMatthias Ringwald 
3605d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3606f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3607f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3608f3582630SMatthias Ringwald     if (connection == NULL) return;
3609f3582630SMatthias Ringwald 
3610d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3611d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3612d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3613d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
361470b44dd4SMatthias Ringwald     sm_trigger_run();
3615d1a1f6a4SMatthias Ringwald }
3616d1a1f6a4SMatthias Ringwald 
3617d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3618f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3619f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3620f3582630SMatthias Ringwald     if (connection == NULL) return;
3621f3582630SMatthias Ringwald 
3622d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
36233deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
36244ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
36253deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
36264ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
36278b3ffec5SMatthias 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);
36283deb3ec6SMatthias Ringwald }
3629899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3630899e6e02SMatthias Ringwald     // warn about default ER/IR
36311979f09cSMatthias Ringwald     bool warning = false;
3632899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
36331979f09cSMatthias Ringwald         warning = true;
3634899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3635899e6e02SMatthias Ringwald     }
3636899e6e02SMatthias Ringwald     if (sm_er_is_default()){
36371979f09cSMatthias Ringwald         warning = true;
3638899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3639899e6e02SMatthias Ringwald     }
364021045273SMatthias Ringwald     if (warning) {
3641899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3642899e6e02SMatthias Ringwald     }
364321045273SMatthias Ringwald }
3644899e6e02SMatthias Ringwald 
3645899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
36461979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36479305033eSMatthias Ringwald     if (arg != NULL){
3648899e6e02SMatthias Ringwald         // key generated, store in tlv
36494ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3650899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3651e0d13a19SMilanka Ringwald         UNUSED(status);
3652899e6e02SMatthias Ringwald     }
3653899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
36548d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3655841468bbSMatthias Ringwald 
3656841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3657841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3658841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3659841468bbSMatthias Ringwald     }
3660841468bbSMatthias Ringwald 
366170b44dd4SMatthias Ringwald     sm_trigger_run();
3662899e6e02SMatthias Ringwald }
3663899e6e02SMatthias Ringwald 
3664899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
36651979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36669305033eSMatthias Ringwald     if (arg != 0){
3667899e6e02SMatthias Ringwald         // key generated, store in tlv
36684ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3669899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3670e0d13a19SMilanka Ringwald         UNUSED(status);
3671899e6e02SMatthias Ringwald     }
3672899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3673899e6e02SMatthias Ringwald 
3674899e6e02SMatthias Ringwald     // try load ir
36754ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3676899e6e02SMatthias Ringwald     if (key_size == 16){
3677899e6e02SMatthias Ringwald         // ok, let's continue
3678899e6e02SMatthias Ringwald         log_info("IR from TLV");
3679899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3680899e6e02SMatthias Ringwald     } else {
3681899e6e02SMatthias Ringwald         // invalid, generate new random one
36821979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3683899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3684899e6e02SMatthias Ringwald     }
3685899e6e02SMatthias Ringwald }
36863deb3ec6SMatthias Ringwald 
3687f664b5e8SMatthias Ringwald static void sm_connection_init(sm_connection_t * sm_conn, hci_con_handle_t con_handle, uint8_t role, uint8_t addr_type, bd_addr_t address){
3688f664b5e8SMatthias Ringwald 
3689f664b5e8SMatthias Ringwald     // connection info
3690f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3691f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3692f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3693f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3694f664b5e8SMatthias Ringwald 
3695f664b5e8SMatthias Ringwald     // security properties
3696f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3697f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3698f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3699f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3700f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3701f664b5e8SMatthias Ringwald 
3702f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3703f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3704f664b5e8SMatthias Ringwald 
3705f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3706f664b5e8SMatthias Ringwald }
3707f664b5e8SMatthias Ringwald 
3708d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
37093deb3ec6SMatthias Ringwald 
3710cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3711cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
37129ec2630cSMatthias Ringwald 
37133deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3714711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3715fbe050beSMatthias Ringwald     uint8_t           status;
3716f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3717f664b5e8SMatthias Ringwald 
37183deb3ec6SMatthias Ringwald     switch (packet_type) {
37193deb3ec6SMatthias Ringwald 
37203deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
37210e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
37223deb3ec6SMatthias Ringwald 
37233deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
3724745015f6SMatthias Ringwald                     switch (btstack_event_state_get_state(packet)){
3725745015f6SMatthias Ringwald                         case HCI_STATE_WORKING:
37263deb3ec6SMatthias Ringwald                             log_info("HCI Working!");
3727899e6e02SMatthias Ringwald                             // setup IR/ER with TLV
3728899e6e02SMatthias Ringwald                             btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
37299305033eSMatthias Ringwald                             if (sm_tlv_impl != NULL){
37304ea43905SMatthias Ringwald                                 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3731899e6e02SMatthias Ringwald                                 if (key_size == 16){
3732899e6e02SMatthias Ringwald                                     // ok, let's continue
3733899e6e02SMatthias Ringwald                                     log_info("ER from TLV");
3734899e6e02SMatthias Ringwald                                     sm_handle_random_result_er( NULL );
3735899e6e02SMatthias Ringwald                                 } else {
3736899e6e02SMatthias Ringwald                                     // invalid, generate random one
37371979f09cSMatthias Ringwald                                     sm_persistent_keys_random_active = true;
3738899e6e02SMatthias Ringwald                                     btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3739899e6e02SMatthias Ringwald                                 }
3740899e6e02SMatthias Ringwald                             } else {
3741899e6e02SMatthias Ringwald                                 sm_validate_er_ir();
37428d9b6072SMatthias Ringwald                                 dkg_state = DKG_CALC_IRK;
3743841468bbSMatthias Ringwald 
3744841468bbSMatthias Ringwald                                 if (test_use_fixed_local_irk){
3745841468bbSMatthias Ringwald                                     log_info_key("IRK", sm_persistent_irk);
3746841468bbSMatthias Ringwald                                     dkg_state = DKG_CALC_DHK;
3747841468bbSMatthias Ringwald                                 }
3748899e6e02SMatthias Ringwald                             }
37491bf086daSMatthias Ringwald 
375015211b85SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
375115211b85SMatthias Ringwald                             // trigger ECC key generation
375215211b85SMatthias Ringwald                             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
375315211b85SMatthias Ringwald                                 sm_ec_generate_new_key();
375415211b85SMatthias Ringwald                             }
375515211b85SMatthias Ringwald #endif
375615211b85SMatthias Ringwald 
37571bf086daSMatthias Ringwald                             // restart random address updates after power cycle
37584a688bd1SMatthias Ringwald                             if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){
37594a688bd1SMatthias Ringwald                                 gap_random_address_set(sm_random_address);
37604a688bd1SMatthias Ringwald                             } else {
37611bf086daSMatthias Ringwald                                 gap_random_address_set_mode(gap_random_adress_type);
37624a688bd1SMatthias Ringwald                             }
3763745015f6SMatthias Ringwald                             break;
3764745015f6SMatthias Ringwald 
3765745015f6SMatthias Ringwald                         case HCI_STATE_OFF:
37667f775357SMatthias Ringwald                         case HCI_STATE_HALTING:
3767cbdd51cfSMatthias Ringwald                             log_info("SM: reset state");
3768745015f6SMatthias Ringwald                             // stop random address update
3769745015f6SMatthias Ringwald                             gap_random_address_update_stop();
3770cbdd51cfSMatthias Ringwald                             // reset state
3771cbdd51cfSMatthias Ringwald                             sm_state_reset();
3772745015f6SMatthias Ringwald                             break;
3773745015f6SMatthias Ringwald 
3774745015f6SMatthias Ringwald                         default:
3775745015f6SMatthias Ringwald                             break;
37763deb3ec6SMatthias Ringwald                     }
37773deb3ec6SMatthias Ringwald 					break;
3778c18be159SMatthias Ringwald 
37792d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
37802d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
37812d095694SMatthias Ringwald 			        // ignore if connection failed
37822d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
37833deb3ec6SMatthias Ringwald 
37842d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
37852d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
37862d095694SMatthias Ringwald 			        if (!sm_conn) break;
37872d095694SMatthias Ringwald 
37882d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
37892d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
37902d095694SMatthias Ringwald                                        con_handle,
37912d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3792f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
37932d095694SMatthias Ringwald                                        addr);
37942d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
37952d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
37962d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
37972d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3798c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
37992d095694SMatthias Ringwald 			        break;
38002d095694SMatthias Ringwald #endif
3801c18be159SMatthias Ringwald 
3802c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3803c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3804c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3805c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3806c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3807c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3808c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3809c18be159SMatthias Ringwald 			        break;
3810c18be159SMatthias Ringwald #endif
3811c18be159SMatthias Ringwald 
38123deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
38133deb3ec6SMatthias Ringwald                     switch (packet[2]) {
38143deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3815f664b5e8SMatthias Ringwald                             // ignore if connection failed
3816f664b5e8SMatthias Ringwald                             if (packet[3]) return;
38173deb3ec6SMatthias Ringwald 
3818711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3819711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38203deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38213deb3ec6SMatthias Ringwald 
3822f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3823f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3824f664b5e8SMatthias Ringwald                                                con_handle,
3825f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3826f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3827f664b5e8SMatthias Ringwald                                                addr);
3828687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3829f664b5e8SMatthias Ringwald 
3830f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3831b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3832b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3833ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3834ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3835f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3836b892db1cSMatthias Ringwald                             }
3837b892db1cSMatthias Ringwald #endif
3838b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3839b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3840ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3841ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
38423deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38433deb3ec6SMatthias Ringwald                             }
3844b892db1cSMatthias Ringwald #endif
38453deb3ec6SMatthias Ringwald                             break;
38463deb3ec6SMatthias Ringwald 
38473deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3848711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3849711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38503deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38513deb3ec6SMatthias Ringwald 
38523deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
38533deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
38543deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
38553deb3ec6SMatthias Ringwald                                 break;
38563deb3ec6SMatthias Ringwald                             }
3857c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3858778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3859778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3860e53be891SMatthias Ringwald                                 break;
3861e53be891SMatthias Ringwald                             }
38623deb3ec6SMatthias Ringwald 
38633deb3ec6SMatthias Ringwald                             // store rand and ediv
38649c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3865f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3866549ad5d2SMatthias Ringwald 
3867549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3868549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
38694ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
38706c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
387106cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3872549ad5d2SMatthias Ringwald                                     break;
3873549ad5d2SMatthias Ringwald                                 }
38746c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
38756c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
38766c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
38776c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
38786c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
38796c39055aSMatthias Ringwald                                         break;
38806c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
38816c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
38826c39055aSMatthias Ringwald                                         break;
38836c39055aSMatthias Ringwald                                     default:
38846c39055aSMatthias Ringwald                                         // wait for irk look doen
38856c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
38866c39055aSMatthias Ringwald                                         break;
38876c39055aSMatthias Ringwald                                 }
38886c39055aSMatthias Ringwald                                 break;
38896c39055aSMatthias Ringwald                             }
3890549ad5d2SMatthias Ringwald 
3891549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
389206cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3893549ad5d2SMatthias Ringwald #else
3894549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3895549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3896549ad5d2SMatthias Ringwald #endif
38973deb3ec6SMatthias Ringwald                             break;
3898804d3e67SMatthias Ringwald 
38993deb3ec6SMatthias Ringwald                         default:
39003deb3ec6SMatthias Ringwald                             break;
39013deb3ec6SMatthias Ringwald                     }
39023deb3ec6SMatthias Ringwald                     break;
39033deb3ec6SMatthias Ringwald 
39043deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
39058601e696SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
39063b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3907711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39083deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39093deb3ec6SMatthias Ringwald 
39103b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
39113deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
39123deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
39133deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
391403a9359aSMatthias Ringwald 
3915fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3916fbe050beSMatthias Ringwald 
39175567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
391803a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3919fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3920fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
39218d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
39228d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39238d4eef95SMatthias Ringwald                                 } else {
392403a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39258d4eef95SMatthias Ringwald                                 }
3926fbe050beSMatthias Ringwald                             } else {
3927e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3928cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
39293b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3930cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
39313b7fd749SMatthias Ringwald                             }
3932fbe050beSMatthias Ringwald 
3933fbe050beSMatthias Ringwald                             // emit re-encryption complete
393473102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3935fbe050beSMatthias Ringwald 
3936c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3937c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3938c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
39390ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
394003a9359aSMatthias Ringwald                             }
394103a9359aSMatthias Ringwald 
39423deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39433deb3ec6SMatthias Ringwald                             break;
3944fbe050beSMatthias Ringwald 
39453deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3946fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3947dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
394842134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39493deb3ec6SMatthias Ringwald                                 // slave
3950bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3951bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3952bbf8db22SMatthias Ringwald                                 } else {
3953f3582630SMatthias 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);
3954bbf8db22SMatthias Ringwald                                 }
39553deb3ec6SMatthias Ringwald                             } else {
39563deb3ec6SMatthias Ringwald                                 // master
395761d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
39583deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
39593deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3960f3582630SMatthias 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);
39613deb3ec6SMatthias Ringwald                                 } else {
39623deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39633deb3ec6SMatthias Ringwald                                 }
39643deb3ec6SMatthias Ringwald                             }
39653deb3ec6SMatthias Ringwald                             break;
3966c18be159SMatthias Ringwald 
3967c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3968c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3969a036ae12SMatthias Ringwald                             // CTKD requires BR/EDR Secure Connection
3970c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3971c18be159SMatthias Ringwald                             // prepare for pairing request
3972c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3973c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3974c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3975a036ae12SMatthias Ringwald                                 // check if remote supports fixed channels
3976553c9408SMatthias Ringwald                                 bool defer = true;
3977a036ae12SMatthias Ringwald                                 const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3978a036ae12SMatthias Ringwald                                 if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE){
3979a036ae12SMatthias Ringwald                                     // check if remote supports SMP over BR/EDR
3980a036ae12SMatthias Ringwald                                     if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
3981c18be159SMatthias Ringwald                                         sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3982553c9408SMatthias Ringwald                                     } else {
3983553c9408SMatthias Ringwald                                         defer = false;
3984c18be159SMatthias Ringwald                                     }
3985a036ae12SMatthias Ringwald                                 } else {
3986a036ae12SMatthias Ringwald                                     // wait for fixed channel info
3987a036ae12SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK;
3988a036ae12SMatthias Ringwald                                 }
3989553c9408SMatthias Ringwald                                 if (defer){
3990f82b8f4bSMatthias Ringwald                                     hci_dedicated_bonding_defer_disconnect(con_handle, true);
3991553c9408SMatthias Ringwald                                 }
3992a036ae12SMatthias Ringwald                             }
3993c18be159SMatthias Ringwald                             break;
3994c18be159SMatthias Ringwald #endif
39953deb3ec6SMatthias Ringwald                         default:
39963deb3ec6SMatthias Ringwald                             break;
39973deb3ec6SMatthias Ringwald                     }
39983deb3ec6SMatthias Ringwald                     break;
39993deb3ec6SMatthias Ringwald 
40003deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
4001711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
4002711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
40033deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
40043deb3ec6SMatthias Ringwald 
40053deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
40063deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
40073deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
40083deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
40095567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
40105567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
40115567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
40125567aa60SMatthias Ringwald                             } else {
40133deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
40145567aa60SMatthias Ringwald                             }
40153deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
40163deb3ec6SMatthias Ringwald                             break;
40173deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
401842134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
40193deb3ec6SMatthias Ringwald                                 // slave
4020f3582630SMatthias 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);
40213deb3ec6SMatthias Ringwald                             } else {
40223deb3ec6SMatthias Ringwald                                 // master
40233deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
40243deb3ec6SMatthias Ringwald                             }
40253deb3ec6SMatthias Ringwald                             break;
40263deb3ec6SMatthias Ringwald                         default:
40273deb3ec6SMatthias Ringwald                             break;
40283deb3ec6SMatthias Ringwald                     }
40293deb3ec6SMatthias Ringwald                     break;
40303deb3ec6SMatthias Ringwald 
40313deb3ec6SMatthias Ringwald 
40323deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
4033711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
4034711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
4035711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
40363deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
40373deb3ec6SMatthias Ringwald 
403803f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
40397f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
40407f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
40417f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
40427f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
40437f3f442dSMatthias Ringwald                             break;
40447f3f442dSMatthias Ringwald                         default:
404568a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
40460ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
40477f3f442dSMatthias Ringwald                             break;
404803f736b1SMatthias Ringwald                     }
4049accbde80SMatthias Ringwald 
40503deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
40513deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
40523deb3ec6SMatthias Ringwald                     break;
40533deb3ec6SMatthias Ringwald 
40543deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
4055f7811256SMatthias Ringwald                     if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) {
40569091c5f5SMatthias Ringwald                         // set local addr for le device db
405733373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
40580c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
405933373e40SMatthias Ringwald                     }
406065b44ffdSMatthias Ringwald                     break;
4061a036ae12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4062a036ae12SMatthias Ringwald                 case L2CAP_EVENT_INFORMATION_RESPONSE:
4063a036ae12SMatthias Ringwald                     con_handle = l2cap_event_information_response_get_con_handle(packet);
4064a036ae12SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
4065a036ae12SMatthias Ringwald                     if (!sm_conn) break;
4066a036ae12SMatthias Ringwald                     if (sm_conn->sm_engine_state == SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK){
4067a036ae12SMatthias Ringwald                         // check if remote supports SMP over BR/EDR
4068a036ae12SMatthias Ringwald                         const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
4069a036ae12SMatthias Ringwald                         if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
4070a036ae12SMatthias Ringwald                             sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
4071a036ae12SMatthias Ringwald                         } else {
4072a036ae12SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4073f82b8f4bSMatthias Ringwald                             hci_dedicated_bonding_defer_disconnect(con_handle, false);
4074a036ae12SMatthias Ringwald                         }
4075a036ae12SMatthias Ringwald                     }
4076a036ae12SMatthias Ringwald                     break;
4077a036ae12SMatthias Ringwald #endif
407865b44ffdSMatthias Ringwald                 default:
407965b44ffdSMatthias Ringwald                     break;
40803deb3ec6SMatthias Ringwald 			}
408165b44ffdSMatthias Ringwald             break;
408265b44ffdSMatthias Ringwald         default:
408365b44ffdSMatthias Ringwald             break;
40843deb3ec6SMatthias Ringwald 	}
40853deb3ec6SMatthias Ringwald 
40863deb3ec6SMatthias Ringwald     sm_run();
40873deb3ec6SMatthias Ringwald }
40883deb3ec6SMatthias Ringwald 
40893deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
40903deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
40913deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
40923deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
40933deb3ec6SMatthias Ringwald }
40943deb3ec6SMatthias Ringwald 
4095945888f5SMatthias Ringwald 
409631c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4097945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
4098945888f5SMatthias Ringwald     switch (method){
4099945888f5SMatthias Ringwald         case JUST_WORKS:
410047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
4101945888f5SMatthias Ringwald             return 1;
4102945888f5SMatthias Ringwald         default:
4103945888f5SMatthias Ringwald             return 0;
4104945888f5SMatthias Ringwald     }
4105945888f5SMatthias Ringwald }
410607036a04SMatthias Ringwald // responder
4107945888f5SMatthias Ringwald 
4108688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
4109688a08f9SMatthias Ringwald     switch (method){
4110688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
4111688a08f9SMatthias Ringwald             return 1;
4112688a08f9SMatthias Ringwald         default:
4113688a08f9SMatthias Ringwald             return 0;
4114688a08f9SMatthias Ringwald     }
4115688a08f9SMatthias Ringwald }
411640c5d850SMatthias Ringwald 
411740c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
411840c5d850SMatthias Ringwald     switch (method){
411940c5d850SMatthias Ringwald         case PK_RESP_INPUT:
412040c5d850SMatthias Ringwald         case PK_INIT_INPUT:
412147fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
412240c5d850SMatthias Ringwald             return 1;
412340c5d850SMatthias Ringwald         default:
412440c5d850SMatthias Ringwald             return 0;
412540c5d850SMatthias Ringwald     }
412640c5d850SMatthias Ringwald }
412740c5d850SMatthias Ringwald 
412831c09488SMatthias Ringwald #endif
4129688a08f9SMatthias Ringwald 
41303deb3ec6SMatthias Ringwald /**
41313deb3ec6SMatthias Ringwald  * @return ok
41323deb3ec6SMatthias Ringwald  */
41333deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
41343deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
41353deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
41363deb3ec6SMatthias Ringwald         case JUST_WORKS:
41374ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
41383deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
41393deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
414047fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
41414ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
41423deb3ec6SMatthias Ringwald         case OOB:
41434ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
414447fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
41454ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
41463deb3ec6SMatthias Ringwald         default:
41473deb3ec6SMatthias Ringwald             return 0;
41483deb3ec6SMatthias Ringwald     }
41493deb3ec6SMatthias Ringwald }
41503deb3ec6SMatthias Ringwald 
415136f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
415236f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
415336f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
415436f0defaSMatthias Ringwald     if (sm_sc_only_mode){
415536f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
415636f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
415736f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
415836f0defaSMatthias Ringwald             return;
415936f0defaSMatthias Ringwald         }
416036f0defaSMatthias Ringwald     }
416136f0defaSMatthias Ringwald #else
416236f0defaSMatthias Ringwald     UNUSED(packet);
416336f0defaSMatthias Ringwald #endif
416436f0defaSMatthias Ringwald 
416536f0defaSMatthias Ringwald     int have_ltk;
416636f0defaSMatthias Ringwald     uint8_t ltk[16];
416736f0defaSMatthias Ringwald 
416836f0defaSMatthias Ringwald     // IRK complete?
416936f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
417036f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
417136f0defaSMatthias Ringwald             // start pairing
417236f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
417336f0defaSMatthias Ringwald             break;
417436f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
417536f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
417636f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
417736f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
417836f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
417936f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
418036f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
418136f0defaSMatthias Ringwald             } else {
418236f0defaSMatthias Ringwald                 // start pairing
418336f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
418436f0defaSMatthias Ringwald             }
418536f0defaSMatthias Ringwald             break;
418636f0defaSMatthias Ringwald         default:
418736f0defaSMatthias Ringwald             // otherwise, store security request
418836f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
418936f0defaSMatthias Ringwald             break;
419036f0defaSMatthias Ringwald     }
419136f0defaSMatthias Ringwald }
419236f0defaSMatthias Ringwald #endif
419336f0defaSMatthias Ringwald 
4194f9bda154SMatthias Ringwald static uint8_t sm_pdu_validate_and_get_opcode(uint8_t packet_type, const uint8_t *packet, uint16_t size){
41958334d3d8SMatthias Ringwald 
41964c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
41974c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
41984c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
41994c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
42004c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
42014c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
42024c1d1092SMatthias Ringwald             17, // 0x04 pairing random
42034c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
42044c1d1092SMatthias Ringwald             17, // 0x06 encryption information
42057a2e6387SMatthias Ringwald             11, // 0x07 master identification
42064c1d1092SMatthias Ringwald             17, // 0x08 identification information
42074c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
42084c1d1092SMatthias Ringwald             17, // 0x0a signing information
42094c1d1092SMatthias Ringwald             2,  // 0x0b security request
42104c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
42114c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
42124c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
42134c1d1092SMatthias Ringwald     };
42143deb3ec6SMatthias Ringwald 
4215f9bda154SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return 0;
4216f9bda154SMatthias Ringwald     if (size == 0u) return 0;
42174c1d1092SMatthias Ringwald 
42184c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
42194c1d1092SMatthias Ringwald 
42204c1d1092SMatthias Ringwald     // validate pdu size
4221f9bda154SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return 0;
4222f9bda154SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return 0;
4223f9bda154SMatthias Ringwald 
4224f9bda154SMatthias Ringwald     return sm_pdu_code;
4225f9bda154SMatthias Ringwald }
4226f9bda154SMatthias Ringwald 
4227f9bda154SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
4228f9bda154SMatthias Ringwald 
4229f9bda154SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4230f9bda154SMatthias Ringwald         sm_run();
4231f9bda154SMatthias Ringwald     }
4232f9bda154SMatthias Ringwald 
4233f9bda154SMatthias Ringwald     uint8_t sm_pdu_code = sm_pdu_validate_and_get_opcode(packet_type, packet, size);
4234f9bda154SMatthias Ringwald     if (sm_pdu_code == 0) return;
42353deb3ec6SMatthias Ringwald 
4236711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
42373deb3ec6SMatthias Ringwald     if (!sm_conn) return;
42383deb3ec6SMatthias Ringwald 
42394c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
424068a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
42410ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4242accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
42433deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
42443deb3ec6SMatthias Ringwald         return;
42453deb3ec6SMatthias Ringwald     }
42463deb3ec6SMatthias Ringwald 
42474c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
42483deb3ec6SMatthias Ringwald 
42493deb3ec6SMatthias Ringwald     int err;
425042134bc6SMatthias Ringwald     UNUSED(err);
42513deb3ec6SMatthias Ringwald 
42524c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
42533d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
42543d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
42553d7fe1e9SMatthias Ringwald         buffer[1] = 3;
42563d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
42573d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
42583d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
42593d7fe1e9SMatthias Ringwald         return;
42603d7fe1e9SMatthias Ringwald     }
42613d7fe1e9SMatthias Ringwald 
42623deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
42633deb3ec6SMatthias Ringwald 
4264c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
42653deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
42663deb3ec6SMatthias Ringwald             return;
42673deb3ec6SMatthias Ringwald 
426842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
426942134bc6SMatthias Ringwald 
42703deb3ec6SMatthias Ringwald         // Initiator
42713deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
42724c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
42733deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42743deb3ec6SMatthias Ringwald                 break;
42753deb3ec6SMatthias Ringwald             }
427636f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4277dc8ca372SMatthias Ringwald             break;
42783deb3ec6SMatthias Ringwald 
42793deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4280aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4281aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4282aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4283aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4284aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4285aacfafc3SMatthias Ringwald                 break;
4286aacfafc3SMatthias Ringwald             }
4287aacfafc3SMatthias Ringwald 
4288aacfafc3SMatthias Ringwald             // all other pdus are incorrect
42894c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
42903deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42913deb3ec6SMatthias Ringwald                 break;
42923deb3ec6SMatthias Ringwald             }
42930af429c6SMatthias Ringwald 
42943deb3ec6SMatthias Ringwald             // store pairing request
42956535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
42966535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
42973deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
42980af429c6SMatthias Ringwald 
42990af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
43000af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
43010af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
43020af429c6SMatthias Ringwald                 err = test_pairing_failure;
43030af429c6SMatthias Ringwald             }
43040af429c6SMatthias Ringwald #endif
43050af429c6SMatthias Ringwald 
43069305033eSMatthias Ringwald             if (err != 0){
4307f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
43083deb3ec6SMatthias Ringwald                 break;
43093deb3ec6SMatthias Ringwald             }
4310b41539d5SMatthias Ringwald 
4311b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4312b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4313f3582630SMatthias 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);
4314b41539d5SMatthias Ringwald                 break;
4315b41539d5SMatthias Ringwald             }
4316b41539d5SMatthias Ringwald 
4317136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4318136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
43198cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
43208cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4321136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4322136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4323136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4324c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4325136d331aSMatthias Ringwald                     }
43268cba5ca3SMatthias Ringwald                 } else {
4327c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
43288cba5ca3SMatthias Ringwald                 }
4329136d331aSMatthias Ringwald                 break;
4330136d331aSMatthias Ringwald             }
4331136d331aSMatthias Ringwald #endif
43323deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
43333deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
43343deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
43353deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4336f3582630SMatthias 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);
43373deb3ec6SMatthias Ringwald             }
43383deb3ec6SMatthias Ringwald             break;
43393deb3ec6SMatthias Ringwald 
43403deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
43414c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
43423deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43433deb3ec6SMatthias Ringwald                 break;
43443deb3ec6SMatthias Ringwald             }
43453deb3ec6SMatthias Ringwald 
43463deb3ec6SMatthias Ringwald             // store s_confirm
43479c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4348192365feSMatthias Ringwald 
4349aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4350aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4351aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4352aa9b34e5SMatthias Ringwald                 break;
4353aa9b34e5SMatthias Ringwald             }
4354aa9b34e5SMatthias Ringwald 
4355192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4356192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4357192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4358192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4359192365feSMatthias Ringwald             }
4360192365feSMatthias Ringwald #endif
43613deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
43623deb3ec6SMatthias Ringwald             break;
43633deb3ec6SMatthias Ringwald 
43643deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
43654c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
43663deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43673deb3ec6SMatthias Ringwald                 break;;
43683deb3ec6SMatthias Ringwald             }
43693deb3ec6SMatthias Ringwald 
43703deb3ec6SMatthias Ringwald             // received random value
43719c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
43723deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
43733deb3ec6SMatthias Ringwald             break;
4374dc542de1SMatthias Ringwald 
4375dc542de1SMatthias Ringwald         case SM_PH4_W4_CONNECTION_ENCRYPTED:
4376dc542de1SMatthias Ringwald             // ignore Security Request, see SM_INITIATOR_PH1_W4_PAIRING_RESPONSE above
4377dc542de1SMatthias Ringwald             if (sm_pdu_code != SM_CODE_SECURITY_REQUEST){
4378dc542de1SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4379dc542de1SMatthias Ringwald             }
4380dc542de1SMatthias Ringwald             break;
438142134bc6SMatthias Ringwald #endif
43823deb3ec6SMatthias Ringwald 
438342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43843deb3ec6SMatthias Ringwald         // Responder
43853deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
43863deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
43873deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
43884c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
43893deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43903deb3ec6SMatthias Ringwald                 break;;
43913deb3ec6SMatthias Ringwald             }
43923deb3ec6SMatthias Ringwald 
43933deb3ec6SMatthias Ringwald             // store pairing request
4394212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4395212d735eSMatthias Ringwald 
4396212d735eSMatthias Ringwald             // check if IRK completed
4397212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4398212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4399212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
44003deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
44013deb3ec6SMatthias Ringwald                     break;
4402212d735eSMatthias Ringwald                 default:
4403212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4404212d735eSMatthias Ringwald                     break;
4405212d735eSMatthias Ringwald             }
4406212d735eSMatthias Ringwald             break;
440742134bc6SMatthias Ringwald #endif
44083deb3ec6SMatthias Ringwald 
440927c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4410c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
44114c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
441227c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
441327c32905SMatthias Ringwald                 break;
441427c32905SMatthias Ringwald             }
4415bccf5e67SMatthias Ringwald 
4416e53be891SMatthias Ringwald             // store public key for DH Key calculation
4417fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4418fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4419bccf5e67SMatthias Ringwald 
442002658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
442102658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
442202658749SMatthias Ringwald                 log_info("Remote PK matches ours");
442302658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
442402658749SMatthias Ringwald                 break;
442502658749SMatthias Ringwald             }
442602658749SMatthias Ringwald 
4427d1a1f6a4SMatthias Ringwald             // validate public key
4428d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
44299305033eSMatthias Ringwald             if (err != 0){
443002658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4431349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4432bccf5e67SMatthias Ringwald                 break;
4433bccf5e67SMatthias Ringwald             }
4434891bb64aSMatthias Ringwald 
4435d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4436f3582630SMatthias 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);
44373cf37b8cSMatthias Ringwald 
443865a9a04eSMatthias Ringwald 
443965a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
444042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4441136d331aSMatthias Ringwald                 // responder
4442c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4443136d331aSMatthias Ringwald             } else {
4444136d331aSMatthias Ringwald                 // initiator
4445a1e31e9cSMatthias Ringwald                 // stk generation method
4446a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4447a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4448a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
444947fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4450c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4451a1e31e9cSMatthias Ringwald                         break;
4452a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
445307036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
445407036a04SMatthias Ringwald                         break;
445507036a04SMatthias Ringwald                     case PK_INIT_INPUT:
445647fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
445707036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
445807036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
445907036a04SMatthias Ringwald                             break;
446007036a04SMatthias Ringwald                         }
4461b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4462a1e31e9cSMatthias Ringwald                         break;
4463a1e31e9cSMatthias Ringwald                     case OOB:
4464d1a1f6a4SMatthias Ringwald                         // generate Nx
44654acf7b7bSMatthias Ringwald                         log_info("Generate Na");
44666ca80073SMatthias 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);
4467a1e31e9cSMatthias Ringwald                         break;
44687bbeb3adSMilanka Ringwald                     default:
44697bbeb3adSMilanka Ringwald                         btstack_assert(false);
44707bbeb3adSMilanka Ringwald                         break;
4471a1e31e9cSMatthias Ringwald                 }
4472136d331aSMatthias Ringwald             }
447327c32905SMatthias Ringwald             break;
4474e53be891SMatthias Ringwald 
4475c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
44764c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
447745a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
447845a61d50SMatthias Ringwald                 break;
447945a61d50SMatthias Ringwald             }
448045a61d50SMatthias Ringwald             // received confirm value
448145a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
448245a61d50SMatthias Ringwald 
4483192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4484192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4485192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4486192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4487192365feSMatthias Ringwald             }
4488192365feSMatthias Ringwald #endif
448942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
449045a61d50SMatthias Ringwald                 // responder
449107036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
449207036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
449307036a04SMatthias Ringwald                         // still waiting for passkey
449407036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
449507036a04SMatthias Ringwald                         break;
449607036a04SMatthias Ringwald                     }
449707036a04SMatthias Ringwald                 }
4498b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
449945a61d50SMatthias Ringwald             } else {
450045a61d50SMatthias Ringwald                 // initiator
4501945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
45026ca80073SMatthias 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);
4503f1c1783eSMatthias Ringwald                 } else {
4504c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
450545a61d50SMatthias Ringwald                 }
4506f1c1783eSMatthias Ringwald             }
450745a61d50SMatthias Ringwald             break;
450845a61d50SMatthias Ringwald 
4509c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
45104c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4511e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4512136d331aSMatthias Ringwald                 break;
4513e53be891SMatthias Ringwald             }
4514e53be891SMatthias Ringwald 
4515e53be891SMatthias Ringwald             // received random value
4516e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4517e53be891SMatthias Ringwald 
45185a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4519ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4520d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4521d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4522d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
452365a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4524d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4525688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4526ae451ec5SMatthias Ringwald                  break;
45275a293e6eSMatthias Ringwald             }
45286f52a196SMatthias Ringwald 
45294acf7b7bSMatthias Ringwald             // OOB
45304acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
45314acf7b7bSMatthias Ringwald 
45324acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
45334acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
45344acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45354ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
45364acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
45374acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
45384acf7b7bSMatthias Ringwald                     } else {
45396535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
45404acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
45414acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
45424acf7b7bSMatthias Ringwald                     }
45434acf7b7bSMatthias Ringwald                 }  else {
45444ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
45454acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
45464acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
45474acf7b7bSMatthias Ringwald                     } else {
45486535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
45494acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
45504acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
45514acf7b7bSMatthias Ringwald                     }
45524acf7b7bSMatthias Ringwald                 }
45534acf7b7bSMatthias Ringwald 
4554a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
45554acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4556a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4557a680ba6bSMatthias Ringwald                      break;
4558a680ba6bSMatthias Ringwald                 }
45594acf7b7bSMatthias Ringwald             }
4560a680ba6bSMatthias Ringwald 
4561a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4562688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4563e53be891SMatthias Ringwald             break;
4564e53be891SMatthias Ringwald 
4565901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4566901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
45673cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4568901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4569901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4570901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4571901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4572901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4573901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4574901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4575c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4576901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4577d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
45784c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4579e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4580e53be891SMatthias Ringwald                 break;
4581e53be891SMatthias Ringwald             }
4582e53be891SMatthias Ringwald             // store DHKey Check
4583901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4584e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4585446a8c36SMatthias Ringwald 
4586901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4587901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4588019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4589bd57ffebSMatthias Ringwald             }
4590bd57ffebSMatthias Ringwald             break;
459127c32905SMatthias Ringwald #endif
459227c32905SMatthias Ringwald 
459342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
45943deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
45954c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
45963deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
459727c32905SMatthias Ringwald                 break;
45983deb3ec6SMatthias Ringwald             }
45993deb3ec6SMatthias Ringwald 
46003deb3ec6SMatthias Ringwald             // received confirm value
46019c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
46023deb3ec6SMatthias Ringwald 
4603192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4604192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4605192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4606192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4607192365feSMatthias Ringwald             }
4608192365feSMatthias Ringwald #endif
46093deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
46103deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
46115611a760SMatthias 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);
46123deb3ec6SMatthias Ringwald             }
46133deb3ec6SMatthias Ringwald 
46143deb3ec6SMatthias Ringwald             // handle user cancel pairing?
46153deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4616f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
46173deb3ec6SMatthias Ringwald                 break;
46183deb3ec6SMatthias Ringwald             }
46193deb3ec6SMatthias Ringwald 
46203deb3ec6SMatthias Ringwald             // wait for user action?
46213deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
46223deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
46233deb3ec6SMatthias Ringwald                 break;
46243deb3ec6SMatthias Ringwald             }
46253deb3ec6SMatthias Ringwald 
46263deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4627f3582630SMatthias 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);
46283deb3ec6SMatthias Ringwald             break;
46293deb3ec6SMatthias Ringwald 
46303deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
46314c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
46323deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
46333deb3ec6SMatthias Ringwald                 break;;
46343deb3ec6SMatthias Ringwald             }
46353deb3ec6SMatthias Ringwald 
46363deb3ec6SMatthias Ringwald             // received random value
46379c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
46383deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
46393deb3ec6SMatthias Ringwald             break;
464042134bc6SMatthias Ringwald #endif
46413deb3ec6SMatthias Ringwald 
4642672dc582SMatthias Ringwald         case SM_PH2_W4_CONNECTION_ENCRYPTED:
46433deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
46444c1d1092SMatthias Ringwald             switch(sm_pdu_code){
46453deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
46463deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
46479c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
46483deb3ec6SMatthias Ringwald                     break;
46493deb3ec6SMatthias Ringwald 
46503deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
46513deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4652f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
46539c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
46543deb3ec6SMatthias Ringwald                     break;
46553deb3ec6SMatthias Ringwald 
46563deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
46573deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
46589c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
46593deb3ec6SMatthias Ringwald                     break;
46603deb3ec6SMatthias Ringwald 
46613deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
46623deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
46633deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4664724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
46653deb3ec6SMatthias Ringwald                     break;
46663deb3ec6SMatthias Ringwald 
46673deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
46683deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
46699c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
46703deb3ec6SMatthias Ringwald                     break;
46713deb3ec6SMatthias Ringwald                 default:
46723deb3ec6SMatthias Ringwald                     // Unexpected PDU
46733deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
46743deb3ec6SMatthias Ringwald                     break;
46753deb3ec6SMatthias Ringwald             }
46763deb3ec6SMatthias Ringwald             // done with key distribution?
467761d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
46783deb3ec6SMatthias Ringwald 
46793deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
46803deb3ec6SMatthias Ringwald 
468142134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
46826f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
46833deb3ec6SMatthias Ringwald                 } else {
4684625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4685625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4686bbf8db22SMatthias Ringwald                     } else {
4687f3582630SMatthias 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);
4688625f00b2SMatthias Ringwald                     }
46893deb3ec6SMatthias Ringwald                 }
46903deb3ec6SMatthias Ringwald             }
46913deb3ec6SMatthias Ringwald             break;
4692c18be159SMatthias Ringwald 
4693c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4694c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4695553c9408SMatthias Ringwald 
4696553c9408SMatthias Ringwald             // dedicated bonding complete
4697f82b8f4bSMatthias Ringwald             hci_dedicated_bonding_defer_disconnect(sm_conn->sm_handle, false);
4698553c9408SMatthias Ringwald 
4699c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4700c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4701c18be159SMatthias Ringwald                 break;
4702c18be159SMatthias Ringwald             }
4703c18be159SMatthias Ringwald             // store pairing response
4704c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4705c18be159SMatthias Ringwald 
4706c18be159SMatthias Ringwald             // validate encryption key size
4707c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres));
4708c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4709c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4710c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4711c18be159SMatthias Ringwald             }
4712c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4713c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4714c18be159SMatthias Ringwald                 break;
4715c18be159SMatthias Ringwald             }
4716c18be159SMatthias Ringwald 
4717c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4718c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4719c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4720c18be159SMatthias Ringwald 
4721c18be159SMatthias Ringwald             // skip receive if there are none
472261d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4723c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4724c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4725c18be159SMatthias Ringwald             } else {
4726c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4727c18be159SMatthias Ringwald             }
4728c18be159SMatthias Ringwald             break;
4729c18be159SMatthias Ringwald 
4730c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4731c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4732c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4733c18be159SMatthias Ringwald                 break;
4734c18be159SMatthias Ringwald             }
4735c18be159SMatthias Ringwald             // store pairing request
4736c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4737c18be159SMatthias Ringwald             // validate encryption key size
4738c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq));
4739c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4740c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4741c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4742c18be159SMatthias Ringwald             }
4743c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4744c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4745c18be159SMatthias Ringwald                 break;
4746c18be159SMatthias Ringwald             }
4747c18be159SMatthias Ringwald             // trigger response
4748c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4749c18be159SMatthias Ringwald             break;
4750c18be159SMatthias Ringwald 
4751c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4752c18be159SMatthias Ringwald             switch(sm_pdu_code){
4753c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4754c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4755c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4756c18be159SMatthias Ringwald                     break;
4757c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4758c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4759c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4760c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4761c18be159SMatthias Ringwald                     break;
4762c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4763c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4764c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4765c18be159SMatthias Ringwald                     break;
4766c18be159SMatthias Ringwald                 default:
4767c18be159SMatthias Ringwald                     // Unexpected PDU
4768c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4769c18be159SMatthias Ringwald                     break;
4770c18be159SMatthias Ringwald             }
4771c18be159SMatthias Ringwald 
4772c18be159SMatthias Ringwald             // all keys received
477361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4774c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4775c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4776c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4777c18be159SMatthias Ringwald                 } else {
4778c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4779c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4780c18be159SMatthias Ringwald                 }
4781c18be159SMatthias Ringwald             }
4782c18be159SMatthias Ringwald             break;
4783c18be159SMatthias Ringwald #endif
4784c18be159SMatthias Ringwald 
47853deb3ec6SMatthias Ringwald         default:
47863deb3ec6SMatthias Ringwald             // Unexpected PDU
47873deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
47882d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
47893deb3ec6SMatthias Ringwald             break;
47903deb3ec6SMatthias Ringwald     }
47913deb3ec6SMatthias Ringwald 
479270b44dd4SMatthias Ringwald     // try to send next pdu
479370b44dd4SMatthias Ringwald     sm_trigger_run();
47943deb3ec6SMatthias Ringwald }
47953deb3ec6SMatthias Ringwald 
47963deb3ec6SMatthias Ringwald // Security Manager Client API
4797a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
47983deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
47993deb3ec6SMatthias Ringwald }
48003deb3ec6SMatthias Ringwald 
48014acf7b7bSMatthias 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)){
4802a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4803a680ba6bSMatthias Ringwald }
4804a680ba6bSMatthias Ringwald 
4805b96d60a6SMatthias Ringwald void sm_register_ltk_callback( bool (*get_ltk_callback)(hci_con_handle_t con_handle, uint8_t address_type, bd_addr_t addr, uint8_t * ltk)){
4806b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4807b96d60a6SMatthias Ringwald }
4808b96d60a6SMatthias Ringwald 
480989a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
481089a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
481189a78d34SMatthias Ringwald }
481289a78d34SMatthias Ringwald 
481367f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
481467f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
481567f708e0SMatthias Ringwald }
481667f708e0SMatthias Ringwald 
48173deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
48183deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
48193deb3ec6SMatthias Ringwald }
48203deb3ec6SMatthias Ringwald 
48213deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
48223deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
48233deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
48243deb3ec6SMatthias Ringwald }
48253deb3ec6SMatthias Ringwald 
48263deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
482798d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
482898d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
482998d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
483098d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
483198d95509SMatthias Ringwald     }
483298d95509SMatthias Ringwald #endif
48333deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
48343deb3ec6SMatthias Ringwald }
48353deb3ec6SMatthias Ringwald 
48363deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
48373deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
48383deb3ec6SMatthias Ringwald }
48393deb3ec6SMatthias Ringwald 
484042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48413deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
48423deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
48433deb3ec6SMatthias Ringwald }
484442134bc6SMatthias Ringwald #endif
48453deb3ec6SMatthias Ringwald 
48463deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
48476535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
48483deb3ec6SMatthias Ringwald }
48493deb3ec6SMatthias Ringwald 
48503deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
48516535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
48523deb3ec6SMatthias Ringwald }
48533deb3ec6SMatthias Ringwald 
48543deb3ec6SMatthias Ringwald // Testing support only
48553deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
48566535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4857103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4858841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
48593deb3ec6SMatthias Ringwald }
48603deb3ec6SMatthias Ringwald 
48613deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4862841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
48633deb3ec6SMatthias Ringwald }
48643deb3ec6SMatthias Ringwald 
4865d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4866d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4867d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4868d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
486934b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
487070b44dd4SMatthias Ringwald     sm_trigger_run();
4871d1a1f6a4SMatthias Ringwald }
4872674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
487334b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4874674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4875674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4876674e5b4aSMatthias Ringwald }
4877d1a1f6a4SMatthias Ringwald #endif
4878d1a1f6a4SMatthias Ringwald 
4879192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4880192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4881192365feSMatthias Ringwald     test_pairing_failure = reason;
4882192365feSMatthias Ringwald }
4883192365feSMatthias Ringwald #endif
4884192365feSMatthias Ringwald 
48857887cd92SMatthias Ringwald static void sm_state_reset(void) {
48867f775357SMatthias Ringwald #ifdef USE_CMAC_ENGINE
48877f775357SMatthias Ringwald     sm_cmac_active  = 0;
48887f775357SMatthias Ringwald #endif
48897f775357SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
48907f775357SMatthias Ringwald     rau_state = RAU_IDLE;
48917f775357SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
48927f775357SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
48937f775357SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
48947f775357SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
48957f775357SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
4896cbdd51cfSMatthias Ringwald     sm_persistent_keys_random_active = false;
48977f775357SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
489815211b85SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_IDLE;
48997f775357SMatthias Ringwald #endif
49007f775357SMatthias Ringwald }
49017f775357SMatthias Ringwald 
49023deb3ec6SMatthias Ringwald void sm_init(void){
49032d2d4d3cSMatthias Ringwald 
49042d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
49052d2d4d3cSMatthias Ringwald 
4906899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4907899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4908899e6e02SMatthias Ringwald 
49093deb3ec6SMatthias Ringwald     // defaults
49103deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
49113deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4912b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4913b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4914b4343428SMatthias Ringwald 
49153deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
49163deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
49173deb3ec6SMatthias Ringwald 
49185ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
49191979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4920caf15bf3SMatthias Ringwald 
49213deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
49223deb3ec6SMatthias Ringwald 
4923841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
49243deb3ec6SMatthias Ringwald 
49257f775357SMatthias Ringwald     // other
492684c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
492784c0c5c7SMatthias Ringwald 
4928a036ae12SMatthias Ringwald     // register for HCI Events
4929e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4930e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4931e03e489aSMatthias Ringwald 
4932bad51150SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4933a036ae12SMatthias Ringwald     // register for L2CAP events
4934a036ae12SMatthias Ringwald     l2cap_event_callback_registration.callback = &sm_event_packet_handler;
4935a036ae12SMatthias Ringwald     l2cap_add_event_handler(&l2cap_event_callback_registration);
4936bad51150SMatthias Ringwald #endif
4937a036ae12SMatthias Ringwald 
4938d1a1f6a4SMatthias Ringwald     //
4939d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4940d1a1f6a4SMatthias Ringwald 
494151bd74d1SMatthias Ringwald     // init le_device_db
494251bd74d1SMatthias Ringwald     le_device_db_init();
494351bd74d1SMatthias Ringwald 
4944b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4945e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4946384eabd3SMatthias Ringwald #ifdef ENABLE_CLASSIC
4947384eabd3SMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4948384eabd3SMatthias Ringwald #endif
494927c32905SMatthias Ringwald 
49507f775357SMatthias Ringwald     // state
49517f775357SMatthias Ringwald     sm_state_reset();
49522d2d4d3cSMatthias Ringwald 
49532d2d4d3cSMatthias Ringwald     sm_initialized = true;
49543deb3ec6SMatthias Ringwald }
49553deb3ec6SMatthias Ringwald 
495615537ea4SMatthias Ringwald void sm_deinit(void){
495715537ea4SMatthias Ringwald     sm_initialized = false;
495815537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
495915537ea4SMatthias Ringwald }
496015537ea4SMatthias Ringwald 
49614b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
49624b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4963caf15bf3SMatthias Ringwald }
4964caf15bf3SMatthias Ringwald 
49656c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
49661979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
49676c39055aSMatthias Ringwald }
49686c39055aSMatthias Ringwald 
4969711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4970711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
49713deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
49723deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
49733deb3ec6SMatthias Ringwald }
49743deb3ec6SMatthias Ringwald 
4975916ea5b2SMatthias Ringwald static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk){
4976916ea5b2SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(connection->sm_handle);
4977916ea5b2SMatthias Ringwald     btstack_assert(hci_con != NULL);
4978916ea5b2SMatthias Ringwald     memcpy(hci_con->link_key, ltk, 16);
4979916ea5b2SMatthias Ringwald     hci_con->link_key_type = 1;
4980916ea5b2SMatthias Ringwald }
4981916ea5b2SMatthias Ringwald 
498277e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
498377e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
498477e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
498577e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
498677e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
498777e2e5edSMatthias Ringwald }
498877e2e5edSMatthias Ringwald #endif
498977e2e5edSMatthias Ringwald 
49906bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4991711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4992711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49933deb3ec6SMatthias Ringwald     if (!sm_conn) return;
49946bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
49956bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
49963deb3ec6SMatthias Ringwald }
49973deb3ec6SMatthias Ringwald 
49983deb3ec6SMatthias Ringwald // request pairing
4999711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
5000711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50013deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50023deb3ec6SMatthias Ringwald 
50037af5dcd5SMatthias Ringwald     bool have_ltk;
50047af5dcd5SMatthias Ringwald     uint8_t ltk[16];
50053deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
500642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
500724c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
500824c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
500924c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
50107af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
50117af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
50127af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
50137af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
50147af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
50157af5dcd5SMatthias Ringwald                         if (have_ltk){
50167af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
501724c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
50187af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
50197af5dcd5SMatthias Ringwald                             break;
50207af5dcd5SMatthias Ringwald                         }
50217af5dcd5SMatthias Ringwald                         /* fall through */
50227af5dcd5SMatthias Ringwald 
50237af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
50247af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
50257af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
50267af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
50277af5dcd5SMatthias Ringwald                         break;
50287af5dcd5SMatthias Ringwald                     default:
50297af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
50307af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
50317af5dcd5SMatthias Ringwald                         break;
50327af5dcd5SMatthias Ringwald                 }
503324c20dc4SMatthias Ringwald                 break;
503424c20dc4SMatthias Ringwald             default:
503524c20dc4SMatthias Ringwald                 break;
503624c20dc4SMatthias Ringwald         }
50373deb3ec6SMatthias Ringwald     } else {
50383deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
5039175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
5040175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
50413deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
50423deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
50433dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
5044f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
5045f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
5046f53ec649SMatthias Ringwald                         if (have_ltk){
5047c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
50485567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
5049c245ca32SMatthias Ringwald                             break;
5050f53ec649SMatthias Ringwald                         }
5051cf373d3aSMatthias Ringwald                         /* fall through */
5052c245ca32SMatthias Ringwald 
505334c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
50543deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
50553deb3ec6SMatthias Ringwald                         break;
50563deb3ec6SMatthias Ringwald                     default:
5057d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
505809ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
50593deb3ec6SMatthias Ringwald                         break;
50603deb3ec6SMatthias Ringwald                 }
5061175b7faaSMatthias Ringwald                 break;
5062cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
5063cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
5064cb6d7eb0SMatthias Ringwald                 break;
5065175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
506609ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
5067175b7faaSMatthias Ringwald                 break;
5068175b7faaSMatthias Ringwald             default:
5069175b7faaSMatthias Ringwald                 break;
50703deb3ec6SMatthias Ringwald         }
50713deb3ec6SMatthias Ringwald     }
507270b44dd4SMatthias Ringwald     sm_trigger_run();
50733deb3ec6SMatthias Ringwald }
50743deb3ec6SMatthias Ringwald 
50753deb3ec6SMatthias Ringwald // called by client app on authorization request
5076711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
5077711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50783deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50793deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
5080589f5a99SMatthias 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);
50813deb3ec6SMatthias Ringwald }
50823deb3ec6SMatthias Ringwald 
5083711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
5084711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50853deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50863deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
5087589f5a99SMatthias 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);
50883deb3ec6SMatthias Ringwald }
50893deb3ec6SMatthias Ringwald 
50903deb3ec6SMatthias Ringwald // GAP Bonding API
50913deb3ec6SMatthias Ringwald 
5092711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
5093711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50943deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50953deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
50960af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
50970af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
50980af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
50990af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
51000af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
51010af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
51020af429c6SMatthias Ringwald #endif
51030af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
5104de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
5105de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
5106de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
510747fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
51080af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
5109de2fd182SMatthias Ringwald                     break;
511047fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
5111de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
5112de2fd182SMatthias Ringwald                     break;
5113de2fd182SMatthias Ringwald                 case JUST_WORKS:
5114de2fd182SMatthias Ringwald                 case OOB:
5115de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
5116de2fd182SMatthias Ringwald                     break;
51177bbeb3adSMilanka Ringwald                 default:
51187bbeb3adSMilanka Ringwald                     btstack_assert(false);
51197bbeb3adSMilanka Ringwald                     break;
5120de2fd182SMatthias Ringwald             }
51210af429c6SMatthias Ringwald             break;
51220af429c6SMatthias Ringwald         default:
51230af429c6SMatthias Ringwald             break;
51243deb3ec6SMatthias Ringwald     }
512570b44dd4SMatthias Ringwald     sm_trigger_run();
51263deb3ec6SMatthias Ringwald }
51273deb3ec6SMatthias Ringwald 
5128711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
5129711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51303deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51313deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
51323deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5133136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
5134c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
5135bbf8db22SMatthias Ringwald         } else {
5136f3582630SMatthias 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);
5137136d331aSMatthias Ringwald         }
51383deb3ec6SMatthias Ringwald     }
51390346c37cSMatthias Ringwald 
51400346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5141c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
5142dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
5143446a8c36SMatthias Ringwald     }
51440346c37cSMatthias Ringwald #endif
51450346c37cSMatthias Ringwald 
514670b44dd4SMatthias Ringwald     sm_trigger_run();
51473deb3ec6SMatthias Ringwald }
51483deb3ec6SMatthias Ringwald 
5149c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
5150c8c46d51SMatthias Ringwald     // for now, it's the same
5151c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
5152c8c46d51SMatthias Ringwald }
5153c8c46d51SMatthias Ringwald 
5154711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
5155711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51563deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51573deb3ec6SMatthias Ringwald     sm_reset_tk();
5158f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
51593deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
51603deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5161f3582630SMatthias 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);
51623deb3ec6SMatthias Ringwald     }
51631c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51646535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
51656535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
516607036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
516707036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
516807036a04SMatthias Ringwald     }
51691c516d8fSMatthias Ringwald #endif
517070b44dd4SMatthias Ringwald     sm_trigger_run();
51713deb3ec6SMatthias Ringwald }
51723deb3ec6SMatthias Ringwald 
51733d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
51743d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51753d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51763d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5177dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
51784ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5179dd4a08fbSMatthias Ringwald     switch (action){
5180dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5181dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
51824ea43905SMatthias Ringwald             flags |= (1u << action);
5183dd4a08fbSMatthias Ringwald             break;
5184dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5185dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
51864ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5187dd4a08fbSMatthias Ringwald             break;
5188dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
51894ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5190dd4a08fbSMatthias Ringwald                 // erase actions queued
5191dd4a08fbSMatthias Ringwald                 num_actions--;
51924ea43905SMatthias Ringwald                 if (num_actions == 0u){
5193dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
51944ea43905SMatthias Ringwald                     flags &= 0x19u;
5195dd4a08fbSMatthias Ringwald                 }
5196dd4a08fbSMatthias Ringwald                 break;
5197dd4a08fbSMatthias Ringwald             }
5198dd4a08fbSMatthias Ringwald             num_actions++;
51994ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5200dd4a08fbSMatthias Ringwald             break;
5201dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
52024ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5203dd4a08fbSMatthias Ringwald                 // enter actions queued
5204dd4a08fbSMatthias Ringwald                 num_actions--;
52054ea43905SMatthias Ringwald                 if (num_actions == 0u){
5206dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
52074ea43905SMatthias Ringwald                     flags &= 0x19u;
5208dd4a08fbSMatthias Ringwald                 }
5209dd4a08fbSMatthias Ringwald                 break;
5210dd4a08fbSMatthias Ringwald             }
5211dd4a08fbSMatthias Ringwald             num_actions++;
52124ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5213dd4a08fbSMatthias Ringwald             break;
5214dd4a08fbSMatthias Ringwald         default:
5215dd4a08fbSMatthias Ringwald             break;
5216dd4a08fbSMatthias Ringwald     }
5217dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
521870b44dd4SMatthias Ringwald     sm_trigger_run();
52193d7fe1e9SMatthias Ringwald }
52203d7fe1e9SMatthias Ringwald 
5221c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5222d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5223d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5224d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
522570b44dd4SMatthias Ringwald     sm_trigger_run();
5226d1a1f6a4SMatthias Ringwald }
5227c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
52288334d3d8SMatthias Ringwald 
52298334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
52308334d3d8SMatthias Ringwald 
5231c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5232c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5233d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5234d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5235c59d0c92SMatthias Ringwald     return 0;
5236c59d0c92SMatthias Ringwald }
5237c59d0c92SMatthias Ringwald #endif
5238c59d0c92SMatthias Ringwald 
52393deb3ec6SMatthias Ringwald /**
5240ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5241ba394633SMatthias Ringwald  * @param con_handle
5242ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5243ba394633SMatthias Ringwald  */
5244ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5245ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5246ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5247ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5248ba394633SMatthias Ringwald }
5249ba394633SMatthias Ringwald 
5250ba394633SMatthias Ringwald /**
52513deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
52523deb3ec6SMatthias Ringwald  * @param handle
52536b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
52543deb3ec6SMatthias Ringwald  */
5255711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5256711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
52573deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
52583deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
52593deb3ec6SMatthias Ringwald }
52603deb3ec6SMatthias Ringwald 
5261916ea5b2SMatthias Ringwald uint8_t sm_get_ltk(hci_con_handle_t con_handle, sm_key_t ltk){
5262916ea5b2SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5263916ea5b2SMatthias Ringwald     if (hci_connection == NULL){
5264916ea5b2SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5265916ea5b2SMatthias Ringwald     }
5266916ea5b2SMatthias Ringwald     if (hci_connection->link_key_type == 0){
5267916ea5b2SMatthias Ringwald         return ERROR_CODE_PIN_OR_KEY_MISSING;
5268916ea5b2SMatthias Ringwald     }
5269916ea5b2SMatthias Ringwald     memcpy(ltk, hci_connection->link_key, 16);
5270916ea5b2SMatthias Ringwald     return ERROR_CODE_SUCCESS;
5271916ea5b2SMatthias Ringwald }
5272916ea5b2SMatthias Ringwald 
52738f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
527447ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
527547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
527647ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
527747ba4de1SMatthias Ringwald             return 0;
527847ba4de1SMatthias Ringwald         default:
52798f57b085SMatthias Ringwald             return 1;
52808f57b085SMatthias Ringwald     }
528147ba4de1SMatthias Ringwald }
5282d70217a2SMatthias Ringwald 
528333373e40SMatthias Ringwald static uint8_t own_address_type(void){
5284b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5285b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5286b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5287b95a5a35SMatthias Ringwald         default:
5288b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5289b95a5a35SMatthias Ringwald     }
529033373e40SMatthias Ringwald }
52918f57b085SMatthias Ringwald 
52923deb3ec6SMatthias Ringwald // GAP LE API
52933deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
52943deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
52953deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5296b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
52978f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
52983deb3ec6SMatthias Ringwald     gap_random_address_update_start();
52993deb3ec6SMatthias Ringwald     gap_random_address_trigger();
53003deb3ec6SMatthias Ringwald }
53013deb3ec6SMatthias Ringwald 
53023deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
53033deb3ec6SMatthias Ringwald     return gap_random_adress_type;
53043deb3ec6SMatthias Ringwald }
53053deb3ec6SMatthias Ringwald 
53063deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
53073deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
53088f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
53093deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
53103deb3ec6SMatthias Ringwald     gap_random_address_update_start();
53113deb3ec6SMatthias Ringwald }
53123deb3ec6SMatthias Ringwald 
5313667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
53148f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
53156535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
531663d302e8SMatthias Ringwald     // assert msb bits are set to '11'
531763d302e8SMatthias Ringwald     sm_random_address[0] |= 0xc0;
531863d302e8SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
53197e252622SMatthias Ringwald }
53207e252622SMatthias Ringwald 
5321d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
53223deb3ec6SMatthias Ringwald /*
53233deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
53243deb3ec6SMatthias Ringwald  * @param adv_int_min
53253deb3ec6SMatthias Ringwald  * @param adv_int_max
53263deb3ec6SMatthias Ringwald  * @param adv_type
53273deb3ec6SMatthias Ringwald  * @param direct_address_type
53283deb3ec6SMatthias Ringwald  * @param direct_address
53293deb3ec6SMatthias Ringwald  * @param channel_map
53303deb3ec6SMatthias Ringwald  * @param filter_policy
53313deb3ec6SMatthias Ringwald  *
53323deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
53333deb3ec6SMatthias Ringwald  */
53343deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
53353deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5336b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
53373deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
53383deb3ec6SMatthias Ringwald }
5339d70217a2SMatthias Ringwald #endif
5340dcd6c9b5SMatthias Ringwald 
5341dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5342dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5343dcd6c9b5SMatthias Ringwald      // wrong connection
5344dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5345dcd6c9b5SMatthias Ringwald     // already encrypted
5346dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5347dcd6c9b5SMatthias Ringwald     // irk status?
5348dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5349dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5350dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5351dcd6c9b5SMatthias Ringwald             return 0;
5352dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5353dcd6c9b5SMatthias Ringwald             break;
5354dcd6c9b5SMatthias Ringwald         default:
5355dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5356dcd6c9b5SMatthias Ringwald             return 1;
5357dcd6c9b5SMatthias Ringwald     }
5358f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5359f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5360b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5361b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5362b15d5ceaSMatthias Ringwald     } else {
5363dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5364dcd6c9b5SMatthias Ringwald     }
5365b15d5ceaSMatthias Ringwald }
53663cdbe9dbSMatthias Ringwald 
53673cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
53683cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
53693cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
53703cdbe9dbSMatthias Ringwald #else
53713cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
53723cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
53733cdbe9dbSMatthias Ringwald #endif
53743cdbe9dbSMatthias Ringwald }
5375052bbdc5SMatthias Ringwald 
5376052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5377052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5378052bbdc5SMatthias Ringwald }
53794f384501SMatthias Ringwald 
53804f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
53814f384501SMatthias Ringwald     uint16_t i;
53824f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
53834f384501SMatthias Ringwald         bd_addr_t entry_address;
53844f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
53854f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
53864f384501SMatthias Ringwald         // skip unused entries
53874f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
53884f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
53892e08b70bSMatthias Ringwald             sm_remove_le_device_db_entry(i);
53904f384501SMatthias Ringwald             break;
53914f384501SMatthias Ringwald         }
53924f384501SMatthias Ringwald     }
53934f384501SMatthias Ringwald }
5394