xref: /btstack/src/ble/sm.c (revision ea9b67963c9d4a24002d906ff4f05b2537c93050)
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 int       sm_address_resolution_ah_calculation_active;
2573deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2583deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2593deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2603deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2618f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2623deb3ec6SMatthias Ringwald 
263d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2643deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2653deb3ec6SMatthias Ringwald 
266d1a1f6a4SMatthias Ringwald // crypto
267d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
268d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
269d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
270d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2717df1ef2fSMatthias Ringwald #endif
2727df1ef2fSMatthias Ringwald 
273d1a1f6a4SMatthias Ringwald // temp storage for random data
274d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
275d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
276d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
277d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2783deb3ec6SMatthias Ringwald 
279e03e489aSMatthias Ringwald // to receive hci events
280e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
281e03e489aSMatthias Ringwald 
28289a78d34SMatthias Ringwald /* to dispatch sm event */
28389a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28489a78d34SMatthias Ringwald 
285ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
286ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
287ece00d2dSMatthias Ringwald 
28809e4d397SMatthias Ringwald // LE Secure Connections
28909e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
29009e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
291fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
29209e4d397SMatthias Ringwald #endif
293df86eb96SMatthias Ringwald 
2943deb3ec6SMatthias Ringwald //
2953deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2963deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2973deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2983deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2993deb3ec6SMatthias Ringwald //
3003deb3ec6SMatthias Ringwald 
3013deb3ec6SMatthias Ringwald // data needed for security setup
3023deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3033deb3ec6SMatthias Ringwald 
304ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3053deb3ec6SMatthias Ringwald 
3063deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3073deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
308dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3093deb3ec6SMatthias Ringwald 
3103deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3139a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
314715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3153deb3ec6SMatthias Ringwald 
3163deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3173deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3183deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
319a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
32027c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3213deb3ec6SMatthias Ringwald 
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3233deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3243deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3273deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3283deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3293deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3303deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3313deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3323deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3333deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3343deb3ec6SMatthias Ringwald 
33568437d83SMatthias Ringwald     uint8_t   sm_state_vars;
336e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
337fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
338446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
339446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
340d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
341e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
342e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
343446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
344446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3452bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
346a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3477df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
348e53be891SMatthias Ringwald #endif
34927c32905SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // Phase 3
3513deb3ec6SMatthias Ringwald 
3523deb3ec6SMatthias Ringwald     // key distribution, we generate
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3543deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3553deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3563deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3583deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3593deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3603deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3613deb3ec6SMatthias Ringwald 
3623deb3ec6SMatthias Ringwald     // key distribution, received from peer
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3643deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3653deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3663deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3683deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3693deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3703deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3713deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
372715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
373715a43d1SMatthias Ringwald     int       sm_le_device_index;
374715a43d1SMatthias Ringwald #endif
375e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
376e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
377e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
378e0a03c85SMatthias Ringwald #endif
3793deb3ec6SMatthias Ringwald } sm_setup_context_t;
3803deb3ec6SMatthias Ringwald 
3813deb3ec6SMatthias Ringwald //
3823deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3833deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3843deb3ec6SMatthias Ringwald 
3853deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3867149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3873deb3ec6SMatthias Ringwald 
3886b65794dSMilanka Ringwald // @return 1 if oob data is available
3893deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3903deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3914acf7b7bSMatthias 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);
392b96d60a6SMatthias Ringwald static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk);
3933deb3ec6SMatthias Ringwald 
3943deb3ec6SMatthias Ringwald static void sm_run(void);
395711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
396711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39777e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39877e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
39977e2e5edSMatthias Ringwald #endif
4003deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
4013deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4122a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4152a526f21SMatthias Ringwald #endif
416d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
417d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
418d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
419d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
420d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4216d80b495SMatthias 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));
42234b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4236ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4246ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4252a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
426d1a1f6a4SMatthias Ringwald #endif
4270ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4283deb3ec6SMatthias Ringwald 
4293deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4303deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4313deb3ec6SMatthias Ringwald }
4323deb3ec6SMatthias Ringwald 
4331fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4341fbd72c5SMatthias Ringwald //     return packet[0];
4351fbd72c5SMatthias Ringwald // }
4361fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4371fbd72c5SMatthias Ringwald     return packet[1];
4381fbd72c5SMatthias Ringwald }
4391fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4401fbd72c5SMatthias Ringwald     return packet[2];
4411fbd72c5SMatthias Ringwald }
4421fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4431fbd72c5SMatthias Ringwald     return packet[3];
4441fbd72c5SMatthias Ringwald }
4451fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4461fbd72c5SMatthias Ringwald     return packet[4];
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4491fbd72c5SMatthias Ringwald     return packet[5];
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4521fbd72c5SMatthias Ringwald     return packet[6];
4531fbd72c5SMatthias Ringwald }
4541fbd72c5SMatthias Ringwald 
4551fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4561fbd72c5SMatthias Ringwald     packet[0] = code;
4571fbd72c5SMatthias Ringwald }
4581fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4591fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4601fbd72c5SMatthias Ringwald }
4611fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4621fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4631fbd72c5SMatthias Ringwald }
4641fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4651fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4661fbd72c5SMatthias Ringwald }
4671fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4681fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4691fbd72c5SMatthias Ringwald }
4701fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4711fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4721fbd72c5SMatthias Ringwald }
4731fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4741fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4751fbd72c5SMatthias Ringwald }
4761fbd72c5SMatthias Ringwald 
4776b65794dSMilanka Ringwald // @return 1 if all bytes are 0
4781979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4793deb3ec6SMatthias Ringwald     int i;
4803764b551SMatthias Ringwald     for (i=0; i < size ; i++){
48184c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4821979f09cSMatthias Ringwald             return false;
48384c0c5c7SMatthias Ringwald         }
4843deb3ec6SMatthias Ringwald     }
4851979f09cSMatthias Ringwald     return true;
4863deb3ec6SMatthias Ringwald }
4873deb3ec6SMatthias Ringwald 
4881979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4893764b551SMatthias Ringwald     return sm_is_null(random, 8);
4903764b551SMatthias Ringwald }
4913764b551SMatthias Ringwald 
4921979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4933764b551SMatthias Ringwald     return sm_is_null(key, 16);
4943764b551SMatthias Ringwald }
4953764b551SMatthias Ringwald 
49670b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49770b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49870b44dd4SMatthias Ringwald 	UNUSED(ts);
49970b44dd4SMatthias Ringwald 	sm_run();
50070b44dd4SMatthias Ringwald }
50170b44dd4SMatthias Ringwald static void sm_trigger_run(void){
5022d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
50384c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50470b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50570b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50670b44dd4SMatthias Ringwald }
50770b44dd4SMatthias Ringwald 
5083deb3ec6SMatthias Ringwald // Key utils
5093deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5103deb3ec6SMatthias Ringwald     int i;
5113deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5123deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5133deb3ec6SMatthias Ringwald     }
5143deb3ec6SMatthias Ringwald }
5153deb3ec6SMatthias Ringwald 
5163deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5173deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5183deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5193deb3ec6SMatthias Ringwald     int i;
5203deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5213deb3ec6SMatthias Ringwald         key[15-i] = 0;
5223deb3ec6SMatthias Ringwald     }
5233deb3ec6SMatthias Ringwald }
5243deb3ec6SMatthias Ringwald 
525899e6e02SMatthias Ringwald // ER / IR checks
52621045273SMatthias Ringwald static void sm_er_ir_set_default(void){
527899e6e02SMatthias Ringwald     int i;
528899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
529899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
530899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
531899e6e02SMatthias Ringwald     }
532899e6e02SMatthias Ringwald }
533899e6e02SMatthias Ringwald 
534899e6e02SMatthias Ringwald static int sm_er_is_default(void){
535899e6e02SMatthias Ringwald     int i;
536899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
537899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
538899e6e02SMatthias Ringwald     }
539899e6e02SMatthias Ringwald     return 1;
540899e6e02SMatthias Ringwald }
541899e6e02SMatthias Ringwald 
542899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
543899e6e02SMatthias Ringwald     int i;
544899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
545899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
546899e6e02SMatthias Ringwald     }
547899e6e02SMatthias Ringwald     return 1;
548899e6e02SMatthias Ringwald }
549899e6e02SMatthias Ringwald 
55073102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
55173102768SMatthias Ringwald     UNUSED(channel);
55273102768SMatthias Ringwald 
55373102768SMatthias Ringwald     // log event
55473102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55573102768SMatthias Ringwald     // dispatch to all event handlers
55673102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55773102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55873102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55973102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
56073102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
56173102768SMatthias Ringwald     }
56273102768SMatthias Ringwald }
56373102768SMatthias Ringwald 
56473102768SMatthias 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){
56573102768SMatthias Ringwald     event[0] = type;
56673102768SMatthias Ringwald     event[1] = event_size - 2;
56773102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56873102768SMatthias Ringwald     event[4] = addr_type;
56973102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
57073102768SMatthias Ringwald }
57173102768SMatthias Ringwald 
57273102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
57373102768SMatthias Ringwald     uint8_t event[11];
57473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57673102768SMatthias Ringwald }
57773102768SMatthias Ringwald 
57873102768SMatthias Ringwald static void sm_notify_client_passkey(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint32_t passkey){
57973102768SMatthias Ringwald     uint8_t event[15];
58073102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58173102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
58273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58373102768SMatthias Ringwald }
58473102768SMatthias Ringwald 
58573102768SMatthias 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){
58673102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58773102768SMatthias Ringwald     bd_addr_t identity_address;
58873102768SMatthias Ringwald     int identity_address_type;
58973102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
59073102768SMatthias Ringwald 
59173102768SMatthias Ringwald     uint8_t event[20];
59273102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59373102768SMatthias Ringwald     event[11] = identity_address_type;
59473102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
59573102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
59673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59773102768SMatthias Ringwald }
59873102768SMatthias Ringwald 
59973102768SMatthias 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){
60073102768SMatthias Ringwald     uint8_t event[12];
60173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
60273102768SMatthias Ringwald     event[11] = status;
60373102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
60473102768SMatthias Ringwald }
60573102768SMatthias Ringwald 
60673102768SMatthias Ringwald 
60773102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60873102768SMatthias Ringwald 
6093ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6103ab61f77SMatthias Ringwald 
6117b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
61273102768SMatthias Ringwald 
61373102768SMatthias Ringwald     int       identity_addr_type;
61473102768SMatthias Ringwald     bd_addr_t identity_addr;
6153c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6163c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6183c0e26deSMatthias Ringwald     } else {
6193c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6203c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6213c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6223c0e26deSMatthias Ringwald     }
62373102768SMatthias Ringwald 
62473102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
62573102768SMatthias Ringwald }
62673102768SMatthias Ringwald 
62773102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62873102768SMatthias Ringwald 
62960be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
63060be5b21SMatthias Ringwald 
6317b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
63273102768SMatthias Ringwald 
63373102768SMatthias Ringwald     int       identity_addr_type;
63473102768SMatthias Ringwald     bd_addr_t identity_addr;
6353c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6363c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63773102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6383c0e26deSMatthias Ringwald     } else {
6393c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6403c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6413c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6423c0e26deSMatthias Ringwald     }
64373102768SMatthias Ringwald 
64473102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
64573102768SMatthias Ringwald }
64673102768SMatthias Ringwald 
647d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
648d3c12277SMatthias Ringwald 
649d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
650d3c12277SMatthias Ringwald 
651d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
652d3c12277SMatthias Ringwald 
653d3c12277SMatthias Ringwald     uint8_t event[11];
654d3c12277SMatthias 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);
655d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
656d3c12277SMatthias Ringwald }
657d3c12277SMatthias Ringwald 
6580ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
659f61072f5SMatthias Ringwald 
660d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
661d77906ffSMatthias Ringwald 
66269f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
66369f82ad8SMatthias Ringwald 
6640ccf6c9cSMatthias Ringwald     uint8_t event[13];
6650ccf6c9cSMatthias 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);
6660ccf6c9cSMatthias Ringwald     event[11] = status;
6670ccf6c9cSMatthias Ringwald     event[12] = reason;
6680ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6690ccf6c9cSMatthias Ringwald }
6700ccf6c9cSMatthias Ringwald 
6713deb3ec6SMatthias Ringwald // SMP Timeout implementation
6723deb3ec6SMatthias Ringwald 
6733deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6743deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6753deb3ec6SMatthias Ringwald //
6763deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6773deb3ec6SMatthias Ringwald //
6783deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6793deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6803deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6813deb3ec6SMatthias Ringwald // established.
6823deb3ec6SMatthias Ringwald 
683ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6843deb3ec6SMatthias Ringwald     log_info("SM timeout");
685c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6863deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68768a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6880ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6893deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6903deb3ec6SMatthias Ringwald 
6913deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6923deb3ec6SMatthias Ringwald     sm_run();
6933deb3ec6SMatthias Ringwald }
6943deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
695528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
69691a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
697528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
698528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
699528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
7003deb3ec6SMatthias Ringwald }
7013deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
702528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
7033deb3ec6SMatthias Ringwald }
7043deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
7053deb3ec6SMatthias Ringwald     sm_timeout_stop();
7063deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7073deb3ec6SMatthias Ringwald }
7083deb3ec6SMatthias Ringwald 
7093deb3ec6SMatthias Ringwald // end of sm timeout
7103deb3ec6SMatthias Ringwald 
7113deb3ec6SMatthias Ringwald // GAP Random Address updates
7123deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
713ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7143deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7153deb3ec6SMatthias Ringwald 
7163deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
717899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
718d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
719fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
72070b44dd4SMatthias Ringwald     sm_trigger_run();
7213deb3ec6SMatthias Ringwald }
7223deb3ec6SMatthias Ringwald 
723ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7249ec2630cSMatthias Ringwald     UNUSED(timer);
7259ec2630cSMatthias Ringwald 
7263deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
727528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
728528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7293deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7303deb3ec6SMatthias Ringwald }
7313deb3ec6SMatthias Ringwald 
7323deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
733528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
734528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
735528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7363deb3ec6SMatthias Ringwald }
7373deb3ec6SMatthias Ringwald 
7383deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
739528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7403deb3ec6SMatthias Ringwald }
7413deb3ec6SMatthias Ringwald 
7423deb3ec6SMatthias Ringwald // ah(k,r) helper
7433deb3ec6SMatthias Ringwald // r = padding || r
7443deb3ec6SMatthias Ringwald // r - 24 bit value
7454a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7463deb3ec6SMatthias Ringwald     // r'= padding || r
7473deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7486535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7493deb3ec6SMatthias Ringwald }
7503deb3ec6SMatthias Ringwald 
7513deb3ec6SMatthias Ringwald // d1 helper
7523deb3ec6SMatthias Ringwald // d' = padding || r || d
7533deb3ec6SMatthias Ringwald // d,r - 16 bit values
7544a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7553deb3ec6SMatthias Ringwald     // d'= padding || r || d
7563deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
757f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
758f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7593deb3ec6SMatthias Ringwald }
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7624a6806f3SMatthias 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){
7633deb3ec6SMatthias Ringwald 
7643deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7653deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7663deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7673deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7683deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7693deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7703deb3ec6SMatthias Ringwald 
7713deb3ec6SMatthias Ringwald     sm_key_t p1;
7729c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7739c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7743deb3ec6SMatthias Ringwald     p1[14] = rat;
7753deb3ec6SMatthias Ringwald     p1[15] = iat;
7768314c363SMatthias Ringwald     log_info_key("p1", p1);
7778314c363SMatthias Ringwald     log_info_key("r", r);
7783deb3ec6SMatthias Ringwald 
7793deb3ec6SMatthias Ringwald     // t1 = r xor p1
7803deb3ec6SMatthias Ringwald     int i;
7813deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7823deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7833deb3ec6SMatthias Ringwald     }
7848314c363SMatthias Ringwald     log_info_key("t1", t1);
7853deb3ec6SMatthias Ringwald }
7863deb3ec6SMatthias Ringwald 
7873deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7884a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7893deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7903deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7913deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7923deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7933deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7943deb3ec6SMatthias Ringwald 
7953deb3ec6SMatthias Ringwald     sm_key_t p2;
7963deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7976535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7986535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7998314c363SMatthias Ringwald     log_info_key("p2", p2);
8003deb3ec6SMatthias Ringwald 
8013deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
8023deb3ec6SMatthias Ringwald     int i;
8033deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
8043deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
8053deb3ec6SMatthias Ringwald     }
8068314c363SMatthias Ringwald     log_info_key("t3", t3);
8073deb3ec6SMatthias Ringwald }
8083deb3ec6SMatthias Ringwald 
8094a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8108314c363SMatthias Ringwald     log_info_key("r1", r1);
8118314c363SMatthias Ringwald     log_info_key("r2", r2);
8126535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8136535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8143deb3ec6SMatthias Ringwald }
8153deb3ec6SMatthias Ringwald 
816fbe050beSMatthias Ringwald 
8173deb3ec6SMatthias Ringwald // decide on stk generation based on
8183deb3ec6SMatthias Ringwald // - pairing request
8193deb3ec6SMatthias Ringwald // - io capabilities
8203deb3ec6SMatthias Ringwald // - OOB data availability
8213deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8223deb3ec6SMatthias Ringwald 
8238334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8248334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8258334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8278334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8288334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8298334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8308334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8318334d3d8SMatthias Ringwald     };
8328334d3d8SMatthias Ringwald 
8338334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8348334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8358334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8368334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8378334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8388334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8398334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8408334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8418334d3d8SMatthias Ringwald     };
8428334d3d8SMatthias Ringwald #endif
8438334d3d8SMatthias Ringwald 
8443deb3ec6SMatthias Ringwald     // default: just works
8453deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8463deb3ec6SMatthias Ringwald 
84727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84827c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84927c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8504ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
85127c32905SMatthias Ringwald #else
85227c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
85327c32905SMatthias Ringwald #endif
85498d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
85527c32905SMatthias Ringwald 
85665a9a04eSMatthias Ringwald 
85765a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8581979f09cSMatthias Ringwald     bool use_oob;
85965a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
86065a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
86165a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8621979f09cSMatthias 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;
86365a9a04eSMatthias Ringwald     } else {
86465a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
86565a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8661979f09cSMatthias 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;
86765a9a04eSMatthias Ringwald     }
86865a9a04eSMatthias Ringwald     if (use_oob){
86965a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
87065a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
87165a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
87265a9a04eSMatthias Ringwald         return;
87365a9a04eSMatthias Ringwald     }
87465a9a04eSMatthias Ringwald 
87527c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
87627c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87727c32905SMatthias Ringwald     // model shall be used.
8784ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8794ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
88027c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
88127c32905SMatthias Ringwald         return;
88227c32905SMatthias Ringwald     }
88327c32905SMatthias Ringwald 
8843deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8853deb3ec6SMatthias Ringwald     sm_reset_tk();
8863deb3ec6SMatthias Ringwald 
8873deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8888da2e96dSMatthias 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)){
8893deb3ec6SMatthias Ringwald         return;
8903deb3ec6SMatthias Ringwald     }
8913deb3ec6SMatthias Ringwald 
8923deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8933deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
89427c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
89527c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
89627c32905SMatthias Ringwald 
89727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
898c6b7cbd9SMatthias Ringwald     // table not define by default
89927c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
90027c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
90127c32905SMatthias Ringwald     }
90227c32905SMatthias Ringwald #endif
90327c32905SMatthias 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)];
90427c32905SMatthias Ringwald 
9053deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
9061ad129beSMatthias 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);
9073deb3ec6SMatthias Ringwald }
9083deb3ec6SMatthias Ringwald 
9093deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9103deb3ec6SMatthias Ringwald     int flags = 0;
9113deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9123deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9143deb3ec6SMatthias Ringwald     }
9153deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9163deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9173deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9183deb3ec6SMatthias Ringwald     }
9193deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9203deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9213deb3ec6SMatthias Ringwald     }
9223deb3ec6SMatthias Ringwald     return flags;
9233deb3ec6SMatthias Ringwald }
9243deb3ec6SMatthias Ringwald 
9259a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9263deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9279a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9289a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
929715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9309790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
931715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9329790be5fSMatthias Ringwald #endif
9333deb3ec6SMatthias Ringwald }
9343deb3ec6SMatthias Ringwald 
9353deb3ec6SMatthias Ringwald // CSRK Key Lookup
9363deb3ec6SMatthias Ringwald 
9373deb3ec6SMatthias Ringwald 
9383deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9393deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9403deb3ec6SMatthias Ringwald }
9413deb3ec6SMatthias Ringwald 
942711e6c80SMatthias 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){
9436535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9443deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9453deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9463deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9473deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
948711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9493deb3ec6SMatthias Ringwald }
9503deb3ec6SMatthias Ringwald 
9513deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9523deb3ec6SMatthias Ringwald     // check if already in list
953665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9543deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
955665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
956665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
957665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9583deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9593deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9603deb3ec6SMatthias Ringwald         // already in list
9613deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9623deb3ec6SMatthias Ringwald     }
9633deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9643deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9653deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9666535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
967665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96870b44dd4SMatthias Ringwald     sm_trigger_run();
9693deb3ec6SMatthias Ringwald     return 0;
9703deb3ec6SMatthias Ringwald }
9713deb3ec6SMatthias Ringwald 
972d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
973d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
974514d35fcSMatthias Ringwald 
975d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
976d1a1f6a4SMatthias Ringwald     UNUSED(arg);
977d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
978d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97970b44dd4SMatthias Ringwald     sm_trigger_run();
9803deb3ec6SMatthias Ringwald }
981514d35fcSMatthias Ringwald 
9824dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9834ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9843deb3ec6SMatthias Ringwald }
9856d80b495SMatthias Ringwald #endif
9863deb3ec6SMatthias Ringwald 
9876d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
988514d35fcSMatthias Ringwald // generic cmac calculation
989d1a1f6a4SMatthias 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)){
990d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
991d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
992d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9933deb3ec6SMatthias Ringwald }
9947a766ebfSMatthias Ringwald #endif
9953deb3ec6SMatthias Ringwald 
996514d35fcSMatthias Ringwald // cmac for ATT Message signing
9977a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
998d1a1f6a4SMatthias Ringwald 
999d1a1f6a4SMatthias 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)){
1000d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
1001d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
1002d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
1003d1a1f6a4SMatthias Ringwald }
1004d1a1f6a4SMatthias Ringwald 
10054dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
1006d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1007d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10084dfd504aSMatthias Ringwald         return 0;
10094dfd504aSMatthias Ringwald     }
10104dfd504aSMatthias Ringwald 
1011d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10124dfd504aSMatthias Ringwald 
1013d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10144dfd504aSMatthias Ringwald     if (offset < 3){
1015d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10164dfd504aSMatthias Ringwald     }
1017d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10184dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1019d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10204dfd504aSMatthias Ringwald     }
1021d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10224dfd504aSMatthias Ringwald }
10234dfd504aSMatthias Ringwald 
10244dfd504aSMatthias 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)){
1025514d35fcSMatthias Ringwald     // ATT Message Signing
1026d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1027d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1028d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1029514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1030d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1031d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1032d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10333deb3ec6SMatthias Ringwald }
10347a766ebfSMatthias Ringwald #endif
10353deb3ec6SMatthias Ringwald 
1036*ea9b6796SMatthias Ringwald static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){
1037*ea9b6796SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1038*ea9b6796SMatthias Ringwald     sm_notify_client_base(event_type, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
1039*ea9b6796SMatthias Ringwald }
1040*ea9b6796SMatthias Ringwald 
1041*ea9b6796SMatthias Ringwald static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn){
1042*ea9b6796SMatthias Ringwald     sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type,
1043*ea9b6796SMatthias Ringwald                              sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
1044*ea9b6796SMatthias Ringwald }
1045*ea9b6796SMatthias Ringwald 
10463deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1047446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10483deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1049d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10503deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10513deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
105242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1053*ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10543deb3ec6SMatthias Ringwald             } else {
1055*ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10563deb3ec6SMatthias Ringwald             }
10573deb3ec6SMatthias Ringwald             break;
10583deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
105942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1060*ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10613deb3ec6SMatthias Ringwald             } else {
1062*ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10633deb3ec6SMatthias Ringwald             }
10643deb3ec6SMatthias Ringwald             break;
106547fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
1066*ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10673deb3ec6SMatthias Ringwald             break;
106847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1069*ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST);
107027c32905SMatthias Ringwald             break;
10713deb3ec6SMatthias Ringwald         case JUST_WORKS:
1072*ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST);
10733deb3ec6SMatthias Ringwald             break;
10743deb3ec6SMatthias Ringwald         case OOB:
10753deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10763deb3ec6SMatthias Ringwald             break;
10777bbeb3adSMilanka Ringwald         default:
10787bbeb3adSMilanka Ringwald             btstack_assert(false);
10797bbeb3adSMilanka Ringwald             break;
10803deb3ec6SMatthias Ringwald     }
10813deb3ec6SMatthias Ringwald }
10823deb3ec6SMatthias Ringwald 
108361d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
1084b2296177SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, bution_expected_set);
1085b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10863deb3ec6SMatthias Ringwald }
10873deb3ec6SMatthias Ringwald 
1088711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10897149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10903deb3ec6SMatthias Ringwald         sm_timeout_stop();
10917149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1092711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1093c085d9ffSMatthias Ringwald 
1094c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1095c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1096c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1097c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1098c085d9ffSMatthias Ringwald         }
1099c085d9ffSMatthias Ringwald #endif
11003deb3ec6SMatthias Ringwald     }
11013deb3ec6SMatthias Ringwald }
11023deb3ec6SMatthias Ringwald 
11037d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11041dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11050ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11061dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11071dca9d8aSMatthias Ringwald }
11081dca9d8aSMatthias Ringwald 
11093deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1110bb09604fSMatthias Ringwald 
1111bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11123deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1113bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11143deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1115bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1116bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1117bb09604fSMatthias Ringwald #endif
11187ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11197ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11207ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11217ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11227ece0eaaSMatthias Ringwald         }
11237ece0eaaSMatthias Ringwald #endif
11243deb3ec6SMatthias Ringwald     }
11253deb3ec6SMatthias Ringwald     return flags;
11263deb3ec6SMatthias Ringwald }
11273deb3ec6SMatthias Ringwald 
1128d7471931SMatthias Ringwald static void sm_reset_setup(void){
11293deb3ec6SMatthias Ringwald     // fill in sm setup
1130901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1131dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1132d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11333deb3ec6SMatthias Ringwald     sm_reset_tk();
1134d7471931SMatthias Ringwald }
1135d7471931SMatthias Ringwald 
1136d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1137d7471931SMatthias Ringwald     // fill in sm setup
11383deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11396535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11403deb3ec6SMatthias Ringwald 
1141a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11429305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1143a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11443deb3ec6SMatthias Ringwald     }
11453deb3ec6SMatthias Ringwald 
1146a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1147a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11484acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11494acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1150a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11519305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11524acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1153a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1154a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1155a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1156a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11574acf7b7bSMatthias Ringwald                     setup->sm_ra);
11584acf7b7bSMatthias Ringwald             } else {
11594acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11604acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11614acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11624acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11634acf7b7bSMatthias Ringwald                     setup->sm_rb);
11644acf7b7bSMatthias Ringwald             }
1165a680ba6bSMatthias Ringwald         } else {
1166a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1167a680ba6bSMatthias Ringwald         }
1168a680ba6bSMatthias Ringwald     }
1169a680ba6bSMatthias Ringwald #endif
1170a680ba6bSMatthias Ringwald 
11713deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11733deb3ec6SMatthias Ringwald         // slave
11743deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11753deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1176d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11776535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1178d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11793deb3ec6SMatthias Ringwald     } else {
11803deb3ec6SMatthias Ringwald         // master
11813deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11823deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1183d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11846535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1185d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11863deb3ec6SMatthias Ringwald 
1187d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11881ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11891ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11903deb3ec6SMatthias Ringwald     }
11913deb3ec6SMatthias Ringwald 
119257132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1193d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11942c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11952c041b42SMatthias Ringwald     // enable SC for SC only mode
11962c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11972c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1198d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
11992c041b42SMatthias Ringwald     }
12002c041b42SMatthias Ringwald #endif
120157132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120257132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120357132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120457132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120557132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120657132f12SMatthias Ringwald 	}
120757132f12SMatthias Ringwald #endif
12081ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1209a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1210df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1211d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12123deb3ec6SMatthias Ringwald }
12133deb3ec6SMatthias Ringwald 
12143deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12153deb3ec6SMatthias Ringwald 
12163deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12179a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12189a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
121942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
122052f9cf63SMatthias Ringwald         // slave / responder
12213deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12229a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12239a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12243deb3ec6SMatthias Ringwald     } else {
12253deb3ec6SMatthias Ringwald         // master / initiator
12263deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12279a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12289a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12293deb3ec6SMatthias Ringwald     }
12303deb3ec6SMatthias Ringwald 
12313deb3ec6SMatthias Ringwald     // check key size
12322c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12332c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12342c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12352c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12362c041b42SMatthias Ringwald     }
12372c041b42SMatthias Ringwald #endif
12381ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12394ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12403deb3ec6SMatthias Ringwald 
1241eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12423deb3ec6SMatthias Ringwald     sm_setup_tk();
12433deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12443deb3ec6SMatthias Ringwald 
12453deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12463deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12473deb3ec6SMatthias Ringwald 
1248eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12492c041b42SMatthias Ringwald     // Check LE SC Only mode
12503cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12513cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12523cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12533cdbe9dbSMatthias Ringwald     }
12543cdbe9dbSMatthias Ringwald 
12559a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1256eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12579a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12589a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1259eddc894fSMatthias Ringwald     }
1260eddc894fSMatthias Ringwald #endif
1261eddc894fSMatthias Ringwald 
126252f9cf63SMatthias Ringwald     // identical to responder
12639a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
126452f9cf63SMatthias Ringwald 
12653deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1266c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12673deb3ec6SMatthias Ringwald 
12683deb3ec6SMatthias Ringwald     return 0;
12693deb3ec6SMatthias Ringwald }
12703deb3ec6SMatthias Ringwald 
12713deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12723deb3ec6SMatthias Ringwald 
12733deb3ec6SMatthias Ringwald     // cache and reset context
12743deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12753deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12763deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12773deb3ec6SMatthias Ringwald 
12783deb3ec6SMatthias Ringwald     // reset context
12793deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12803deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12813deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1282711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12833deb3ec6SMatthias Ringwald 
12843deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1285d2e90122SMatthias Ringwald     sm_key_t ltk;
12861979f09cSMatthias Ringwald     bool have_ltk;
12876c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12881979f09cSMatthias Ringwald     bool trigger_pairing;
128942134bc6SMatthias Ringwald #endif
12903deb3ec6SMatthias Ringwald     switch (mode){
12913deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12923deb3ec6SMatthias Ringwald             break;
12933deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12943deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1295711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12966c44b759SMatthias Ringwald 
12976c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12986c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12996c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
13006c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
13016c44b759SMatthias Ringwald 
13023deb3ec6SMatthias Ringwald             switch (event){
1303a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13043deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13053deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1306a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13076c44b759SMatthias Ringwald 
13086c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13096c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13106c44b759SMatthias Ringwald 
13116c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13126c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1313212d735eSMatthias Ringwald                         // IRK required before, continue
13146c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13156c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13166c39055aSMatthias Ringwald                             break;
13176c39055aSMatthias Ringwald                         }
1318212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1319212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1320212d735eSMatthias Ringwald                             break;
1321212d735eSMatthias Ringwald                         }
13227af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13237af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13246c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13257af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13267af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13276c44b759SMatthias Ringwald #endif
13287af5dcd5SMatthias Ringwald 
13297af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13301979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13317af5dcd5SMatthias Ringwald 
13327af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13337af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13347af5dcd5SMatthias Ringwald                             if (have_ltk){
13357af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13367af5dcd5SMatthias Ringwald                             } else {
13377af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13387af5dcd5SMatthias Ringwald                             }
13397af5dcd5SMatthias Ringwald                             sm_trigger_run();
13406c44b759SMatthias Ringwald                         }
13416c44b759SMatthias Ringwald #endif
13426c44b759SMatthias Ringwald                     } else {
13436c44b759SMatthias Ringwald 
134442134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13456c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13466c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13476c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13481979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13493deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
135009ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
135132bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1352c245ca32SMatthias Ringwald 
1353d4af1595SMatthias Ringwald                         if (have_ltk){
13546a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1355b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135632bc5d65SMatthias Ringwald #else
135732bc5d65SMatthias Ringwald                             if (trigger_pairing){
135832bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135932bc5d65SMatthias Ringwald                             } else {
136032bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
136132bc5d65SMatthias Ringwald                             }
136232bc5d65SMatthias Ringwald #endif
136332bc5d65SMatthias Ringwald                         }
136432bc5d65SMatthias Ringwald 
136532bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13666c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13675567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1368d4af1595SMatthias Ringwald                             break;
1369d4af1595SMatthias Ringwald                         }
13706c44b759SMatthias Ringwald 
13716c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13726c44b759SMatthias Ringwald                         if (trigger_pairing){
13733deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1374d4af1595SMatthias Ringwald                             break;
13753deb3ec6SMatthias Ringwald                         }
137642134bc6SMatthias Ringwald #endif
1377298ab52bSMatthias Ringwald                     }
13783deb3ec6SMatthias Ringwald                     break;
13793deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13803deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13816c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13827af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13836c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13846c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13856c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13866c39055aSMatthias Ringwald                         }
13877af5dcd5SMatthias Ringwald                         // send security request if requested
13887af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13897af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13907af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13917af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13927af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13937af5dcd5SMatthias Ringwald                         }
13946c39055aSMatthias Ringwald                         break;
13957af5dcd5SMatthias Ringwald #endif
13966c39055aSMatthias Ringwald                     }
139742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139809ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13993deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
140009ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
14013deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
140242134bc6SMatthias Ringwald #endif
14033deb3ec6SMatthias Ringwald                     break;
14047bbeb3adSMilanka Ringwald 
14057bbeb3adSMilanka Ringwald                 default:
14067bbeb3adSMilanka Ringwald                     btstack_assert(false);
14077bbeb3adSMilanka Ringwald                     break;
14083deb3ec6SMatthias Ringwald             }
14093deb3ec6SMatthias Ringwald             break;
14103deb3ec6SMatthias Ringwald         default:
14113deb3ec6SMatthias Ringwald             break;
14123deb3ec6SMatthias Ringwald     }
14133deb3ec6SMatthias Ringwald 
14143deb3ec6SMatthias Ringwald     switch (event){
1415a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1416711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14173deb3ec6SMatthias Ringwald             break;
14183deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1419711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14203deb3ec6SMatthias Ringwald             break;
14217bbeb3adSMilanka Ringwald         default:
14227bbeb3adSMilanka Ringwald             btstack_assert(false);
14237bbeb3adSMilanka Ringwald             break;
14243deb3ec6SMatthias Ringwald     }
14253deb3ec6SMatthias Ringwald }
14263deb3ec6SMatthias Ringwald 
142755f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14283deb3ec6SMatthias Ringwald     int le_db_index = -1;
14293deb3ec6SMatthias Ringwald 
14303deb3ec6SMatthias Ringwald     // lookup device based on IRK
14313deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14323deb3ec6SMatthias Ringwald         int i;
1433092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14343deb3ec6SMatthias Ringwald             sm_key_t irk;
14353deb3ec6SMatthias Ringwald             bd_addr_t address;
1436c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14373deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1438adf5eaa9SMatthias Ringwald             // skip unused entries
1439c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
144011d10bdaSMatthias Ringwald             // compare Identity Address
144111d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
144211d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1443c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1444c7e2c1a5SMatthias Ringwald 
14453deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14463deb3ec6SMatthias Ringwald             le_db_index = i;
14473deb3ec6SMatthias Ringwald             break;
14483deb3ec6SMatthias Ringwald         }
1449c7e2c1a5SMatthias Ringwald     } else {
1450c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1451c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14523deb3ec6SMatthias Ringwald     }
14533deb3ec6SMatthias Ringwald 
14543deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14553deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1456c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14573deb3ec6SMatthias Ringwald         int i;
1458092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14593deb3ec6SMatthias Ringwald             bd_addr_t address;
1460adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14613deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1462adf5eaa9SMatthias Ringwald             // skip unused entries
1463adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14643deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14655df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14663deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14673deb3ec6SMatthias Ringwald                 le_db_index = i;
14683deb3ec6SMatthias Ringwald                 break;
14693deb3ec6SMatthias Ringwald             }
14703deb3ec6SMatthias Ringwald         }
14713deb3ec6SMatthias Ringwald     }
14723deb3ec6SMatthias Ringwald 
14733deb3ec6SMatthias Ringwald     // if not found, add to db
147402b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14753deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14763deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147702b02cffSMatthias Ringwald         new_to_le_device_db = true;
14783deb3ec6SMatthias Ringwald     }
14793deb3ec6SMatthias Ringwald 
14803deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14813deb3ec6SMatthias Ringwald 
148202b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148302b02cffSMatthias Ringwald         if (!new_to_le_device_db){
148402b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148502b02cffSMatthias Ringwald         }
148602b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148702b02cffSMatthias Ringwald #else
148802b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
148902b02cffSMatthias Ringwald #endif
149002b02cffSMatthias Ringwald 
149148163929SMatthias 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);
1492e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14937710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
149448163929SMatthias Ringwald 
1495eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14963deb3ec6SMatthias Ringwald         // store local CSRK
1497715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1498715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14993deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
15003deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15013deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
15023deb3ec6SMatthias Ringwald         }
15033deb3ec6SMatthias Ringwald 
15043deb3ec6SMatthias Ringwald         // store remote CSRK
15053deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15063deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
15073deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15083deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15093deb3ec6SMatthias Ringwald         }
1510eda85fbfSMatthias Ringwald #endif
151178f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
151278f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1513e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151478f44163SMatthias Ringwald             uint8_t zero_rand[8];
151578f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
151678f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15173dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151878f44163SMatthias Ringwald         }
151978f44163SMatthias Ringwald 
1520e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152178f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
152278f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1523e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15243deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15253dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152678f44163SMatthias Ringwald 
15273deb3ec6SMatthias Ringwald         }
15283deb3ec6SMatthias Ringwald     }
152955f09f49SMatthias Ringwald }
153055f09f49SMatthias Ringwald 
153155f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
153255f09f49SMatthias Ringwald 
153355f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
153455f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
153555f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
153655f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
153755f09f49SMatthias Ringwald 
153855f09f49SMatthias Ringwald     if (bonding_enabled){
153955f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
154027ef8bc8SMatthias Ringwald     } else {
154127ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
154227ef8bc8SMatthias Ringwald     }
15433deb3ec6SMatthias Ringwald }
15443deb3ec6SMatthias Ringwald 
1545688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1546f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1547688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1548688a08f9SMatthias Ringwald }
1549688a08f9SMatthias Ringwald 
1550688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1551688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1552688a08f9SMatthias Ringwald }
1553688a08f9SMatthias Ringwald 
15549af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1555688a08f9SMatthias Ringwald 
1556dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1557945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1558f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1559dc300847SMatthias Ringwald 
1560b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1561b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15621f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1563b90c4e75SMatthias Ringwald     } else {
1564b90c4e75SMatthias 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);
1565b35a3de2SMatthias Ringwald     }
1566b35a3de2SMatthias Ringwald }
1567b35a3de2SMatthias Ringwald 
1568688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
156942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1570688a08f9SMatthias Ringwald         // Responder
15714acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15724acf7b7bSMatthias Ringwald             // generate Nb
15734acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15746ca80073SMatthias 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);
15754acf7b7bSMatthias Ringwald         } else {
1576688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15774acf7b7bSMatthias Ringwald         }
1578688a08f9SMatthias Ringwald     } else {
1579688a08f9SMatthias Ringwald         // Initiator role
1580688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1581688a08f9SMatthias Ringwald             case JUST_WORKS:
1582dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1583688a08f9SMatthias Ringwald                 break;
1584688a08f9SMatthias Ringwald 
158547fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1586bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1587688a08f9SMatthias Ringwald                 break;
1588688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1589688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
159047fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15914ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1592b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1593688a08f9SMatthias Ringwald                 } else {
1594dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1595688a08f9SMatthias Ringwald                 }
1596688a08f9SMatthias Ringwald                 break;
1597688a08f9SMatthias Ringwald             case OOB:
159865a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1599688a08f9SMatthias Ringwald                 break;
16007bbeb3adSMilanka Ringwald             default:
16017bbeb3adSMilanka Ringwald                 btstack_assert(false);
16027bbeb3adSMilanka Ringwald                 break;
1603688a08f9SMatthias Ringwald         }
1604688a08f9SMatthias Ringwald     }
1605688a08f9SMatthias Ringwald }
1606688a08f9SMatthias Ringwald 
1607aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1608688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1609688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1610688a08f9SMatthias Ringwald 
1611c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1612c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1613a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1614c59d0c92SMatthias Ringwald         return;
1615c59d0c92SMatthias Ringwald     }
1616c59d0c92SMatthias Ringwald 
1617bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1618bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16196857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16202bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1621b4f65634SMatthias Ringwald #endif
1622bd57ffebSMatthias Ringwald 
1623bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1624aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16256535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1626bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1627aec94140SMatthias Ringwald             break;
1628688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1629688a08f9SMatthias Ringwald             // check
1630688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1631bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1632688a08f9SMatthias Ringwald                 break;
1633688a08f9SMatthias Ringwald             }
1634bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1635688a08f9SMatthias Ringwald             break;
1636901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1637901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1638901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1639901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1640901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1641019005a0SMatthias Ringwald             break;
1642019005a0SMatthias Ringwald         }
16430346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16446535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1645bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16460346c37cSMatthias Ringwald             break;
16470346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16486535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1649bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16500346c37cSMatthias Ringwald             break;
16510346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1652b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1653b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1654b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1655b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16566535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16576535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1658893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1659bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1660019005a0SMatthias Ringwald             break;
1661901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16626535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
166342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1664901c000fSMatthias Ringwald                 // responder
1665901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1666901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1667901c000fSMatthias Ringwald                 } else {
1668901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1669901c000fSMatthias Ringwald                 }
1670901c000fSMatthias Ringwald             } else {
1671901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1672901c000fSMatthias Ringwald             }
1673901c000fSMatthias Ringwald             break;
1674901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1675901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1676901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1677aec94140SMatthias Ringwald                 break;
1678aec94140SMatthias Ringwald             }
167942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1680901c000fSMatthias Ringwald                 // responder
1681901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1682901c000fSMatthias Ringwald             } else {
1683901c000fSMatthias Ringwald                 // initiator
1684901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1685bd57ffebSMatthias Ringwald             }
1686901c000fSMatthias Ringwald             break;
16876857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
168857132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16896535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
169057132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16912bacf595SMatthias Ringwald             break;
169257132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16932bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16942bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16952bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16968974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
169755160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16988974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16992bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
17002bacf595SMatthias Ringwald             } else {
17012bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
17022bacf595SMatthias Ringwald             }
17030ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17042bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17052bacf595SMatthias Ringwald             break;
1706e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1707e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1708e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1709e0a03c85SMatthias Ringwald             break;
1710e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1711e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1712e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1713e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1714e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1715e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1716e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1717c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1718e0a03c85SMatthias Ringwald             break;
1719bdb14b0eSMatthias Ringwald #endif
1720bd57ffebSMatthias Ringwald         default:
1721bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1722bd57ffebSMatthias Ringwald             break;
1723bd57ffebSMatthias Ringwald     }
172470b44dd4SMatthias Ringwald     sm_trigger_run();
1725aec94140SMatthias Ringwald }
1726aec94140SMatthias Ringwald 
1727688a08f9SMatthias 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){
1728dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1729aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17306535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17316535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1732aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1733aec94140SMatthias Ringwald     log_info("f4 key");
1734aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1735aec94140SMatthias Ringwald     log_info("f4 message");
1736dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1737d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1738aec94140SMatthias Ringwald }
1739aec94140SMatthias Ringwald 
17400346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17410346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17420346c37cSMatthias Ringwald 
17430346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17448334d3d8SMatthias Ringwald 
17458334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17468334d3d8SMatthias Ringwald 
174740c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17480346c37cSMatthias Ringwald     // calculate salt for f5
17490346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17500346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17516535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1752d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17530346c37cSMatthias Ringwald }
17540346c37cSMatthias Ringwald 
17550346c37cSMatthias 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){
17560346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17570346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17580346c37cSMatthias Ringwald 
17590346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17600346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17616535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17626535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17636535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17646535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17656535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17666535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17670346c37cSMatthias Ringwald     log_info("f5 key");
17680346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17690346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17700346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1771d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17720346c37cSMatthias Ringwald }
17730346c37cSMatthias Ringwald 
17740346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17750346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17760346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17770346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17786535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17796535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
178042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17810346c37cSMatthias Ringwald         // responder
17820346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17830346c37cSMatthias Ringwald     } else {
17840346c37cSMatthias Ringwald         // initiator
17850346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17860346c37cSMatthias Ringwald     }
17870346c37cSMatthias Ringwald }
17880346c37cSMatthias Ringwald 
17890346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17900346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17910346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17920346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17930346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17940346c37cSMatthias Ringwald     // 1..52 setup before
17950346c37cSMatthias Ringwald     log_info("f5 key");
17960346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17970346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17980346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1799d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18000346c37cSMatthias Ringwald }
1801f92edc8eSMatthias Ringwald 
18020346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
18030346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
18040346c37cSMatthias Ringwald }
18050346c37cSMatthias Ringwald 
180631f061fbSMatthias 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){
18076535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18086535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18096535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18106535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18126535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
181331f061fbSMatthias Ringwald }
181431f061fbSMatthias Ringwald 
181531f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
181631f061fbSMatthias Ringwald     const uint16_t message_len = 65;
181731f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1818dc300847SMatthias Ringwald     log_info("f6 key");
1819dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1820dc300847SMatthias Ringwald     log_info("f6 message");
1821dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1822d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1823dc300847SMatthias Ringwald }
1824dc300847SMatthias Ringwald 
1825f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1826f92edc8eSMatthias Ringwald // - U is 256 bits
1827f92edc8eSMatthias Ringwald // - V is 256 bits
1828f92edc8eSMatthias Ringwald // - X is 128 bits
1829f92edc8eSMatthias Ringwald // - Y is 128 bits
1830bd57ffebSMatthias 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){
1831bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1832bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18336535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18346535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18356535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1836f92edc8eSMatthias Ringwald     log_info("g2 key");
1837f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1838f92edc8eSMatthias Ringwald     log_info("g2 message");
18392bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1840d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1841f92edc8eSMatthias Ringwald }
1842f92edc8eSMatthias Ringwald 
1843b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1844f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
184542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1846f92edc8eSMatthias Ringwald         // responder
1847fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1848f92edc8eSMatthias Ringwald     } else {
1849f92edc8eSMatthias Ringwald         // initiator
1850fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1851f92edc8eSMatthias Ringwald     }
1852f92edc8eSMatthias Ringwald }
1853f92edc8eSMatthias Ringwald 
1854945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18559af0f475SMatthias Ringwald     uint8_t z = 0;
185640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18579af0f475SMatthias Ringwald         // some form of passkey
18589af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18594ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18609af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18619af0f475SMatthias Ringwald     }
1862fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18639af0f475SMatthias Ringwald }
1864688a08f9SMatthias Ringwald 
1865688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1866a680ba6bSMatthias Ringwald     // OOB
1867a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18684acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18694acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18704acf7b7bSMatthias Ringwald         } else {
18714acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18724acf7b7bSMatthias Ringwald         }
1873a680ba6bSMatthias Ringwald         return;
1874a680ba6bSMatthias Ringwald     }
1875a680ba6bSMatthias Ringwald 
1876688a08f9SMatthias Ringwald     uint8_t z = 0;
187740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1878688a08f9SMatthias Ringwald         // some form of passkey
1879688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1880688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18814ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1882688a08f9SMatthias Ringwald     }
1883fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1884688a08f9SMatthias Ringwald }
1885688a08f9SMatthias Ringwald 
18860346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1887505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18883cf37b8cSMatthias Ringwald 
18893cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18903cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18913cf37b8cSMatthias Ringwald         return;
18923cf37b8cSMatthias Ringwald     } else {
18933cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18943cf37b8cSMatthias Ringwald     }
1895d1a1f6a4SMatthias Ringwald }
18963cf37b8cSMatthias Ringwald 
1897d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1898f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1899f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1900f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1901f3582630SMatthias Ringwald 
1902d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1903d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1904d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1905d1a1f6a4SMatthias Ringwald     // trigger next step
1906d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1907d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1908d1a1f6a4SMatthias Ringwald     }
190970b44dd4SMatthias Ringwald     sm_trigger_run();
1910dc300847SMatthias Ringwald }
1911dc300847SMatthias Ringwald 
1912dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1913dc300847SMatthias Ringwald     // calculate DHKCheck
1914dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1915dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1916dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19176535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19186535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1919dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1920dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1921dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1922dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1923dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1924dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1925dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1926dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
192742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1928dc300847SMatthias Ringwald         // responder
192931f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
193031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1931dc300847SMatthias Ringwald     } else {
1932dc300847SMatthias Ringwald         // initiator
193331f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
193431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1935dc300847SMatthias Ringwald     }
1936dc300847SMatthias Ringwald }
1937dc300847SMatthias Ringwald 
1938019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1939019005a0SMatthias Ringwald     // validate E = f6()
1940019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1941019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1942019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19436535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19446535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1945019005a0SMatthias Ringwald 
1946019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1947019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1948019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1949019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1950019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1951019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1952019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1953019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
195442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1955019005a0SMatthias Ringwald         // responder
195631f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
195731f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1958019005a0SMatthias Ringwald     } else {
1959019005a0SMatthias Ringwald         // initiator
196031f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
196131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1962019005a0SMatthias Ringwald     }
1963019005a0SMatthias Ringwald }
19642bacf595SMatthias Ringwald 
196555c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19662bacf595SMatthias Ringwald 
19672bacf595SMatthias Ringwald //
19682bacf595SMatthias Ringwald // Link Key Conversion Function h6
19692bacf595SMatthias Ringwald //
197057132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19712bacf595SMatthias Ringwald // - W is 128 bits
19722bacf595SMatthias Ringwald // - keyID is 32 bits
19732bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19742bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19752bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19762bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19772bacf595SMatthias Ringwald     log_info("h6 key");
19782bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19792bacf595SMatthias Ringwald     log_info("h6 message");
19802bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1981d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19822bacf595SMatthias Ringwald }
198357132f12SMatthias Ringwald //
198457132f12SMatthias Ringwald // Link Key Conversion Function h7
198557132f12SMatthias Ringwald //
198657132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
198757132f12SMatthias Ringwald // - SALT is 128 bits
198857132f12SMatthias Ringwald // - W    is 128 bits
198957132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
199057132f12SMatthias Ringwald 	const uint16_t message_len = 16;
199157132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
199257132f12SMatthias Ringwald 	log_info("h7 key");
199357132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
199457132f12SMatthias Ringwald 	log_info("h7 message");
199557132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
199657132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
199757132f12SMatthias Ringwald }
19982bacf595SMatthias Ringwald 
1999b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
2000b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
2001b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
2002b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
200357132f12SMatthias Ringwald 
2004c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
2005b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
20062bacf595SMatthias Ringwald }
20072bacf595SMatthias Ringwald 
2008e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2009e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2010e0a03c85SMatthias Ringwald }
2011e0a03c85SMatthias Ringwald 
20122bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20132bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20142bacf595SMatthias Ringwald }
20152bacf595SMatthias Ringwald 
2016e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2017e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2018e0a03c85SMatthias Ringwald }
2019e0a03c85SMatthias Ringwald 
2020c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
202157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
202257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
202357132f12SMatthias Ringwald }
2024e0a03c85SMatthias Ringwald 
2025e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2026e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2027e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2028e0a03c85SMatthias Ringwald }
2029e0a03c85SMatthias Ringwald 
2030c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2031e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2032e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2033e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2034e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2035e0a03c85SMatthias Ringwald }
2036e0a03c85SMatthias Ringwald 
2037c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2038c18be159SMatthias 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;
2039c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2040c18be159SMatthias Ringwald }
2041c18be159SMatthias Ringwald 
20429af0f475SMatthias Ringwald #endif
20439af0f475SMatthias Ringwald 
204455c62cf5SMatthias Ringwald #endif
204555c62cf5SMatthias Ringwald 
2046613da3deSMatthias Ringwald // key management legacy connections:
2047613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2048613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2049613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2050613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2051613da3deSMatthias Ringwald 
2052613da3deSMatthias Ringwald // key management secure connections:
2053613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2054613da3deSMatthias Ringwald 
205542134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20565829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20575829ebe2SMatthias Ringwald     int encryption_key_size;
20585829ebe2SMatthias Ringwald     int authenticated;
20595829ebe2SMatthias Ringwald     int authorized;
20603dc3a67dSMatthias Ringwald     int secure_connection;
20615829ebe2SMatthias Ringwald 
20625829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20635829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20643dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20653dc3a67dSMatthias 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);
20665829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20675829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20685829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20693dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20705829ebe2SMatthias Ringwald }
207142134bc6SMatthias Ringwald #endif
2072bd57ffebSMatthias Ringwald 
207342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
207459066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20756535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
207659066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
207759066796SMatthias Ringwald     // re-establish used key encryption size
207859066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20794ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
208059066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20814ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20823dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20833dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
208459066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
208559066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
208659066796SMatthias Ringwald }
208742134bc6SMatthias Ringwald #endif
208859066796SMatthias Ringwald 
20893deb3ec6SMatthias Ringwald // distributed key generation
2090d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20913deb3ec6SMatthias Ringwald     switch (dkg_state){
20923deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20933deb3ec6SMatthias Ringwald             // already busy?
20943deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2095d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20963deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2097d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2098d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2099d1a1f6a4SMatthias 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);
2100d7f1c72eSMatthias Ringwald                 return true;
21013deb3ec6SMatthias Ringwald             }
21023deb3ec6SMatthias Ringwald             break;
21033deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
21043deb3ec6SMatthias Ringwald             // already busy?
21053deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2106d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
21073deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2108d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2109d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2110d1a1f6a4SMatthias 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);
2111d7f1c72eSMatthias Ringwald                 return true;
21123deb3ec6SMatthias Ringwald             }
21133deb3ec6SMatthias Ringwald             break;
21143deb3ec6SMatthias Ringwald         default:
21153deb3ec6SMatthias Ringwald             break;
21163deb3ec6SMatthias Ringwald     }
2117d7f1c72eSMatthias Ringwald     return false;
2118d7f1c72eSMatthias Ringwald }
21193deb3ec6SMatthias Ringwald 
21203deb3ec6SMatthias Ringwald // random address updates
2121d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21223deb3ec6SMatthias Ringwald     switch (rau_state){
2123fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2124fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21255b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2126d7f1c72eSMatthias Ringwald             return true;
21273deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21283deb3ec6SMatthias Ringwald             // already busy?
21293deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2130d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2131d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2132d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2133d7f1c72eSMatthias Ringwald                 return true;
21343deb3ec6SMatthias Ringwald             }
21353deb3ec6SMatthias Ringwald             break;
21363deb3ec6SMatthias Ringwald         default:
21373deb3ec6SMatthias Ringwald             break;
21383deb3ec6SMatthias Ringwald     }
2139d7f1c72eSMatthias Ringwald     return false;
2140d7f1c72eSMatthias Ringwald }
21413deb3ec6SMatthias Ringwald 
21423deb3ec6SMatthias Ringwald // CSRK Lookup
2143d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2144d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2145d7f1c72eSMatthias Ringwald 
21463deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21473deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21483deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2149665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2150665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21513deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21523deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21533deb3ec6SMatthias Ringwald                 // and start lookup
21543deb3ec6SMatthias 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);
21553deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21563deb3ec6SMatthias Ringwald                 break;
21573deb3ec6SMatthias Ringwald             }
21583deb3ec6SMatthias Ringwald         }
21593deb3ec6SMatthias Ringwald     }
21603deb3ec6SMatthias Ringwald 
21613deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21623deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2163665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21643deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2165665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21663deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21673deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21683deb3ec6SMatthias Ringwald         }
21693deb3ec6SMatthias Ringwald     }
21703deb3ec6SMatthias Ringwald 
21713deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21723deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2173092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2174092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2175adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21763deb3ec6SMatthias Ringwald             bd_addr_t addr;
21773deb3ec6SMatthias Ringwald             sm_key_t irk;
21783deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21793deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21803deb3ec6SMatthias Ringwald 
2181adf5eaa9SMatthias Ringwald             // skip unused entries
2182adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2183adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2184adf5eaa9SMatthias Ringwald                 continue;
2185adf5eaa9SMatthias Ringwald             }
2186adf5eaa9SMatthias Ringwald 
21875df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21883deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2189a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21903deb3ec6SMatthias Ringwald                 break;
21913deb3ec6SMatthias Ringwald             }
21923deb3ec6SMatthias Ringwald 
2193a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2194a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21953deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21963deb3ec6SMatthias Ringwald                 continue;
21973deb3ec6SMatthias Ringwald             }
21983deb3ec6SMatthias Ringwald 
21993deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
22003deb3ec6SMatthias Ringwald 
22013deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
22028314c363SMatthias Ringwald             log_info_key("IRK", irk);
22033deb3ec6SMatthias Ringwald 
22046535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2205d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
22063deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2207d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2208d1a1f6a4SMatthias 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);
2209d7f1c72eSMatthias Ringwald             return true;
22103deb3ec6SMatthias Ringwald         }
22113deb3ec6SMatthias Ringwald 
2212092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22133deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22143deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22153deb3ec6SMatthias Ringwald         }
22163deb3ec6SMatthias Ringwald     }
2217d7f1c72eSMatthias Ringwald     return false;
2218d7f1c72eSMatthias Ringwald }
22193deb3ec6SMatthias Ringwald 
2220d7f1c72eSMatthias Ringwald // SC OOB
2221d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2222c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2223c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2224c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2225c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2226c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2227c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2228d7f1c72eSMatthias Ringwald             return true;
2229c59d0c92SMatthias Ringwald         default:
2230c59d0c92SMatthias Ringwald             break;
2231c59d0c92SMatthias Ringwald     }
2232c59d0c92SMatthias Ringwald #endif
2233d7f1c72eSMatthias Ringwald     return false;
2234d7f1c72eSMatthias Ringwald }
2235275aafe8SMatthias Ringwald 
2236687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2237687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2238687a03c8SMatthias Ringwald }
2239687a03c8SMatthias Ringwald 
224041d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2241d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2242d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
224341d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2244e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
224541d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
224641d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
224741d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2248f4935286SMatthias Ringwald 
2249f4935286SMatthias Ringwald             // general
2250f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2251f4935286SMatthias Ringwald                 uint8_t buffer[2];
2252f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2253f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2254f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2255687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2256f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2257f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2258f4935286SMatthias Ringwald                 break;
2259f4935286SMatthias Ringwald             }
2260f4935286SMatthias Ringwald 
226141d32297SMatthias Ringwald             // responder side
226241d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
226341d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
226441d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2265d7f1c72eSMatthias Ringwald                 return true;
22664b8b5afeSMatthias Ringwald 
22674b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22684b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22694b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22704b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2271e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22724b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22734b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2274d7f1c72eSMatthias Ringwald                         return true;
22754b8b5afeSMatthias Ringwald                     default:
22764b8b5afeSMatthias Ringwald                         break;
22774b8b5afeSMatthias Ringwald                 }
22784b8b5afeSMatthias Ringwald                 break;
22794b8b5afeSMatthias Ringwald #endif
228041d32297SMatthias Ringwald             default:
228141d32297SMatthias Ringwald                 break;
228241d32297SMatthias Ringwald         }
228341d32297SMatthias Ringwald     }
2284d7f1c72eSMatthias Ringwald     return false;
2285d7f1c72eSMatthias Ringwald }
22863deb3ec6SMatthias Ringwald 
2287d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22883deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2289d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22903deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22917149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2292665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22933deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22943deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22951979f09cSMatthias Ringwald         bool done = true;
22963deb3ec6SMatthias Ringwald         int err;
229742134bc6SMatthias Ringwald         UNUSED(err);
229834b6528fSMatthias Ringwald 
229934b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
230034b6528fSMatthias Ringwald         // assert ec key is ready
2301505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2302178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2303178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
230434b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
230534b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
230634b6528fSMatthias Ringwald             }
230734b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
230834b6528fSMatthias Ringwald                 continue;
230934b6528fSMatthias Ringwald             }
231034b6528fSMatthias Ringwald         }
231134b6528fSMatthias Ringwald #endif
231234b6528fSMatthias Ringwald 
23133deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
231442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23153deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23163deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
231742134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2318549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
231906cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
232087014f74SMatthias Ringwald #endif
232187014f74SMatthias Ringwald #endif
232234c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23235567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
232434c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2325549ad5d2SMatthias Ringwald #endif
2326c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2327c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2328c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2329c18be159SMatthias Ringwald #endif
233087014f74SMatthias Ringwald 				// just lock context
233187014f74SMatthias Ringwald 				break;
23323deb3ec6SMatthias Ringwald             default:
23331979f09cSMatthias Ringwald                 done = false;
23343deb3ec6SMatthias Ringwald                 break;
23353deb3ec6SMatthias Ringwald         }
23363deb3ec6SMatthias Ringwald         if (done){
23377149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23387149bde5SMatthias 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);
23393deb3ec6SMatthias Ringwald         }
23403deb3ec6SMatthias Ringwald     }
2341d7f1c72eSMatthias Ringwald }
2342d7f1c72eSMatthias Ringwald 
2343403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2344403280b9SMatthias Ringwald     int i;
2345403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2346403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2347403280b9SMatthias Ringwald     uint8_t action = 0;
2348403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2349403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2350403280b9SMatthias Ringwald             bool clear_flag = true;
2351403280b9SMatthias Ringwald             switch (i){
2352403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2353403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2354403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2355403280b9SMatthias Ringwald                 default:
2356403280b9SMatthias Ringwald                     break;
2357403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2358403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2359403280b9SMatthias Ringwald                     num_actions--;
2360403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2361403280b9SMatthias Ringwald                     break;
2362403280b9SMatthias Ringwald             }
2363403280b9SMatthias Ringwald             if (clear_flag){
2364403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2365403280b9SMatthias Ringwald             }
2366403280b9SMatthias Ringwald             action = i;
2367403280b9SMatthias Ringwald             break;
2368403280b9SMatthias Ringwald         }
2369403280b9SMatthias Ringwald     }
2370403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2371403280b9SMatthias Ringwald 
2372403280b9SMatthias Ringwald     // send keypress notification
2373403280b9SMatthias Ringwald     uint8_t buffer[2];
2374403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2375403280b9SMatthias Ringwald     buffer[1] = action;
2376687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2377403280b9SMatthias Ringwald 
2378403280b9SMatthias Ringwald     // try
2379403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2380403280b9SMatthias Ringwald }
2381403280b9SMatthias Ringwald 
2382403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2383403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2384403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2385403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2386403280b9SMatthias Ringwald         uint8_t buffer[17];
2387403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2388403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2389687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2390403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2391403280b9SMatthias Ringwald         return;
2392403280b9SMatthias Ringwald     }
2393403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2394403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2395403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2396403280b9SMatthias Ringwald         uint8_t buffer[11];
2397403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2398403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2399403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2400687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2401403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2402403280b9SMatthias Ringwald         return;
2403403280b9SMatthias Ringwald     }
2404403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2405403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2406403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2407403280b9SMatthias Ringwald         uint8_t buffer[17];
2408403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2409403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2410687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2411403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2412403280b9SMatthias Ringwald         return;
2413403280b9SMatthias Ringwald     }
2414403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2415403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2416403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2417403280b9SMatthias Ringwald         bd_addr_t local_address;
2418403280b9SMatthias Ringwald         uint8_t buffer[8];
2419403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2420403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2421403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2422403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2423403280b9SMatthias Ringwald                 // public or static random
2424403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2425403280b9SMatthias Ringwald                 break;
2426403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2427403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2428403280b9SMatthias Ringwald                 // fallback to public
2429403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2430403280b9SMatthias Ringwald                 buffer[1] = 0;
2431403280b9SMatthias Ringwald                 break;
2432403280b9SMatthias Ringwald             default:
2433403280b9SMatthias Ringwald                 btstack_assert(false);
2434403280b9SMatthias Ringwald                 break;
2435403280b9SMatthias Ringwald         }
2436403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2437687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2438403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2439403280b9SMatthias Ringwald         return;
2440403280b9SMatthias Ringwald     }
2441403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2442403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2443403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2444403280b9SMatthias Ringwald 
2445403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2446403280b9SMatthias Ringwald         // hack to reproduce test runs
2447403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2448403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2449403280b9SMatthias Ringwald                     }
2450403280b9SMatthias Ringwald 
2451403280b9SMatthias Ringwald                     // store local CSRK
2452403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2453403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2454403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2455403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2456403280b9SMatthias Ringwald                     }
2457403280b9SMatthias Ringwald #endif
2458403280b9SMatthias Ringwald 
2459403280b9SMatthias Ringwald         uint8_t buffer[17];
2460403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2461403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2462687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2463403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2464403280b9SMatthias Ringwald         return;
2465403280b9SMatthias Ringwald     }
2466403280b9SMatthias Ringwald     btstack_assert(false);
2467403280b9SMatthias Ringwald }
2468403280b9SMatthias Ringwald 
2469bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2470bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2471bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2472bbd73538SMatthias Ringwald     // - use secure connections
2473bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2474bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2475bbd73538SMatthias 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;
2476bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2477bbd73538SMatthias Ringwald     // - need identity address / public addr
2478bbd73538SMatthias 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);
2479bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2480bbd73538SMatthias 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)
2481bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2482bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2483bbd73538SMatthias 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.
2484bbd73538SMatthias Ringwald     uint8_t link_key[16];
2485bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2486bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
24877040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2488bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2489bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2490bbd73538SMatthias Ringwald         return false;
2491bbd73538SMatthias Ringwald     }
2492bbd73538SMatthias Ringwald     // get started (all of the above are true)
2493bbd73538SMatthias Ringwald     return true;
2494bbd73538SMatthias Ringwald #else
2495bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2496bbd73538SMatthias Ringwald 	return false;
2497bbd73538SMatthias Ringwald #endif
2498bbd73538SMatthias Ringwald }
2499bbd73538SMatthias Ringwald 
25006f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
25016f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
25026f7422f1SMatthias 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;
25036f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
25046f7422f1SMatthias Ringwald     } else {
25056f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25066f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25076f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25086f7422f1SMatthias Ringwald     }
25096f7422f1SMatthias Ringwald }
25106f7422f1SMatthias Ringwald 
2511af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2512af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2513af7ef9d1SMatthias 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;
2514af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2515af7ef9d1SMatthias Ringwald     } else {
2516af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2517af7ef9d1SMatthias Ringwald     }
2518af7ef9d1SMatthias Ringwald }
2519af7ef9d1SMatthias Ringwald 
2520d7f1c72eSMatthias Ringwald static void sm_run(void){
2521d7f1c72eSMatthias Ringwald 
2522d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2523d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2524d7f1c72eSMatthias Ringwald 
2525d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2526d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2527d7f1c72eSMatthias Ringwald 
2528d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2529d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2530d7f1c72eSMatthias Ringwald 
2531d7f1c72eSMatthias Ringwald     bool done;
2532d7f1c72eSMatthias Ringwald 
2533d7f1c72eSMatthias Ringwald     //
2534d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2535d7f1c72eSMatthias Ringwald     //
2536d7f1c72eSMatthias Ringwald 
2537d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2538d7f1c72eSMatthias Ringwald     if (done) return;
2539d7f1c72eSMatthias Ringwald 
2540d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2541d7f1c72eSMatthias Ringwald     if (done) return;
2542d7f1c72eSMatthias Ringwald 
2543d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2544d7f1c72eSMatthias Ringwald     if (done) return;
2545d7f1c72eSMatthias Ringwald 
2546d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2547d7f1c72eSMatthias Ringwald     if (done) return;
2548d7f1c72eSMatthias Ringwald 
2549d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2550d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2551d7f1c72eSMatthias Ringwald 
2552d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2553d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2554d7f1c72eSMatthias Ringwald     if (done) return;
2555d7f1c72eSMatthias Ringwald 
2556d7f1c72eSMatthias Ringwald     //
2557d7f1c72eSMatthias Ringwald     // active connection handling
2558d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2559d7f1c72eSMatthias Ringwald 
2560d7f1c72eSMatthias Ringwald     while (true) {
2561d7f1c72eSMatthias Ringwald 
2562d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2563d7f1c72eSMatthias Ringwald 
2564d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25653deb3ec6SMatthias Ringwald 
25663deb3ec6SMatthias Ringwald         //
25673deb3ec6SMatthias Ringwald         // active connection handling
25683deb3ec6SMatthias Ringwald         //
25693deb3ec6SMatthias Ringwald 
25703cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25713cf37b8cSMatthias Ringwald         if (!connection) {
25723cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25733cf37b8cSMatthias Ringwald             return;
25743cf37b8cSMatthias Ringwald         }
25753cf37b8cSMatthias Ringwald 
25763deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25777149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25787149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25797149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2580b170b20fSMatthias Ringwald             return;
2581b170b20fSMatthias Ringwald         }
25823deb3ec6SMatthias Ringwald 
25833d7fe1e9SMatthias Ringwald         // send keypress notifications
2584dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2585403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2586d7471931SMatthias Ringwald             return;
25873d7fe1e9SMatthias Ringwald         }
25883d7fe1e9SMatthias Ringwald 
25893deb3ec6SMatthias Ringwald         int key_distribution_flags;
259042134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2591b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2592b6afa23eSMatthias Ringwald         int err;
25939b75de03SMatthias Ringwald         bool have_ltk;
25949b75de03SMatthias Ringwald         uint8_t ltk[16];
2595b6f39a74SMatthias Ringwald #endif
25963deb3ec6SMatthias Ringwald 
25973deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2598dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2599dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2600dd4a08fbSMatthias Ringwald         }
26013deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
26023deb3ec6SMatthias Ringwald 
2603f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2604aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2605aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2606aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2607aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2608aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2609aec94140SMatthias Ringwald                 break;
2610688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2611688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2612688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2613688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2614688a08f9SMatthias Ringwald                 break;
2615dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2616dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2617dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2618dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2619dc300847SMatthias Ringwald                 break;
2620019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2621b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2622019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26230346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26240346c37cSMatthias Ringwald                 break;
26250346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2626b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26270346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26280346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26290346c37cSMatthias Ringwald                 break;
26300346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2631b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26320346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26330346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26340346c37cSMatthias Ringwald                 break;
26350346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2636b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26370346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26380346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2639019005a0SMatthias Ringwald                 break;
2640bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2641b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2642bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2643b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2644bd57ffebSMatthias Ringwald                 break;
2645e0a03c85SMatthias Ringwald #endif
2646e0a03c85SMatthias Ringwald 
264742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26483deb3ec6SMatthias Ringwald             // initiator side
2649f32b7a88SMatthias Ringwald 
26505567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2651f32b7a88SMatthias Ringwald 				sm_reset_setup();
2652f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2653daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2654f32b7a88SMatthias Ringwald 
26553deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26569c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26575567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26583deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2659c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2660c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26613deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26623deb3ec6SMatthias Ringwald                 return;
26633deb3ec6SMatthias Ringwald             }
26643deb3ec6SMatthias Ringwald 
2665b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2666b26f445fSMatthias Ringwald 				sm_reset_setup();
2667b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2668b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2669d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2670b26f445fSMatthias Ringwald 
26711ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26723deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2673687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26743deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26753deb3ec6SMatthias Ringwald                 break;
267642134bc6SMatthias Ringwald #endif
26773deb3ec6SMatthias Ringwald 
267827c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
267941d32297SMatthias Ringwald 
2680c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26811979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26821979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
268327c32905SMatthias Ringwald                 uint8_t buffer[65];
268427c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
268527c32905SMatthias Ringwald                 //
2686fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2687fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2688e53be891SMatthias Ringwald 
2689349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2690349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2691349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2692349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2693349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2694349d0adbSMatthias Ringwald                 }
2695349d0adbSMatthias Ringwald #endif
2696349d0adbSMatthias Ringwald 
269745a61d50SMatthias Ringwald                 // stk generation method
269845a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
269945a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
270045a61d50SMatthias Ringwald                     case JUST_WORKS:
270147fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
270242134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
270307036a04SMatthias Ringwald                             // responder
27041979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2705b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
270627c32905SMatthias Ringwald                         } else {
270707036a04SMatthias Ringwald                             // initiator
2708c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270927c32905SMatthias Ringwald                         }
271045a61d50SMatthias Ringwald                         break;
271145a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
271245a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
271347fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
271407036a04SMatthias Ringwald                         // use random TK for display
27156535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27166535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
271745a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
271807036a04SMatthias Ringwald 
271942134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272045a61d50SMatthias Ringwald                             // responder
2721c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
272245a61d50SMatthias Ringwald                         } else {
272345a61d50SMatthias Ringwald                             // initiator
2724c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272545a61d50SMatthias Ringwald                         }
27261979f09cSMatthias Ringwald                         trigger_user_response = true;
272745a61d50SMatthias Ringwald                         break;
272845a61d50SMatthias Ringwald                     case OOB:
272965a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
273065a9a04eSMatthias Ringwald                             // responder
273165a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
273265a9a04eSMatthias Ringwald                         } else {
273365a9a04eSMatthias Ringwald                             // initiator
273465a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
273565a9a04eSMatthias Ringwald                         }
273645a61d50SMatthias Ringwald                         break;
27377bbeb3adSMilanka Ringwald                     default:
27387bbeb3adSMilanka Ringwald                         btstack_assert(false);
27397bbeb3adSMilanka Ringwald                         break;
274045a61d50SMatthias Ringwald                 }
274145a61d50SMatthias Ringwald 
2742687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
274327c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2744644c6a1dSMatthias Ringwald 
2745b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2746644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2747644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2748644c6a1dSMatthias Ringwald                 }
2749b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2750b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2751b90c4e75SMatthias Ringwald                 }
275227c32905SMatthias Ringwald                 break;
275327c32905SMatthias Ringwald             }
2754c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2755e53be891SMatthias Ringwald                 uint8_t buffer[17];
2756e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27579af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
275842134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2759c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2760e53be891SMatthias Ringwald                 } else {
2761c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2762e53be891SMatthias Ringwald                 }
2763687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2764e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2765e53be891SMatthias Ringwald                 break;
2766e53be891SMatthias Ringwald             }
2767c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2768e53be891SMatthias Ringwald                 uint8_t buffer[17];
2769e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2770e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27719d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27724ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
277340c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
277442134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
277545a61d50SMatthias Ringwald                         // responder
2776c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
277745a61d50SMatthias Ringwald                     } else {
277845a61d50SMatthias Ringwald                         // initiator
2779c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
278045a61d50SMatthias Ringwald                     }
278145a61d50SMatthias Ringwald                 } else {
278240c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
278342134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2784e53be891SMatthias Ringwald                         // responder
278547fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
278640c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2787901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27882886623dSMatthias Ringwald                         } else {
278940c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27902886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2791446a8c36SMatthias Ringwald                         }
2792e53be891SMatthias Ringwald                     } else {
2793136d331aSMatthias Ringwald                         // initiator
2794c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2795e53be891SMatthias Ringwald                     }
279645a61d50SMatthias Ringwald                 }
2797687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2798e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2799e53be891SMatthias Ringwald                 break;
2800e53be891SMatthias Ringwald             }
2801c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2802e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2803e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2804e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2805dc300847SMatthias Ringwald 
280642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2807c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2808e53be891SMatthias Ringwald                 } else {
2809c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2810e53be891SMatthias Ringwald                 }
2811e083ca23SMatthias Ringwald 
2812687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2813e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2814e53be891SMatthias Ringwald                 break;
2815e53be891SMatthias Ringwald             }
2816e53be891SMatthias Ringwald 
2817e53be891SMatthias Ringwald #endif
281842134bc6SMatthias Ringwald 
281942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2820dd12a62bSMatthias Ringwald 
282187014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
282287014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
282387014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2824687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2825c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
282687014f74SMatthias Ringwald 				break;
282787014f74SMatthias Ringwald 			}
282887014f74SMatthias Ringwald 
282938196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
283038196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
283138196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
283238196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
283338196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
283438196718SMatthias Ringwald 						// start using context by loading security info
283538196718SMatthias Ringwald 						sm_reset_setup();
283638196718SMatthias Ringwald 						sm_load_security_info(connection);
283738196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
283838196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
283938196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
284042646f38SMatthias Ringwald                             sm_reencryption_started(connection);
284138196718SMatthias Ringwald                             sm_trigger_run();
284238196718SMatthias Ringwald 							break;
284338196718SMatthias Ringwald 						}
284438196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
284538196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
284638196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
284738196718SMatthias Ringwald 						return;
284838196718SMatthias Ringwald 					default:
284938196718SMatthias Ringwald 						// just wait until IRK lookup is completed
285038196718SMatthias Ringwald 						break;
285138196718SMatthias Ringwald 				}
285238196718SMatthias Ringwald 				break;
285338196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
285438196718SMatthias Ringwald 
2855b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2856b6afa23eSMatthias Ringwald                 sm_reset_setup();
28579b75de03SMatthias Ringwald 
28589b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28599b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28609b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28619b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28629b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28639b75de03SMatthias Ringwald                         if (have_ltk){
28649b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
286519a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28669b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28679b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28689b75de03SMatthias Ringwald                         }
28699b75de03SMatthias Ringwald                         break;
28709b75de03SMatthias Ringwald                     default:
28719b75de03SMatthias Ringwald                         break;
28729b75de03SMatthias Ringwald                 }
28739b75de03SMatthias Ringwald 
2874b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2875d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
287639543d07SMatthias Ringwald 
2877b6afa23eSMatthias Ringwald 				// recover pairing request
2878b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2879b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2880b6afa23eSMatthias Ringwald 
2881b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2882b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2883b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2884b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2885b6afa23eSMatthias Ringwald                     }
2886b6afa23eSMatthias Ringwald #endif
28879305033eSMatthias Ringwald 				if (err != 0){
2888f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2889b6afa23eSMatthias Ringwald 					sm_trigger_run();
2890b6afa23eSMatthias Ringwald 					break;
2891b6afa23eSMatthias Ringwald 				}
2892b6afa23eSMatthias Ringwald 
2893b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2894b6afa23eSMatthias Ringwald 
2895b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2896b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2897b6afa23eSMatthias 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);
2898b6afa23eSMatthias Ringwald 					break;
2899b6afa23eSMatthias Ringwald 				}
2900b6afa23eSMatthias Ringwald 
2901b6afa23eSMatthias Ringwald 				/* fall through */
2902b6afa23eSMatthias Ringwald 
29033deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29041ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2905f55bd529SMatthias Ringwald 
2906f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29073deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29081ad129beSMatthias Ringwald 
2909f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2910f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2911f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2912f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2913f55bd529SMatthias Ringwald                 }
2914f55bd529SMatthias Ringwald #endif
2915f55bd529SMatthias Ringwald                 // setup in response
2916f55bd529SMatthias 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);
2917f55bd529SMatthias 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);
2918f55bd529SMatthias Ringwald 
2919f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29209a90d41aSMatthias 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));
2921f55bd529SMatthias Ringwald 
292227c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2923c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29240b8af2a5SMatthias Ringwald                 } else {
29250b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
292627c32905SMatthias Ringwald                 }
29270b8af2a5SMatthias Ringwald 
2928687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29293deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2930446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2931c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29323deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2933446a8c36SMatthias Ringwald                 }
29343deb3ec6SMatthias Ringwald                 return;
293542134bc6SMatthias Ringwald #endif
29363deb3ec6SMatthias Ringwald 
29373deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29383deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29393deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29409c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
294142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29423deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29433deb3ec6SMatthias Ringwald                 } else {
29443deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29453deb3ec6SMatthias Ringwald                 }
2946687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29473deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29483deb3ec6SMatthias Ringwald                 break;
29493deb3ec6SMatthias Ringwald             }
29503deb3ec6SMatthias Ringwald 
2951d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29523deb3ec6SMatthias Ringwald                 // already busy?
29533deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2954d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2955d1a1f6a4SMatthias 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);
2956d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2957d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2958f3582630SMatthias 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);
29593deb3ec6SMatthias Ringwald                 break;
29603deb3ec6SMatthias Ringwald 
29613deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29623deb3ec6SMatthias Ringwald                 // already busy?
29633deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29643deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2965d1a1f6a4SMatthias 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);
2966d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2967d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2968f3582630SMatthias 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);
29693deb3ec6SMatthias Ringwald                 break;
2970d1a1f6a4SMatthias Ringwald 
29713deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29723deb3ec6SMatthias Ringwald                 // already busy?
29733deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29743deb3ec6SMatthias Ringwald                 // calculate STK
297542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2976d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29773deb3ec6SMatthias Ringwald                 } else {
2978d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29793deb3ec6SMatthias Ringwald                 }
2980d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2981d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2982f3582630SMatthias 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);
29833deb3ec6SMatthias Ringwald                 break;
2984d1a1f6a4SMatthias Ringwald 
29853deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29863deb3ec6SMatthias Ringwald                 // already busy?
29873deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29883deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29899ad0dd7cSMatthias Ringwald 
29909ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29919ad0dd7cSMatthias Ringwald                 // r' = padding || r
29929ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29939ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29946535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29959ad0dd7cSMatthias Ringwald 
29963deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2997d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2998d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2999f3582630SMatthias 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);
3000d1a1f6a4SMatthias Ringwald                 break;
3001d1a1f6a4SMatthias Ringwald 
30023deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30033deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30043deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30059c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
300642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30073deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30083deb3ec6SMatthias Ringwald                 } else {
30093deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30103deb3ec6SMatthias Ringwald                 }
3011687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30123deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30133deb3ec6SMatthias Ringwald                 return;
30143deb3ec6SMatthias Ringwald             }
301542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30163deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30173deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30189c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30193deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30203deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30213deb3ec6SMatthias Ringwald                 return;
30223deb3ec6SMatthias Ringwald             }
3023d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3024b96d60a6SMatthias Ringwald                 // allow to override LTK
3025b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3026b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3027b96d60a6SMatthias Ringwald                 }
30283deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30299c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30305567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30313deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30323deb3ec6SMatthias Ringwald                 return;
30333deb3ec6SMatthias Ringwald             }
3034dd12a62bSMatthias Ringwald 
3035dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30363deb3ec6SMatthias Ringwald                 // already busy?
30373deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30383deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3039c61cfe5aSMatthias Ringwald 
3040dd12a62bSMatthias Ringwald 				sm_reset_setup();
3041dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3042dd12a62bSMatthias Ringwald 
304342646f38SMatthias Ringwald 				sm_reencryption_started(connection);
304442646f38SMatthias Ringwald 
3045c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3046c61cfe5aSMatthias Ringwald                 // r' = padding || r
3047c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3048c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30496535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3050c61cfe5aSMatthias Ringwald 
30513deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3052d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3053d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3054f3582630SMatthias 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);
30553deb3ec6SMatthias Ringwald                 return;
305642134bc6SMatthias Ringwald #endif
305742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
305842134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
305942134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
306042134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
306142134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
306242134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
306342134bc6SMatthias Ringwald                 return;
306442134bc6SMatthias Ringwald             }
306542134bc6SMatthias Ringwald #endif
30663deb3ec6SMatthias Ringwald 
30673deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3068403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3069403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30703deb3ec6SMatthias Ringwald                     return;
30713deb3ec6SMatthias Ringwald                 }
30723deb3ec6SMatthias Ringwald 
30733deb3ec6SMatthias Ringwald                 // keys are sent
307442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30753deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
307661d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30773deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3078f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3079f5020412SMatthias Ringwald                         // start CTKD right away
3080f5020412SMatthias Ringwald                         continue;
30813deb3ec6SMatthias Ringwald                     } else {
30823deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30833deb3ec6SMatthias Ringwald                     }
30843deb3ec6SMatthias Ringwald                 } else {
30851dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30863deb3ec6SMatthias Ringwald                 }
30873deb3ec6SMatthias Ringwald                 break;
30883deb3ec6SMatthias Ringwald 
3089c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3090c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3091c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3092c18be159SMatthias Ringwald                 sm_reset_setup();
3093c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3094c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3095c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3096c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3097c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3098c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3099c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3100c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3101c18be159SMatthias Ringwald 
3102c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3103c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3104c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3105c18be159SMatthias Ringwald                 // Plus signing key if supported
3106c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3107c18be159SMatthias Ringwald #endif
3108c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3109c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3110c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3111c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3112c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3113c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3114c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3115c18be159SMatthias Ringwald 
3116c18be159SMatthias Ringwald                 // set state and send pairing response
3117c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3118c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3119c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3120c18be159SMatthias Ringwald                 break;
3121c18be159SMatthias Ringwald 
3122c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3123c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3124c18be159SMatthias Ringwald                 sm_reset_setup();
3125c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3126c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3127c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3128c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3129c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3130c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3131c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3132c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3133c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3134c18be159SMatthias Ringwald 
3135c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3136c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3137c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3138c18be159SMatthias Ringwald                 // Plus signing key if supported
3139c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3140c18be159SMatthias Ringwald #endif
3141c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3142c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3143c18be159SMatthias Ringwald 
3144c18be159SMatthias 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:
3145c18be159SMatthias Ringwald                 // - the IO Capability field,
3146c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3147c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3148c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3149c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3150c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3151c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3152c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3153c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3154c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3155c18be159SMatthias Ringwald 
3156c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3157c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3158c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3159c18be159SMatthias Ringwald 
3160c18be159SMatthias Ringwald                 // set state and send pairing response
3161c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3162c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3163c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3164c18be159SMatthias Ringwald                 break;
3165c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3166c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3167c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3168c18be159SMatthias Ringwald                     return;
3169c18be159SMatthias Ringwald                 }
3170c18be159SMatthias Ringwald                 // keys are sent
3171c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3172c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
317361d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3174c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3175c18be159SMatthias Ringwald                         break;
3176c18be159SMatthias Ringwald                     }
3177c18be159SMatthias Ringwald                 }
3178c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3179c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3180c18be159SMatthias Ringwald                 continue;
3181c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3182c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3183c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3184c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3185c18be159SMatthias Ringwald                 break;
3186c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3187c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3188c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3189c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3190c18be159SMatthias Ringwald                 break;
3191c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3192c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3193c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3194c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3195c18be159SMatthias Ringwald                 break;
3196c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3197c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3198c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3199c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3200c18be159SMatthias Ringwald                 break;
3201c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3202c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3203c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3204c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3205c18be159SMatthias Ringwald                 break;
3206c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3207c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3208c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3209c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3210c18be159SMatthias Ringwald                 break;
3211c18be159SMatthias Ringwald #endif
3212c18be159SMatthias Ringwald 
32133deb3ec6SMatthias Ringwald             default:
32143deb3ec6SMatthias Ringwald                 break;
32153deb3ec6SMatthias Ringwald         }
32163deb3ec6SMatthias Ringwald 
32173deb3ec6SMatthias Ringwald         // check again if active connection was released
32187149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32193deb3ec6SMatthias Ringwald     }
32203deb3ec6SMatthias Ringwald }
32213deb3ec6SMatthias Ringwald 
3222d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3223d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3224f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322604678764SMatthias Ringwald 
3227f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3228f3582630SMatthias Ringwald     if (connection == NULL) return;
3229f3582630SMatthias Ringwald 
3230d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
323104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3232f3582630SMatthias 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);
3233d1a1f6a4SMatthias Ringwald }
32343deb3ec6SMatthias Ringwald 
3235d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3236f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323804678764SMatthias Ringwald 
3239f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3240f3582630SMatthias Ringwald     if (connection == NULL) return;
3241f3582630SMatthias Ringwald 
32428314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32433deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
324470b44dd4SMatthias Ringwald     sm_trigger_run();
3245d1a1f6a4SMatthias Ringwald }
3246d1a1f6a4SMatthias Ringwald 
3247d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3248d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3249f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
325004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325104678764SMatthias Ringwald 
3252f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3253f3582630SMatthias Ringwald     if (connection == NULL) return;
3254f3582630SMatthias Ringwald 
3255d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
325604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3257f3582630SMatthias 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);
3258d1a1f6a4SMatthias Ringwald }
3259d1a1f6a4SMatthias Ringwald 
3260d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3261f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
326204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326304678764SMatthias Ringwald 
3264f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3265f3582630SMatthias Ringwald     if (connection == NULL) return;
3266f3582630SMatthias Ringwald 
3267d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3268d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3269f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
327070b44dd4SMatthias Ringwald         sm_trigger_run();
32713deb3ec6SMatthias Ringwald         return;
32723deb3ec6SMatthias Ringwald     }
327342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32743deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
327570b44dd4SMatthias Ringwald         sm_trigger_run();
32763deb3ec6SMatthias Ringwald     } else {
3277d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3278d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3279f3582630SMatthias 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);
32803deb3ec6SMatthias Ringwald     }
32813deb3ec6SMatthias Ringwald }
3282d1a1f6a4SMatthias Ringwald 
3283d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
328404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3285f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
328604678764SMatthias Ringwald 
3287f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3288f3582630SMatthias Ringwald     if (connection == NULL) return;
3289f3582630SMatthias Ringwald 
32903deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32918314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
329242134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32933deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
32943deb3ec6SMatthias Ringwald     } else {
32953deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
32963deb3ec6SMatthias Ringwald     }
329770b44dd4SMatthias Ringwald     sm_trigger_run();
3298d1a1f6a4SMatthias Ringwald }
3299d1a1f6a4SMatthias Ringwald 
3300d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3301d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3302f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
330304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
330404678764SMatthias Ringwald 
3305f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3306f3582630SMatthias Ringwald     if (connection == NULL) return;
3307f3582630SMatthias Ringwald 
3308d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33093deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33103deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33113deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33123deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33133deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33143deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3315d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
331604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3317f3582630SMatthias 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);
33183deb3ec6SMatthias Ringwald }
3319d1a1f6a4SMatthias Ringwald 
33202a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3321d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3322d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
332304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3324f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
332504678764SMatthias Ringwald 
3326f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3327f3582630SMatthias Ringwald     if (connection == NULL) return;
3328f3582630SMatthias Ringwald 
3329d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33303deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33313deb3ec6SMatthias Ringwald 
33323deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33333deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33343deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33353deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33363deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3337d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
333804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3339f3582630SMatthias 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);
33403deb3ec6SMatthias Ringwald }
33412a526f21SMatthias Ringwald #endif
3342d1a1f6a4SMatthias Ringwald 
3343d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3344d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3345f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
334604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
334704678764SMatthias Ringwald 
3348f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3349f3582630SMatthias Ringwald     if (connection == NULL) return;
3350f3582630SMatthias Ringwald 
33518314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33523deb3ec6SMatthias Ringwald     // calc CSRK next
3353d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
335404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3355f3582630SMatthias 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);
3356d1a1f6a4SMatthias Ringwald }
3357d1a1f6a4SMatthias Ringwald 
3358d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3359f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
336004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
336104678764SMatthias Ringwald 
3362f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3363f3582630SMatthias Ringwald     if (connection == NULL) return;
3364f3582630SMatthias Ringwald 
3365d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33668314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33673deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33683deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33693deb3ec6SMatthias Ringwald     } else {
33703deb3ec6SMatthias Ringwald         // no keys to send, just continue
337142134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
337261d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3373c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3374c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3375c5a72e35SMatthias Ringwald             } else {
33763deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33773deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3378c5a72e35SMatthias Ringwald             }
33793deb3ec6SMatthias Ringwald         } else {
3380af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33813deb3ec6SMatthias Ringwald         }
33822bacf595SMatthias Ringwald     }
338370b44dd4SMatthias Ringwald     sm_trigger_run();
3384d1a1f6a4SMatthias Ringwald }
3385d1a1f6a4SMatthias Ringwald 
338642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3387d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3388f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
338904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339004678764SMatthias Ringwald 
3391f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3392f3582630SMatthias Ringwald     if (connection == NULL) return;
3393f3582630SMatthias Ringwald 
33943deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33958314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3396d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
339770b44dd4SMatthias Ringwald     sm_trigger_run();
3398d1a1f6a4SMatthias Ringwald }
3399d1a1f6a4SMatthias Ringwald #endif
3400d1a1f6a4SMatthias Ringwald 
3401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3402d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3403d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
340404678764SMatthias Ringwald 
3405d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3406d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3407d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3408d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3409d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3410a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
341170b44dd4SMatthias Ringwald         sm_trigger_run();
34123deb3ec6SMatthias Ringwald         return;
34133deb3ec6SMatthias Ringwald     }
3414d1a1f6a4SMatthias Ringwald     // no match, try next
3415d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
341670b44dd4SMatthias Ringwald     sm_trigger_run();
34173deb3ec6SMatthias Ringwald }
34183deb3ec6SMatthias Ringwald 
3419d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3420d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3421d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342204678764SMatthias Ringwald 
3423d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3424d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
342570b44dd4SMatthias Ringwald     sm_trigger_run();
34267df18c15SMatthias Ringwald }
3427d1a1f6a4SMatthias Ringwald 
3428d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3429d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3430d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
343104678764SMatthias Ringwald 
3432d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3433d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
343470b44dd4SMatthias Ringwald     sm_trigger_run();
34357df18c15SMatthias Ringwald }
3436d1a1f6a4SMatthias Ringwald 
3437d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3438d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3439d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
344004678764SMatthias Ringwald 
34416535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3442e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3443e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3444e91ddb40SMatthias Ringwald 
344570b44dd4SMatthias Ringwald     sm_trigger_run();
344651fa0b28SMatthias Ringwald }
34477df18c15SMatthias Ringwald 
3448d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3449d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34503deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34513deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34523deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34533deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34543deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34554ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34564ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34573deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34583deb3ec6SMatthias Ringwald             break;
34593deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34603deb3ec6SMatthias Ringwald         default:
34613deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34624ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
3463e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
34643deb3ec6SMatthias Ringwald             break;
34653deb3ec6SMatthias Ringwald     }
346670b44dd4SMatthias Ringwald     sm_trigger_run();
34673deb3ec6SMatthias Ringwald }
34683deb3ec6SMatthias Ringwald 
3469c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34706ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3471f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3472f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3473f3582630SMatthias Ringwald     if (connection == NULL) return;
3474c59d0c92SMatthias Ringwald 
347565a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
347670b44dd4SMatthias Ringwald     sm_trigger_run();
347765a9a04eSMatthias Ringwald }
3478d1a1f6a4SMatthias Ringwald 
34796ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34806ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34816ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34826ca80073SMatthias Ringwald     if (connection == NULL) return;
34836ca80073SMatthias Ringwald 
3484b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
348570b44dd4SMatthias Ringwald     sm_trigger_run();
3486d1a1f6a4SMatthias Ringwald }
3487f1c1783eSMatthias Ringwald #endif
3488f1c1783eSMatthias Ringwald 
3489d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3490f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3491f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3492f3582630SMatthias Ringwald     if (connection == NULL) return;
3493f3582630SMatthias Ringwald 
3494d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
349570b44dd4SMatthias Ringwald     sm_trigger_run();
3496d1a1f6a4SMatthias Ringwald }
3497d1a1f6a4SMatthias Ringwald 
3498d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3499f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3500f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3501f3582630SMatthias Ringwald     if (connection == NULL) return;
3502f3582630SMatthias Ringwald 
3503caf15bf3SMatthias Ringwald     sm_reset_tk();
3504caf15bf3SMatthias Ringwald     uint32_t tk;
35055ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
35063deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3507d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
35083deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35094ea43905SMatthias Ringwald         if (tk >= 999999u){
35104ea43905SMatthias Ringwald             tk = tk - 999999u;
35113deb3ec6SMatthias Ringwald         }
3512caf15bf3SMatthias Ringwald     } else {
3513caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35144b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3515caf15bf3SMatthias Ringwald     }
3516f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
351742134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35183deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35193deb3ec6SMatthias Ringwald     } else {
3520b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3521b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3522b41539d5SMatthias Ringwald         } else {
35233deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35243deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35253deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35263deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3527f3582630SMatthias 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);
35283deb3ec6SMatthias Ringwald             }
35293deb3ec6SMatthias Ringwald         }
3530b41539d5SMatthias Ringwald     }
353170b44dd4SMatthias Ringwald     sm_trigger_run();
35323deb3ec6SMatthias Ringwald }
3533d1a1f6a4SMatthias Ringwald 
3534d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3535f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3536f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3537f3582630SMatthias Ringwald     if (connection == NULL) return;
3538f3582630SMatthias Ringwald 
3539d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3540d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3541d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3542d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
354370b44dd4SMatthias Ringwald     sm_trigger_run();
3544d1a1f6a4SMatthias Ringwald }
3545d1a1f6a4SMatthias Ringwald 
3546d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3547f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3548f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3549f3582630SMatthias Ringwald     if (connection == NULL) return;
3550f3582630SMatthias Ringwald 
3551d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35523deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35534ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35543deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35554ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35568b3ffec5SMatthias 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);
35573deb3ec6SMatthias Ringwald }
3558899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3559899e6e02SMatthias Ringwald     // warn about default ER/IR
35601979f09cSMatthias Ringwald     bool warning = false;
3561899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35621979f09cSMatthias Ringwald         warning = true;
3563899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3564899e6e02SMatthias Ringwald     }
3565899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35661979f09cSMatthias Ringwald         warning = true;
3567899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3568899e6e02SMatthias Ringwald     }
356921045273SMatthias Ringwald     if (warning) {
3570899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3571899e6e02SMatthias Ringwald     }
357221045273SMatthias Ringwald }
3573899e6e02SMatthias Ringwald 
3574899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35751979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35769305033eSMatthias Ringwald     if (arg != NULL){
3577899e6e02SMatthias Ringwald         // key generated, store in tlv
35784ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3579899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3580e0d13a19SMilanka Ringwald         UNUSED(status);
3581899e6e02SMatthias Ringwald     }
3582899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35838d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3584841468bbSMatthias Ringwald 
3585841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3586841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3587841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3588841468bbSMatthias Ringwald     }
3589841468bbSMatthias Ringwald 
359070b44dd4SMatthias Ringwald     sm_trigger_run();
3591899e6e02SMatthias Ringwald }
3592899e6e02SMatthias Ringwald 
3593899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
35941979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35959305033eSMatthias Ringwald     if (arg != 0){
3596899e6e02SMatthias Ringwald         // key generated, store in tlv
35974ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3598899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3599e0d13a19SMilanka Ringwald         UNUSED(status);
3600899e6e02SMatthias Ringwald     }
3601899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3602899e6e02SMatthias Ringwald 
3603899e6e02SMatthias Ringwald     // try load ir
36044ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3605899e6e02SMatthias Ringwald     if (key_size == 16){
3606899e6e02SMatthias Ringwald         // ok, let's continue
3607899e6e02SMatthias Ringwald         log_info("IR from TLV");
3608899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3609899e6e02SMatthias Ringwald     } else {
3610899e6e02SMatthias Ringwald         // invalid, generate new random one
36111979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3612899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3613899e6e02SMatthias Ringwald     }
3614899e6e02SMatthias Ringwald }
36153deb3ec6SMatthias Ringwald 
3616f664b5e8SMatthias 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){
3617f664b5e8SMatthias Ringwald 
3618f664b5e8SMatthias Ringwald     // connection info
3619f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3620f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3621f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3622f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3623f664b5e8SMatthias Ringwald 
3624f664b5e8SMatthias Ringwald     // security properties
3625f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3626f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3627f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3628f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3629f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3630f664b5e8SMatthias Ringwald 
3631f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3632f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3633f664b5e8SMatthias Ringwald 
3634f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3635f664b5e8SMatthias Ringwald }
3636f664b5e8SMatthias Ringwald 
3637d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36383deb3ec6SMatthias Ringwald 
3639cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3640cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36419ec2630cSMatthias Ringwald 
36423deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3643711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3644fbe050beSMatthias Ringwald     uint8_t           status;
3645f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3646f664b5e8SMatthias Ringwald 
36473deb3ec6SMatthias Ringwald     switch (packet_type) {
36483deb3ec6SMatthias Ringwald 
36493deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36500e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36513deb3ec6SMatthias Ringwald 
36523deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
36533deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3654be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
36553deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3656899e6e02SMatthias Ringwald 
3657899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3658899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36599305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
36604ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3661899e6e02SMatthias Ringwald                             if (key_size == 16){
3662899e6e02SMatthias Ringwald                                 // ok, let's continue
3663899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3664899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3665899e6e02SMatthias Ringwald                             } else {
3666899e6e02SMatthias Ringwald                                 // invalid, generate random one
36671979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3668899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3669899e6e02SMatthias Ringwald                             }
3670899e6e02SMatthias Ringwald                         } else {
3671899e6e02SMatthias Ringwald                             sm_validate_er_ir();
36728d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3673841468bbSMatthias Ringwald 
3674841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3675841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3676841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3677841468bbSMatthias Ringwald                             }
3678899e6e02SMatthias Ringwald                         }
36791bf086daSMatthias Ringwald 
36801bf086daSMatthias Ringwald                         // restart random address updates after power cycle
36811bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
36823deb3ec6SMatthias Ringwald 					}
36833deb3ec6SMatthias Ringwald 					break;
3684c18be159SMatthias Ringwald 
36852d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
36862d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
36872d095694SMatthias Ringwald 			        // ignore if connection failed
36882d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
36893deb3ec6SMatthias Ringwald 
36902d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
36912d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
36922d095694SMatthias Ringwald 			        if (!sm_conn) break;
36932d095694SMatthias Ringwald 
36942d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
36952d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
36962d095694SMatthias Ringwald                                        con_handle,
36972d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3698f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
36992d095694SMatthias Ringwald                                        addr);
37002d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
37012d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
37022d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
37032d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3704c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
37052d095694SMatthias Ringwald 			        break;
37062d095694SMatthias Ringwald #endif
3707c18be159SMatthias Ringwald 
3708c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3709c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3710c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3711c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3712c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3713c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3714c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3715c18be159SMatthias Ringwald 			        break;
3716c18be159SMatthias Ringwald #endif
3717c18be159SMatthias Ringwald 
37183deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37193deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37203deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3721f664b5e8SMatthias Ringwald                             // ignore if connection failed
3722f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37233deb3ec6SMatthias Ringwald 
3724711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3725711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37263deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37273deb3ec6SMatthias Ringwald 
3728f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3729f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3730f664b5e8SMatthias Ringwald                                                con_handle,
3731f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3732f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3733f664b5e8SMatthias Ringwald                                                addr);
3734687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3735f664b5e8SMatthias Ringwald 
3736f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3737b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3738b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3739ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3740ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3741f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3742b892db1cSMatthias Ringwald                             }
3743b892db1cSMatthias Ringwald #endif
3744b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3745b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3746ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3747ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37483deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37493deb3ec6SMatthias Ringwald                             }
3750b892db1cSMatthias Ringwald #endif
37513deb3ec6SMatthias Ringwald                             break;
37523deb3ec6SMatthias Ringwald 
37533deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3754711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3755711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37563deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37573deb3ec6SMatthias Ringwald 
37583deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37593deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37603deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37613deb3ec6SMatthias Ringwald                                 break;
37623deb3ec6SMatthias Ringwald                             }
3763c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3764778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3765778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3766e53be891SMatthias Ringwald                                 break;
3767e53be891SMatthias Ringwald                             }
37683deb3ec6SMatthias Ringwald 
37693deb3ec6SMatthias Ringwald                             // store rand and ediv
37709c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3771f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3772549ad5d2SMatthias Ringwald 
3773549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3774549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37754ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37766c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
377706cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3778549ad5d2SMatthias Ringwald                                     break;
3779549ad5d2SMatthias Ringwald                                 }
37806c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37816c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37826c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37836c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37846c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
37856c39055aSMatthias Ringwald                                         break;
37866c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
37876c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
37886c39055aSMatthias Ringwald                                         break;
37896c39055aSMatthias Ringwald                                     default:
37906c39055aSMatthias Ringwald                                         // wait for irk look doen
37916c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
37926c39055aSMatthias Ringwald                                         break;
37936c39055aSMatthias Ringwald                                 }
37946c39055aSMatthias Ringwald                                 break;
37956c39055aSMatthias Ringwald                             }
3796549ad5d2SMatthias Ringwald 
3797549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
379806cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3799549ad5d2SMatthias Ringwald #else
3800549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3801549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3802549ad5d2SMatthias Ringwald #endif
38033deb3ec6SMatthias Ringwald                             break;
3804804d3e67SMatthias Ringwald 
38053deb3ec6SMatthias Ringwald                         default:
38063deb3ec6SMatthias Ringwald                             break;
38073deb3ec6SMatthias Ringwald                     }
38083deb3ec6SMatthias Ringwald                     break;
38093deb3ec6SMatthias Ringwald 
38103deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
38113b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3812711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38133deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38143deb3ec6SMatthias Ringwald 
38153b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38163deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38173deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38183deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
381903a9359aSMatthias Ringwald 
3820fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3821fbe050beSMatthias Ringwald 
38225567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
382303a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3824fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3825fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38268d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38278d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38288d4eef95SMatthias Ringwald                                 } else {
382903a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38308d4eef95SMatthias Ringwald                                 }
3831fbe050beSMatthias Ringwald                             } else {
3832e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3833cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38343b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3835cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38363b7fd749SMatthias Ringwald                             }
3837fbe050beSMatthias Ringwald 
3838fbe050beSMatthias Ringwald                             // emit re-encryption complete
383973102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3840fbe050beSMatthias Ringwald 
3841c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3842c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3843c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38440ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
384503a9359aSMatthias Ringwald                             }
384603a9359aSMatthias Ringwald 
38473deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38483deb3ec6SMatthias Ringwald                             break;
3849fbe050beSMatthias Ringwald 
38503deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3851fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3852dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
385342134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38543deb3ec6SMatthias Ringwald                                 // slave
3855bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3856bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3857bbf8db22SMatthias Ringwald                                 } else {
3858f3582630SMatthias 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);
3859bbf8db22SMatthias Ringwald                                 }
38603deb3ec6SMatthias Ringwald                             } else {
38613deb3ec6SMatthias Ringwald                                 // master
386261d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38633deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38643deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3865f3582630SMatthias 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);
38663deb3ec6SMatthias Ringwald                                 } else {
38673deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38683deb3ec6SMatthias Ringwald                                 }
38693deb3ec6SMatthias Ringwald                             }
38703deb3ec6SMatthias Ringwald                             break;
3871c18be159SMatthias Ringwald 
3872c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3873c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3874c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3875c18be159SMatthias Ringwald                             // prepare for pairing request
3876c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3877c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3878c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3879c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3880c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3881c18be159SMatthias Ringwald                             }
3882c18be159SMatthias Ringwald                             break;
3883c18be159SMatthias Ringwald #endif
38843deb3ec6SMatthias Ringwald                         default:
38853deb3ec6SMatthias Ringwald                             break;
38863deb3ec6SMatthias Ringwald                     }
38873deb3ec6SMatthias Ringwald                     break;
38883deb3ec6SMatthias Ringwald 
38893deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3890711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3891711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38923deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38933deb3ec6SMatthias Ringwald 
38943deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
38953deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
38963deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
38973deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
38985567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
38995567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
39005567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39015567aa60SMatthias Ringwald                             } else {
39023deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39035567aa60SMatthias Ringwald                             }
39043deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39053deb3ec6SMatthias Ringwald                             break;
39063deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
390742134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39083deb3ec6SMatthias Ringwald                                 // slave
3909f3582630SMatthias 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);
39103deb3ec6SMatthias Ringwald                             } else {
39113deb3ec6SMatthias Ringwald                                 // master
39123deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39133deb3ec6SMatthias Ringwald                             }
39143deb3ec6SMatthias Ringwald                             break;
39153deb3ec6SMatthias Ringwald                         default:
39163deb3ec6SMatthias Ringwald                             break;
39173deb3ec6SMatthias Ringwald                     }
39183deb3ec6SMatthias Ringwald                     break;
39193deb3ec6SMatthias Ringwald 
39203deb3ec6SMatthias Ringwald 
39213deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3922711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3923711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3924711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39253deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39263deb3ec6SMatthias Ringwald 
392703f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39287f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39297f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39307f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39317f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39327f3f442dSMatthias Ringwald                             break;
39337f3f442dSMatthias Ringwald                         default:
393468a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39350ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39367f3f442dSMatthias Ringwald                             break;
393703f736b1SMatthias Ringwald                     }
3938accbde80SMatthias Ringwald 
39393deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39403deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39413deb3ec6SMatthias Ringwald                     break;
39423deb3ec6SMatthias Ringwald 
39433deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
394433373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
39459091c5f5SMatthias Ringwald                         // set local addr for le device db
394633373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39470c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
394833373e40SMatthias Ringwald                     }
394965b44ffdSMatthias Ringwald                     break;
395065b44ffdSMatthias Ringwald                 default:
395165b44ffdSMatthias Ringwald                     break;
39523deb3ec6SMatthias Ringwald 			}
395365b44ffdSMatthias Ringwald             break;
395465b44ffdSMatthias Ringwald         default:
395565b44ffdSMatthias Ringwald             break;
39563deb3ec6SMatthias Ringwald 	}
39573deb3ec6SMatthias Ringwald 
39583deb3ec6SMatthias Ringwald     sm_run();
39593deb3ec6SMatthias Ringwald }
39603deb3ec6SMatthias Ringwald 
39613deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39623deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39633deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39643deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39653deb3ec6SMatthias Ringwald }
39663deb3ec6SMatthias Ringwald 
3967945888f5SMatthias Ringwald 
396831c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3969945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3970945888f5SMatthias Ringwald     switch (method){
3971945888f5SMatthias Ringwald         case JUST_WORKS:
397247fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3973945888f5SMatthias Ringwald             return 1;
3974945888f5SMatthias Ringwald         default:
3975945888f5SMatthias Ringwald             return 0;
3976945888f5SMatthias Ringwald     }
3977945888f5SMatthias Ringwald }
397807036a04SMatthias Ringwald // responder
3979945888f5SMatthias Ringwald 
3980688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3981688a08f9SMatthias Ringwald     switch (method){
3982688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3983688a08f9SMatthias Ringwald             return 1;
3984688a08f9SMatthias Ringwald         default:
3985688a08f9SMatthias Ringwald             return 0;
3986688a08f9SMatthias Ringwald     }
3987688a08f9SMatthias Ringwald }
398840c5d850SMatthias Ringwald 
398940c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
399040c5d850SMatthias Ringwald     switch (method){
399140c5d850SMatthias Ringwald         case PK_RESP_INPUT:
399240c5d850SMatthias Ringwald         case PK_INIT_INPUT:
399347fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
399440c5d850SMatthias Ringwald             return 1;
399540c5d850SMatthias Ringwald         default:
399640c5d850SMatthias Ringwald             return 0;
399740c5d850SMatthias Ringwald     }
399840c5d850SMatthias Ringwald }
399940c5d850SMatthias Ringwald 
400031c09488SMatthias Ringwald #endif
4001688a08f9SMatthias Ringwald 
40023deb3ec6SMatthias Ringwald /**
40033deb3ec6SMatthias Ringwald  * @return ok
40043deb3ec6SMatthias Ringwald  */
40053deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
40063deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
40073deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
40083deb3ec6SMatthias Ringwald         case JUST_WORKS:
40094ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
40103deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
40113deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
401247fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
40134ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
40143deb3ec6SMatthias Ringwald         case OOB:
40154ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
401647fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40174ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40183deb3ec6SMatthias Ringwald         default:
40193deb3ec6SMatthias Ringwald             return 0;
40203deb3ec6SMatthias Ringwald     }
40213deb3ec6SMatthias Ringwald }
40223deb3ec6SMatthias Ringwald 
402336f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
402436f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
402536f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
402636f0defaSMatthias Ringwald     if (sm_sc_only_mode){
402736f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
402836f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
402936f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
403036f0defaSMatthias Ringwald             return;
403136f0defaSMatthias Ringwald         }
403236f0defaSMatthias Ringwald     }
403336f0defaSMatthias Ringwald #else
403436f0defaSMatthias Ringwald     UNUSED(packet);
403536f0defaSMatthias Ringwald #endif
403636f0defaSMatthias Ringwald 
403736f0defaSMatthias Ringwald     int have_ltk;
403836f0defaSMatthias Ringwald     uint8_t ltk[16];
403936f0defaSMatthias Ringwald 
404036f0defaSMatthias Ringwald     // IRK complete?
404136f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
404236f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
404336f0defaSMatthias Ringwald             // start pairing
404436f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
404536f0defaSMatthias Ringwald             break;
404636f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
404736f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
404836f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
404936f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
405036f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
405136f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
405236f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
405336f0defaSMatthias Ringwald             } else {
405436f0defaSMatthias Ringwald                 // start pairing
405536f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
405636f0defaSMatthias Ringwald             }
405736f0defaSMatthias Ringwald             break;
405836f0defaSMatthias Ringwald         default:
405936f0defaSMatthias Ringwald             // otherwise, store security request
406036f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
406136f0defaSMatthias Ringwald             break;
406236f0defaSMatthias Ringwald     }
406336f0defaSMatthias Ringwald }
406436f0defaSMatthias Ringwald #endif
406536f0defaSMatthias Ringwald 
40668334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40678334d3d8SMatthias Ringwald 
40684c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40694c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40704c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40714c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40724c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40734c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40744c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40754c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40764c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40777a2e6387SMatthias Ringwald             11, // 0x07 master identification
40784c1d1092SMatthias Ringwald             17, // 0x08 identification information
40794c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40804c1d1092SMatthias Ringwald             17, // 0x0a signing information
40814c1d1092SMatthias Ringwald             2,  // 0x0b security request
40824c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40834c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40844c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
40854c1d1092SMatthias Ringwald     };
40863deb3ec6SMatthias Ringwald 
4087c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4088b170b20fSMatthias Ringwald         sm_run();
4089b170b20fSMatthias Ringwald     }
4090b170b20fSMatthias Ringwald 
40913deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
40924ea43905SMatthias Ringwald     if (size == 0u) return;
40934c1d1092SMatthias Ringwald 
40944c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
40954c1d1092SMatthias Ringwald 
40964c1d1092SMatthias Ringwald     // validate pdu size
40974c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
40987a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
40993deb3ec6SMatthias Ringwald 
4100711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
41013deb3ec6SMatthias Ringwald     if (!sm_conn) return;
41023deb3ec6SMatthias Ringwald 
41034c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
410468a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
41050ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4106accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
41073deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
41083deb3ec6SMatthias Ringwald         return;
41093deb3ec6SMatthias Ringwald     }
41103deb3ec6SMatthias Ringwald 
41114c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
41123deb3ec6SMatthias Ringwald 
41133deb3ec6SMatthias Ringwald     int err;
411442134bc6SMatthias Ringwald     UNUSED(err);
41153deb3ec6SMatthias Ringwald 
41164c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
41173d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
41183d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
41193d7fe1e9SMatthias Ringwald         buffer[1] = 3;
41203d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
41213d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
41223d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
41233d7fe1e9SMatthias Ringwald         return;
41243d7fe1e9SMatthias Ringwald     }
41253d7fe1e9SMatthias Ringwald 
41263deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
41273deb3ec6SMatthias Ringwald 
4128c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
41293deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
41303deb3ec6SMatthias Ringwald             return;
41313deb3ec6SMatthias Ringwald 
413242134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
413342134bc6SMatthias Ringwald 
41343deb3ec6SMatthias Ringwald         // Initiator
41353deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
41364c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
41373deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41383deb3ec6SMatthias Ringwald                 break;
41393deb3ec6SMatthias Ringwald             }
414036f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4141dc8ca372SMatthias Ringwald             break;
41423deb3ec6SMatthias Ringwald 
41433deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4144aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4145aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4146aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4147aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4148aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4149aacfafc3SMatthias Ringwald                 break;
4150aacfafc3SMatthias Ringwald             }
4151aacfafc3SMatthias Ringwald 
4152aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41534c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41543deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41553deb3ec6SMatthias Ringwald                 break;
41563deb3ec6SMatthias Ringwald             }
41570af429c6SMatthias Ringwald 
41583deb3ec6SMatthias Ringwald             // store pairing request
41596535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41606535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41613deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41620af429c6SMatthias Ringwald 
41630af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41640af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41650af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41660af429c6SMatthias Ringwald                 err = test_pairing_failure;
41670af429c6SMatthias Ringwald             }
41680af429c6SMatthias Ringwald #endif
41690af429c6SMatthias Ringwald 
41709305033eSMatthias Ringwald             if (err != 0){
4171f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41723deb3ec6SMatthias Ringwald                 break;
41733deb3ec6SMatthias Ringwald             }
4174b41539d5SMatthias Ringwald 
4175b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4176b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4177f3582630SMatthias 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);
4178b41539d5SMatthias Ringwald                 break;
4179b41539d5SMatthias Ringwald             }
4180b41539d5SMatthias Ringwald 
4181136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4182136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41838cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41848cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4185136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4186136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4187136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4188c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4189136d331aSMatthias Ringwald                     }
41908cba5ca3SMatthias Ringwald                 } else {
4191c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
41928cba5ca3SMatthias Ringwald                 }
4193136d331aSMatthias Ringwald                 break;
4194136d331aSMatthias Ringwald             }
4195136d331aSMatthias Ringwald #endif
41963deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
41973deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
41983deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
41993deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4200f3582630SMatthias 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);
42013deb3ec6SMatthias Ringwald             }
42023deb3ec6SMatthias Ringwald             break;
42033deb3ec6SMatthias Ringwald 
42043deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
42054c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42063deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42073deb3ec6SMatthias Ringwald                 break;
42083deb3ec6SMatthias Ringwald             }
42093deb3ec6SMatthias Ringwald 
42103deb3ec6SMatthias Ringwald             // store s_confirm
42119c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4212192365feSMatthias Ringwald 
4213aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4214aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4215aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4216aa9b34e5SMatthias Ringwald                 break;
4217aa9b34e5SMatthias Ringwald             }
4218aa9b34e5SMatthias Ringwald 
4219192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4220192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4221192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4222192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4223192365feSMatthias Ringwald             }
4224192365feSMatthias Ringwald #endif
42253deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42263deb3ec6SMatthias Ringwald             break;
42273deb3ec6SMatthias Ringwald 
42283deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42294c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42303deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42313deb3ec6SMatthias Ringwald                 break;;
42323deb3ec6SMatthias Ringwald             }
42333deb3ec6SMatthias Ringwald 
42343deb3ec6SMatthias Ringwald             // received random value
42359c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42363deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42373deb3ec6SMatthias Ringwald             break;
423842134bc6SMatthias Ringwald #endif
42393deb3ec6SMatthias Ringwald 
424042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42413deb3ec6SMatthias Ringwald         // Responder
42423deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42433deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42443deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42454c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42463deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42473deb3ec6SMatthias Ringwald                 break;;
42483deb3ec6SMatthias Ringwald             }
42493deb3ec6SMatthias Ringwald 
42503deb3ec6SMatthias Ringwald             // store pairing request
4251212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4252212d735eSMatthias Ringwald 
4253212d735eSMatthias Ringwald             // check if IRK completed
4254212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4255212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4256212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42573deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42583deb3ec6SMatthias Ringwald                     break;
4259212d735eSMatthias Ringwald                 default:
4260212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4261212d735eSMatthias Ringwald                     break;
4262212d735eSMatthias Ringwald             }
4263212d735eSMatthias Ringwald             break;
426442134bc6SMatthias Ringwald #endif
42653deb3ec6SMatthias Ringwald 
426627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4267c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42684c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
426927c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
427027c32905SMatthias Ringwald                 break;
427127c32905SMatthias Ringwald             }
4272bccf5e67SMatthias Ringwald 
4273e53be891SMatthias Ringwald             // store public key for DH Key calculation
4274fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4275fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4276bccf5e67SMatthias Ringwald 
427702658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
427802658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
427902658749SMatthias Ringwald                 log_info("Remote PK matches ours");
428002658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
428102658749SMatthias Ringwald                 break;
428202658749SMatthias Ringwald             }
428302658749SMatthias Ringwald 
4284d1a1f6a4SMatthias Ringwald             // validate public key
4285d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
42869305033eSMatthias Ringwald             if (err != 0){
428702658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4288349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4289bccf5e67SMatthias Ringwald                 break;
4290bccf5e67SMatthias Ringwald             }
4291891bb64aSMatthias Ringwald 
4292d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4293f3582630SMatthias 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);
42943cf37b8cSMatthias Ringwald 
429565a9a04eSMatthias Ringwald 
429665a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
429742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4298136d331aSMatthias Ringwald                 // responder
4299c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4300136d331aSMatthias Ringwald             } else {
4301136d331aSMatthias Ringwald                 // initiator
4302a1e31e9cSMatthias Ringwald                 // stk generation method
4303a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4304a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4305a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
430647fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4307c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4308a1e31e9cSMatthias Ringwald                         break;
4309a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
431007036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
431107036a04SMatthias Ringwald                         break;
431207036a04SMatthias Ringwald                     case PK_INIT_INPUT:
431347fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
431407036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
431507036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
431607036a04SMatthias Ringwald                             break;
431707036a04SMatthias Ringwald                         }
4318b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4319a1e31e9cSMatthias Ringwald                         break;
4320a1e31e9cSMatthias Ringwald                     case OOB:
4321d1a1f6a4SMatthias Ringwald                         // generate Nx
43224acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43236ca80073SMatthias 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);
4324a1e31e9cSMatthias Ringwald                         break;
43257bbeb3adSMilanka Ringwald                     default:
43267bbeb3adSMilanka Ringwald                         btstack_assert(false);
43277bbeb3adSMilanka Ringwald                         break;
4328a1e31e9cSMatthias Ringwald                 }
4329136d331aSMatthias Ringwald             }
433027c32905SMatthias Ringwald             break;
4331e53be891SMatthias Ringwald 
4332c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43334c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
433445a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
433545a61d50SMatthias Ringwald                 break;
433645a61d50SMatthias Ringwald             }
433745a61d50SMatthias Ringwald             // received confirm value
433845a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
433945a61d50SMatthias Ringwald 
4340192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4341192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4342192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4343192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4344192365feSMatthias Ringwald             }
4345192365feSMatthias Ringwald #endif
434642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
434745a61d50SMatthias Ringwald                 // responder
434807036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
434907036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
435007036a04SMatthias Ringwald                         // still waiting for passkey
435107036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
435207036a04SMatthias Ringwald                         break;
435307036a04SMatthias Ringwald                     }
435407036a04SMatthias Ringwald                 }
4355b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
435645a61d50SMatthias Ringwald             } else {
435745a61d50SMatthias Ringwald                 // initiator
4358945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43596ca80073SMatthias 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);
4360f1c1783eSMatthias Ringwald                 } else {
4361c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
436245a61d50SMatthias Ringwald                 }
4363f1c1783eSMatthias Ringwald             }
436445a61d50SMatthias Ringwald             break;
436545a61d50SMatthias Ringwald 
4366c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43674c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4368e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4369136d331aSMatthias Ringwald                 break;
4370e53be891SMatthias Ringwald             }
4371e53be891SMatthias Ringwald 
4372e53be891SMatthias Ringwald             // received random value
4373e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4374e53be891SMatthias Ringwald 
43755a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4376ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4377d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4378d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4379d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
438065a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4381d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4382688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4383ae451ec5SMatthias Ringwald                  break;
43845a293e6eSMatthias Ringwald             }
43856f52a196SMatthias Ringwald 
43864acf7b7bSMatthias Ringwald             // OOB
43874acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
43884acf7b7bSMatthias Ringwald 
43894acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
43904acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
43914acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43924ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
43934acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
43944acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
43954acf7b7bSMatthias Ringwald                     } else {
43966535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
43974acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
43984acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
43994acf7b7bSMatthias Ringwald                     }
44004acf7b7bSMatthias Ringwald                 }  else {
44014ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
44024acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
44034acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
44044acf7b7bSMatthias Ringwald                     } else {
44056535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
44064acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
44074acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
44084acf7b7bSMatthias Ringwald                     }
44094acf7b7bSMatthias Ringwald                 }
44104acf7b7bSMatthias Ringwald 
4411a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
44124acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4413a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4414a680ba6bSMatthias Ringwald                      break;
4415a680ba6bSMatthias Ringwald                 }
44164acf7b7bSMatthias Ringwald             }
4417a680ba6bSMatthias Ringwald 
4418a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4419688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4420e53be891SMatthias Ringwald             break;
4421e53be891SMatthias Ringwald 
4422901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4423901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44243cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4425901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4426901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4427901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4428901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4429901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4430901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4431901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4432c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4433901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4434d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44354c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4436e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4437e53be891SMatthias Ringwald                 break;
4438e53be891SMatthias Ringwald             }
4439e53be891SMatthias Ringwald             // store DHKey Check
4440901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4441e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4442446a8c36SMatthias Ringwald 
4443901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4444901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4445019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4446bd57ffebSMatthias Ringwald             }
4447bd57ffebSMatthias Ringwald             break;
444827c32905SMatthias Ringwald #endif
444927c32905SMatthias Ringwald 
445042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44513deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44524c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44533deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
445427c32905SMatthias Ringwald                 break;
44553deb3ec6SMatthias Ringwald             }
44563deb3ec6SMatthias Ringwald 
44573deb3ec6SMatthias Ringwald             // received confirm value
44589c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44593deb3ec6SMatthias Ringwald 
4460192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4461192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4462192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4463192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4464192365feSMatthias Ringwald             }
4465192365feSMatthias Ringwald #endif
44663deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44673deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44685611a760SMatthias 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);
44693deb3ec6SMatthias Ringwald             }
44703deb3ec6SMatthias Ringwald 
44713deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44723deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4473f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44743deb3ec6SMatthias Ringwald                 break;
44753deb3ec6SMatthias Ringwald             }
44763deb3ec6SMatthias Ringwald 
44773deb3ec6SMatthias Ringwald             // wait for user action?
44783deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44793deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44803deb3ec6SMatthias Ringwald                 break;
44813deb3ec6SMatthias Ringwald             }
44823deb3ec6SMatthias Ringwald 
44833deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4484f3582630SMatthias 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);
44853deb3ec6SMatthias Ringwald             break;
44863deb3ec6SMatthias Ringwald 
44873deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
44884c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
44893deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
44903deb3ec6SMatthias Ringwald                 break;;
44913deb3ec6SMatthias Ringwald             }
44923deb3ec6SMatthias Ringwald 
44933deb3ec6SMatthias Ringwald             // received random value
44949c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
44953deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
44963deb3ec6SMatthias Ringwald             break;
449742134bc6SMatthias Ringwald #endif
44983deb3ec6SMatthias Ringwald 
44993deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
45004c1d1092SMatthias Ringwald             switch(sm_pdu_code){
45013deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
45023deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
45039c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
45043deb3ec6SMatthias Ringwald                     break;
45053deb3ec6SMatthias Ringwald 
45063deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
45073deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4508f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
45099c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
45103deb3ec6SMatthias Ringwald                     break;
45113deb3ec6SMatthias Ringwald 
45123deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
45133deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
45149c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
45153deb3ec6SMatthias Ringwald                     break;
45163deb3ec6SMatthias Ringwald 
45173deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
45183deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
45193deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4520724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
45213deb3ec6SMatthias Ringwald                     break;
45223deb3ec6SMatthias Ringwald 
45233deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45243deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45259c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45263deb3ec6SMatthias Ringwald                     break;
45273deb3ec6SMatthias Ringwald                 default:
45283deb3ec6SMatthias Ringwald                     // Unexpected PDU
45293deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45303deb3ec6SMatthias Ringwald                     break;
45313deb3ec6SMatthias Ringwald             }
45323deb3ec6SMatthias Ringwald             // done with key distribution?
453361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45343deb3ec6SMatthias Ringwald 
45353deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45363deb3ec6SMatthias Ringwald 
453742134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45386f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45393deb3ec6SMatthias Ringwald                 } else {
4540625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4541625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4542bbf8db22SMatthias Ringwald                     } else {
4543f3582630SMatthias 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);
4544625f00b2SMatthias Ringwald                     }
45453deb3ec6SMatthias Ringwald                 }
45463deb3ec6SMatthias Ringwald             }
45473deb3ec6SMatthias Ringwald             break;
4548c18be159SMatthias Ringwald 
4549c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4550c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4551c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4552c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4553c18be159SMatthias Ringwald                 break;
4554c18be159SMatthias Ringwald             }
4555c18be159SMatthias Ringwald             // store pairing response
4556c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4557c18be159SMatthias Ringwald 
4558c18be159SMatthias Ringwald             // validate encryption key size
4559c18be159SMatthias 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));
4560c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4561c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4562c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4563c18be159SMatthias Ringwald             }
4564c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4565c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4566c18be159SMatthias Ringwald                 break;
4567c18be159SMatthias Ringwald             }
4568c18be159SMatthias Ringwald 
4569c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4570c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4571c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4572c18be159SMatthias Ringwald 
4573c18be159SMatthias Ringwald             // skip receive if there are none
457461d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4575c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4576c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4577c18be159SMatthias Ringwald             } else {
4578c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4579c18be159SMatthias Ringwald             }
4580c18be159SMatthias Ringwald             break;
4581c18be159SMatthias Ringwald 
4582c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4583c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4584c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4585c18be159SMatthias Ringwald                 break;
4586c18be159SMatthias Ringwald             }
4587c18be159SMatthias Ringwald             // store pairing request
4588c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4589c18be159SMatthias Ringwald             // validate encryption key size
4590c18be159SMatthias 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));
4591c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4592c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4593c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4594c18be159SMatthias Ringwald             }
4595c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4596c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4597c18be159SMatthias Ringwald                 break;
4598c18be159SMatthias Ringwald             }
4599c18be159SMatthias Ringwald             // trigger response
4600c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4601c18be159SMatthias Ringwald             break;
4602c18be159SMatthias Ringwald 
4603c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4604c18be159SMatthias Ringwald             switch(sm_pdu_code){
4605c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4606c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4607c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4608c18be159SMatthias Ringwald                     break;
4609c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4610c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4611c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4612c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4613c18be159SMatthias Ringwald                     break;
4614c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4615c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4616c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4617c18be159SMatthias Ringwald                     break;
4618c18be159SMatthias Ringwald                 default:
4619c18be159SMatthias Ringwald                     // Unexpected PDU
4620c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4621c18be159SMatthias Ringwald                     break;
4622c18be159SMatthias Ringwald             }
4623c18be159SMatthias Ringwald 
4624c18be159SMatthias Ringwald             // all keys received
462561d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4626c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4627c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4628c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4629c18be159SMatthias Ringwald                 } else {
4630c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4631c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4632c18be159SMatthias Ringwald                 }
4633c18be159SMatthias Ringwald             }
4634c18be159SMatthias Ringwald             break;
4635c18be159SMatthias Ringwald #endif
4636c18be159SMatthias Ringwald 
46373deb3ec6SMatthias Ringwald         default:
46383deb3ec6SMatthias Ringwald             // Unexpected PDU
46393deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46402d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46413deb3ec6SMatthias Ringwald             break;
46423deb3ec6SMatthias Ringwald     }
46433deb3ec6SMatthias Ringwald 
464470b44dd4SMatthias Ringwald     // try to send next pdu
464570b44dd4SMatthias Ringwald     sm_trigger_run();
46463deb3ec6SMatthias Ringwald }
46473deb3ec6SMatthias Ringwald 
46483deb3ec6SMatthias Ringwald // Security Manager Client API
4649a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46503deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46513deb3ec6SMatthias Ringwald }
46523deb3ec6SMatthias Ringwald 
46534acf7b7bSMatthias 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)){
4654a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4655a680ba6bSMatthias Ringwald }
4656a680ba6bSMatthias Ringwald 
4657b96d60a6SMatthias 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)){
4658b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4659b96d60a6SMatthias Ringwald }
4660b96d60a6SMatthias Ringwald 
466189a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
466289a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
466389a78d34SMatthias Ringwald }
466489a78d34SMatthias Ringwald 
466567f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
466667f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
466767f708e0SMatthias Ringwald }
466867f708e0SMatthias Ringwald 
46693deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46703deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46713deb3ec6SMatthias Ringwald }
46723deb3ec6SMatthias Ringwald 
46733deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46743deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46753deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46763deb3ec6SMatthias Ringwald }
46773deb3ec6SMatthias Ringwald 
46783deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
467998d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
468098d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
468198d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
468298d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
468398d95509SMatthias Ringwald     }
468498d95509SMatthias Ringwald #endif
46853deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
46863deb3ec6SMatthias Ringwald }
46873deb3ec6SMatthias Ringwald 
46883deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
46893deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
46903deb3ec6SMatthias Ringwald }
46913deb3ec6SMatthias Ringwald 
469242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
46933deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
46943deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
46953deb3ec6SMatthias Ringwald }
469642134bc6SMatthias Ringwald #endif
46973deb3ec6SMatthias Ringwald 
46983deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
46996535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
47003deb3ec6SMatthias Ringwald }
47013deb3ec6SMatthias Ringwald 
47023deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
47036535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
47043deb3ec6SMatthias Ringwald }
47053deb3ec6SMatthias Ringwald 
47063deb3ec6SMatthias Ringwald // Testing support only
47073deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
47086535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4709103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4710841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
47113deb3ec6SMatthias Ringwald }
47123deb3ec6SMatthias Ringwald 
47133deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4714841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
47153deb3ec6SMatthias Ringwald }
47163deb3ec6SMatthias Ringwald 
4717d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4718d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4719d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4720d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
472134b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
472270b44dd4SMatthias Ringwald     sm_trigger_run();
4723d1a1f6a4SMatthias Ringwald }
4724674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
472534b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4726674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4727674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4728674e5b4aSMatthias Ringwald }
4729d1a1f6a4SMatthias Ringwald #endif
4730d1a1f6a4SMatthias Ringwald 
4731192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4732192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4733192365feSMatthias Ringwald     test_pairing_failure = reason;
4734192365feSMatthias Ringwald }
4735192365feSMatthias Ringwald #endif
4736192365feSMatthias Ringwald 
47373deb3ec6SMatthias Ringwald void sm_init(void){
47382d2d4d3cSMatthias Ringwald 
47392d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47402d2d4d3cSMatthias Ringwald 
4741899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4742899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4743899e6e02SMatthias Ringwald 
47443deb3ec6SMatthias Ringwald     // defaults
47453deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47463deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4747b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4748b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4749b4343428SMatthias Ringwald 
47503deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47513deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47523deb3ec6SMatthias Ringwald 
47535ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47541979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4755caf15bf3SMatthias Ringwald 
4756d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4757d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47587a766ebfSMatthias Ringwald #endif
47598d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4760fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47613deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47623deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47633deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47643deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47653deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47663deb3ec6SMatthias Ringwald 
47673deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47687149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47693deb3ec6SMatthias Ringwald 
4770841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47713deb3ec6SMatthias Ringwald 
477284c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
477384c0c5c7SMatthias Ringwald 
4774e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4775e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4776e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4777e03e489aSMatthias Ringwald 
4778d1a1f6a4SMatthias Ringwald     //
4779d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4780d1a1f6a4SMatthias Ringwald 
478151bd74d1SMatthias Ringwald     // init le_device_db
478251bd74d1SMatthias Ringwald     le_device_db_init();
478351bd74d1SMatthias Ringwald 
4784b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4785e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
478627c32905SMatthias Ringwald 
478709e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4788674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4789a3aba2f9SMatthias Ringwald #endif
47902d2d4d3cSMatthias Ringwald 
47912d2d4d3cSMatthias Ringwald     sm_initialized = true;
47923deb3ec6SMatthias Ringwald }
47933deb3ec6SMatthias Ringwald 
479415537ea4SMatthias Ringwald void sm_deinit(void){
479515537ea4SMatthias Ringwald     sm_initialized = false;
479615537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
479715537ea4SMatthias Ringwald }
479815537ea4SMatthias Ringwald 
47994b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
48004b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4801caf15bf3SMatthias Ringwald }
4802caf15bf3SMatthias Ringwald 
48036c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
48041979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
48056c39055aSMatthias Ringwald }
48066c39055aSMatthias Ringwald 
4807711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4808711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
48093deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
48103deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
48113deb3ec6SMatthias Ringwald }
48123deb3ec6SMatthias Ringwald 
481377e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
481477e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
481577e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
481677e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
481777e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
481877e2e5edSMatthias Ringwald }
481977e2e5edSMatthias Ringwald #endif
482077e2e5edSMatthias Ringwald 
48216bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4822711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4823711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48243deb3ec6SMatthias Ringwald     if (!sm_conn) return;
48256bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
48266bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
48273deb3ec6SMatthias Ringwald }
48283deb3ec6SMatthias Ringwald 
48293deb3ec6SMatthias Ringwald // request pairing
4830711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4831711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48323deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48333deb3ec6SMatthias Ringwald 
48347af5dcd5SMatthias Ringwald     bool have_ltk;
48357af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48363deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
483742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
483824c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
483924c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
484024c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48417af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48427af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48437af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48447af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48457af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48467af5dcd5SMatthias Ringwald                         if (have_ltk){
48477af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
484824c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48497af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48507af5dcd5SMatthias Ringwald                             break;
48517af5dcd5SMatthias Ringwald                         }
48527af5dcd5SMatthias Ringwald                         /* fall through */
48537af5dcd5SMatthias Ringwald 
48547af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48557af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48567af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48577af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48587af5dcd5SMatthias Ringwald                         break;
48597af5dcd5SMatthias Ringwald                     default:
48607af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48617af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48627af5dcd5SMatthias Ringwald                         break;
48637af5dcd5SMatthias Ringwald                 }
486424c20dc4SMatthias Ringwald                 break;
486524c20dc4SMatthias Ringwald             default:
486624c20dc4SMatthias Ringwald                 break;
486724c20dc4SMatthias Ringwald         }
48683deb3ec6SMatthias Ringwald     } else {
48693deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4870175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4871175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48723deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48733deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48743dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4875f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4876f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4877f53ec649SMatthias Ringwald                         if (have_ltk){
4878c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48795567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4880c245ca32SMatthias Ringwald                             break;
4881f53ec649SMatthias Ringwald                         }
4882cf373d3aSMatthias Ringwald                         /* fall through */
4883c245ca32SMatthias Ringwald 
488434c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48853deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
48863deb3ec6SMatthias Ringwald                         break;
48873deb3ec6SMatthias Ringwald                     default:
4888d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
488909ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48903deb3ec6SMatthias Ringwald                         break;
48913deb3ec6SMatthias Ringwald                 }
4892175b7faaSMatthias Ringwald                 break;
4893cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4894cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4895cb6d7eb0SMatthias Ringwald                 break;
4896175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
489709ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4898175b7faaSMatthias Ringwald                 break;
4899175b7faaSMatthias Ringwald             default:
4900175b7faaSMatthias Ringwald                 break;
49013deb3ec6SMatthias Ringwald         }
49023deb3ec6SMatthias Ringwald     }
490370b44dd4SMatthias Ringwald     sm_trigger_run();
49043deb3ec6SMatthias Ringwald }
49053deb3ec6SMatthias Ringwald 
49063deb3ec6SMatthias Ringwald // called by client app on authorization request
4907711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4908711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49093deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49103deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4911589f5a99SMatthias 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);
49123deb3ec6SMatthias Ringwald }
49133deb3ec6SMatthias Ringwald 
4914711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4915711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49163deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49173deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4918589f5a99SMatthias 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);
49193deb3ec6SMatthias Ringwald }
49203deb3ec6SMatthias Ringwald 
49213deb3ec6SMatthias Ringwald // GAP Bonding API
49223deb3ec6SMatthias Ringwald 
4923711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4924711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49253deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49263deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
49270af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
49280af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
49290af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49300af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49310af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49320af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49330af429c6SMatthias Ringwald #endif
49340af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4935de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4936de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4937de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
493847fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49390af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4940de2fd182SMatthias Ringwald                     break;
494147fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4942de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4943de2fd182SMatthias Ringwald                     break;
4944de2fd182SMatthias Ringwald                 case JUST_WORKS:
4945de2fd182SMatthias Ringwald                 case OOB:
4946de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4947de2fd182SMatthias Ringwald                     break;
49487bbeb3adSMilanka Ringwald                 default:
49497bbeb3adSMilanka Ringwald                     btstack_assert(false);
49507bbeb3adSMilanka Ringwald                     break;
4951de2fd182SMatthias Ringwald             }
49520af429c6SMatthias Ringwald             break;
49530af429c6SMatthias Ringwald         default:
49540af429c6SMatthias Ringwald             break;
49553deb3ec6SMatthias Ringwald     }
495670b44dd4SMatthias Ringwald     sm_trigger_run();
49573deb3ec6SMatthias Ringwald }
49583deb3ec6SMatthias Ringwald 
4959711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4960711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49613deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49623deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49633deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4964136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4965c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4966bbf8db22SMatthias Ringwald         } else {
4967f3582630SMatthias 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);
4968136d331aSMatthias Ringwald         }
49693deb3ec6SMatthias Ringwald     }
49700346c37cSMatthias Ringwald 
49710346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4972c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4973dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4974446a8c36SMatthias Ringwald     }
49750346c37cSMatthias Ringwald #endif
49760346c37cSMatthias Ringwald 
497770b44dd4SMatthias Ringwald     sm_trigger_run();
49783deb3ec6SMatthias Ringwald }
49793deb3ec6SMatthias Ringwald 
4980c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4981c8c46d51SMatthias Ringwald     // for now, it's the same
4982c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4983c8c46d51SMatthias Ringwald }
4984c8c46d51SMatthias Ringwald 
4985711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4986711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49873deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49883deb3ec6SMatthias Ringwald     sm_reset_tk();
4989f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
49903deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
49913deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4992f3582630SMatthias 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);
49933deb3ec6SMatthias Ringwald     }
49941c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49956535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
49966535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
499707036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
499807036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
499907036a04SMatthias Ringwald     }
50001c516d8fSMatthias Ringwald #endif
500170b44dd4SMatthias Ringwald     sm_trigger_run();
50023deb3ec6SMatthias Ringwald }
50033deb3ec6SMatthias Ringwald 
50043d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
50053d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50063d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50073d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5008dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
50094ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5010dd4a08fbSMatthias Ringwald     switch (action){
5011dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5012dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
50134ea43905SMatthias Ringwald             flags |= (1u << action);
5014dd4a08fbSMatthias Ringwald             break;
5015dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5016dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
50174ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5018dd4a08fbSMatthias Ringwald             break;
5019dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
50204ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5021dd4a08fbSMatthias Ringwald                 // erase actions queued
5022dd4a08fbSMatthias Ringwald                 num_actions--;
50234ea43905SMatthias Ringwald                 if (num_actions == 0u){
5024dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50254ea43905SMatthias Ringwald                     flags &= 0x19u;
5026dd4a08fbSMatthias Ringwald                 }
5027dd4a08fbSMatthias Ringwald                 break;
5028dd4a08fbSMatthias Ringwald             }
5029dd4a08fbSMatthias Ringwald             num_actions++;
50304ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5031dd4a08fbSMatthias Ringwald             break;
5032dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50334ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5034dd4a08fbSMatthias Ringwald                 // enter actions queued
5035dd4a08fbSMatthias Ringwald                 num_actions--;
50364ea43905SMatthias Ringwald                 if (num_actions == 0u){
5037dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50384ea43905SMatthias Ringwald                     flags &= 0x19u;
5039dd4a08fbSMatthias Ringwald                 }
5040dd4a08fbSMatthias Ringwald                 break;
5041dd4a08fbSMatthias Ringwald             }
5042dd4a08fbSMatthias Ringwald             num_actions++;
50434ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5044dd4a08fbSMatthias Ringwald             break;
5045dd4a08fbSMatthias Ringwald         default:
5046dd4a08fbSMatthias Ringwald             break;
5047dd4a08fbSMatthias Ringwald     }
5048dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
504970b44dd4SMatthias Ringwald     sm_trigger_run();
50503d7fe1e9SMatthias Ringwald }
50513d7fe1e9SMatthias Ringwald 
5052c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5053d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5054d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5055d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
505670b44dd4SMatthias Ringwald     sm_trigger_run();
5057d1a1f6a4SMatthias Ringwald }
5058c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50598334d3d8SMatthias Ringwald 
50608334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50618334d3d8SMatthias Ringwald 
5062c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5063c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5064d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5065d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5066c59d0c92SMatthias Ringwald     return 0;
5067c59d0c92SMatthias Ringwald }
5068c59d0c92SMatthias Ringwald #endif
5069c59d0c92SMatthias Ringwald 
50703deb3ec6SMatthias Ringwald /**
5071ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5072ba394633SMatthias Ringwald  * @param con_handle
5073ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5074ba394633SMatthias Ringwald  */
5075ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5076ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5077ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5078ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5079ba394633SMatthias Ringwald }
5080ba394633SMatthias Ringwald 
5081ba394633SMatthias Ringwald /**
50823deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50833deb3ec6SMatthias Ringwald  * @param handle
50846b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
50853deb3ec6SMatthias Ringwald  */
5086711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5087711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50883deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
50893deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
50903deb3ec6SMatthias Ringwald }
50913deb3ec6SMatthias Ringwald 
50928f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
509347ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
509447ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
509547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
509647ba4de1SMatthias Ringwald             return 0;
509747ba4de1SMatthias Ringwald         default:
50988f57b085SMatthias Ringwald             return 1;
50998f57b085SMatthias Ringwald     }
510047ba4de1SMatthias Ringwald }
5101d70217a2SMatthias Ringwald 
510233373e40SMatthias Ringwald static uint8_t own_address_type(void){
5103b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5104b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5105b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5106b95a5a35SMatthias Ringwald         default:
5107b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5108b95a5a35SMatthias Ringwald     }
510933373e40SMatthias Ringwald }
51108f57b085SMatthias Ringwald 
51113deb3ec6SMatthias Ringwald // GAP LE API
51123deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
51133deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51143deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5115b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
51168f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51173deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51183deb3ec6SMatthias Ringwald     gap_random_address_trigger();
51193deb3ec6SMatthias Ringwald }
51203deb3ec6SMatthias Ringwald 
51213deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
51223deb3ec6SMatthias Ringwald     return gap_random_adress_type;
51233deb3ec6SMatthias Ringwald }
51243deb3ec6SMatthias Ringwald 
51253deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
51263deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
51278f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51283deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51293deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51303deb3ec6SMatthias Ringwald }
51313deb3ec6SMatthias Ringwald 
5132667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51338f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51346535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5135e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
51367e252622SMatthias Ringwald }
51377e252622SMatthias Ringwald 
5138d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51393deb3ec6SMatthias Ringwald /*
51403deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51413deb3ec6SMatthias Ringwald  * @param adv_int_min
51423deb3ec6SMatthias Ringwald  * @param adv_int_max
51433deb3ec6SMatthias Ringwald  * @param adv_type
51443deb3ec6SMatthias Ringwald  * @param direct_address_type
51453deb3ec6SMatthias Ringwald  * @param direct_address
51463deb3ec6SMatthias Ringwald  * @param channel_map
51473deb3ec6SMatthias Ringwald  * @param filter_policy
51483deb3ec6SMatthias Ringwald  *
51493deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51503deb3ec6SMatthias Ringwald  */
51513deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51523deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5153b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51543deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51553deb3ec6SMatthias Ringwald }
5156d70217a2SMatthias Ringwald #endif
5157dcd6c9b5SMatthias Ringwald 
5158dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5159dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5160dcd6c9b5SMatthias Ringwald      // wrong connection
5161dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5162dcd6c9b5SMatthias Ringwald     // already encrypted
5163dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5164dcd6c9b5SMatthias Ringwald     // irk status?
5165dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5166dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5167dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5168dcd6c9b5SMatthias Ringwald             return 0;
5169dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5170dcd6c9b5SMatthias Ringwald             break;
5171dcd6c9b5SMatthias Ringwald         default:
5172dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5173dcd6c9b5SMatthias Ringwald             return 1;
5174dcd6c9b5SMatthias Ringwald     }
5175f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5176f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5177b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5178b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5179b15d5ceaSMatthias Ringwald     } else {
5180dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5181dcd6c9b5SMatthias Ringwald     }
5182b15d5ceaSMatthias Ringwald }
51833cdbe9dbSMatthias Ringwald 
51843cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
51853cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51863cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
51873cdbe9dbSMatthias Ringwald #else
51883cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
51893cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
51903cdbe9dbSMatthias Ringwald #endif
51913cdbe9dbSMatthias Ringwald }
5192052bbdc5SMatthias Ringwald 
5193052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5194052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5195052bbdc5SMatthias Ringwald }
51964f384501SMatthias Ringwald 
51974f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
51984f384501SMatthias Ringwald     uint16_t i;
51994f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
52004f384501SMatthias Ringwald         bd_addr_t entry_address;
52014f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
52024f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
52034f384501SMatthias Ringwald         // skip unused entries
52044f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
52054f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
52064f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
52074f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
52084f384501SMatthias Ringwald #endif
52094f384501SMatthias Ringwald             le_device_db_remove(i);
52104f384501SMatthias Ringwald             break;
52114f384501SMatthias Ringwald         }
52124f384501SMatthias Ringwald     }
52134f384501SMatthias Ringwald }
5214