xref: /btstack/src/ble/sm.c (revision 321397a49b5a1e826b749bd36b6f0cfe54c4c5c2)
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);
3957887cd92SMatthias Ringwald static void sm_state_reset(void);
396711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
397711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39877e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39977e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
40077e2e5edSMatthias Ringwald #endif
4013deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
4023deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
412d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4132a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
415d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4162a526f21SMatthias Ringwald #endif
417d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
418d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
419d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
420d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
421d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4226d80b495SMatthias 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));
42334b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4246ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4256ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4262a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
427d1a1f6a4SMatthias Ringwald #endif
4280ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4293deb3ec6SMatthias Ringwald 
4303deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4313deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4323deb3ec6SMatthias Ringwald }
4333deb3ec6SMatthias Ringwald 
4341fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4351fbd72c5SMatthias Ringwald //     return packet[0];
4361fbd72c5SMatthias Ringwald // }
4371fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4381fbd72c5SMatthias Ringwald     return packet[1];
4391fbd72c5SMatthias Ringwald }
4401fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4411fbd72c5SMatthias Ringwald     return packet[2];
4421fbd72c5SMatthias Ringwald }
4431fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4441fbd72c5SMatthias Ringwald     return packet[3];
4451fbd72c5SMatthias Ringwald }
4461fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4471fbd72c5SMatthias Ringwald     return packet[4];
4481fbd72c5SMatthias Ringwald }
4491fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4501fbd72c5SMatthias Ringwald     return packet[5];
4511fbd72c5SMatthias Ringwald }
4521fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4531fbd72c5SMatthias Ringwald     return packet[6];
4541fbd72c5SMatthias Ringwald }
4551fbd72c5SMatthias Ringwald 
4561fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4571fbd72c5SMatthias Ringwald     packet[0] = code;
4581fbd72c5SMatthias Ringwald }
4591fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4601fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4611fbd72c5SMatthias Ringwald }
4621fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4631fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4641fbd72c5SMatthias Ringwald }
4651fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4661fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4671fbd72c5SMatthias Ringwald }
4681fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4691fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4701fbd72c5SMatthias Ringwald }
4711fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4721fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4731fbd72c5SMatthias Ringwald }
4741fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4751fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4761fbd72c5SMatthias Ringwald }
4771fbd72c5SMatthias Ringwald 
4786b65794dSMilanka Ringwald // @return 1 if all bytes are 0
4791979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4803deb3ec6SMatthias Ringwald     int i;
4813764b551SMatthias Ringwald     for (i=0; i < size ; i++){
48284c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4831979f09cSMatthias Ringwald             return false;
48484c0c5c7SMatthias Ringwald         }
4853deb3ec6SMatthias Ringwald     }
4861979f09cSMatthias Ringwald     return true;
4873deb3ec6SMatthias Ringwald }
4883deb3ec6SMatthias Ringwald 
4891979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4903764b551SMatthias Ringwald     return sm_is_null(random, 8);
4913764b551SMatthias Ringwald }
4923764b551SMatthias Ringwald 
4931979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4943764b551SMatthias Ringwald     return sm_is_null(key, 16);
4953764b551SMatthias Ringwald }
4963764b551SMatthias Ringwald 
49770b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49870b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49970b44dd4SMatthias Ringwald 	UNUSED(ts);
50070b44dd4SMatthias Ringwald 	sm_run();
50170b44dd4SMatthias Ringwald }
50270b44dd4SMatthias Ringwald static void sm_trigger_run(void){
5032d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
50484c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50570b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50670b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50770b44dd4SMatthias Ringwald }
50870b44dd4SMatthias Ringwald 
5093deb3ec6SMatthias Ringwald // Key utils
5103deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5113deb3ec6SMatthias Ringwald     int i;
5123deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5133deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5143deb3ec6SMatthias Ringwald     }
5153deb3ec6SMatthias Ringwald }
5163deb3ec6SMatthias Ringwald 
5173deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5183deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5193deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5203deb3ec6SMatthias Ringwald     int i;
5213deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5223deb3ec6SMatthias Ringwald         key[15-i] = 0;
5233deb3ec6SMatthias Ringwald     }
5243deb3ec6SMatthias Ringwald }
5253deb3ec6SMatthias Ringwald 
526899e6e02SMatthias Ringwald // ER / IR checks
52721045273SMatthias Ringwald static void sm_er_ir_set_default(void){
528899e6e02SMatthias Ringwald     int i;
529899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
530899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
531899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
532899e6e02SMatthias Ringwald     }
533899e6e02SMatthias Ringwald }
534899e6e02SMatthias Ringwald 
535899e6e02SMatthias Ringwald static int sm_er_is_default(void){
536899e6e02SMatthias Ringwald     int i;
537899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
538899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
539899e6e02SMatthias Ringwald     }
540899e6e02SMatthias Ringwald     return 1;
541899e6e02SMatthias Ringwald }
542899e6e02SMatthias Ringwald 
543899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
544899e6e02SMatthias Ringwald     int i;
545899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
546899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
547899e6e02SMatthias Ringwald     }
548899e6e02SMatthias Ringwald     return 1;
549899e6e02SMatthias Ringwald }
550899e6e02SMatthias Ringwald 
55173102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
55273102768SMatthias Ringwald     UNUSED(channel);
55373102768SMatthias Ringwald 
55473102768SMatthias Ringwald     // log event
55573102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55673102768SMatthias Ringwald     // dispatch to all event handlers
55773102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55873102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55973102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
56073102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
56173102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
56273102768SMatthias Ringwald     }
56373102768SMatthias Ringwald }
56473102768SMatthias Ringwald 
56573102768SMatthias 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){
56673102768SMatthias Ringwald     event[0] = type;
56773102768SMatthias Ringwald     event[1] = event_size - 2;
56873102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56973102768SMatthias Ringwald     event[4] = addr_type;
57073102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
57173102768SMatthias Ringwald }
57273102768SMatthias Ringwald 
57373102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
57473102768SMatthias Ringwald     uint8_t event[11];
57573102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57773102768SMatthias Ringwald }
57873102768SMatthias Ringwald 
57973102768SMatthias 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){
58073102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58173102768SMatthias Ringwald     bd_addr_t identity_address;
58273102768SMatthias Ringwald     int identity_address_type;
58373102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58473102768SMatthias Ringwald 
58573102768SMatthias Ringwald     uint8_t event[20];
58673102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58773102768SMatthias Ringwald     event[11] = identity_address_type;
58873102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58973102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
59073102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59173102768SMatthias Ringwald }
59273102768SMatthias Ringwald 
59373102768SMatthias 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){
59473102768SMatthias Ringwald     uint8_t event[12];
59573102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59673102768SMatthias Ringwald     event[11] = status;
59773102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59873102768SMatthias Ringwald }
59973102768SMatthias Ringwald 
60073102768SMatthias Ringwald 
60173102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60273102768SMatthias Ringwald 
6033ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6043ab61f77SMatthias Ringwald 
6057b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60673102768SMatthias Ringwald 
60773102768SMatthias Ringwald     int       identity_addr_type;
60873102768SMatthias Ringwald     bd_addr_t identity_addr;
6093c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6103c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61173102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6123c0e26deSMatthias Ringwald     } else {
6133c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6143c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6153c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6163c0e26deSMatthias Ringwald     }
61773102768SMatthias Ringwald 
61873102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61973102768SMatthias Ringwald }
62073102768SMatthias Ringwald 
62173102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62273102768SMatthias Ringwald 
62360be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62460be5b21SMatthias Ringwald 
6257b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62673102768SMatthias Ringwald 
62773102768SMatthias Ringwald     int       identity_addr_type;
62873102768SMatthias Ringwald     bd_addr_t identity_addr;
6293c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6303c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63173102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6323c0e26deSMatthias Ringwald     } else {
6333c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6343c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6353c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6363c0e26deSMatthias Ringwald     }
63773102768SMatthias Ringwald 
63873102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63973102768SMatthias Ringwald }
64073102768SMatthias Ringwald 
641d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
642d3c12277SMatthias Ringwald 
643d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
644d3c12277SMatthias Ringwald 
645d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
646d3c12277SMatthias Ringwald 
647d3c12277SMatthias Ringwald     uint8_t event[11];
648d3c12277SMatthias 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);
649d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
650d3c12277SMatthias Ringwald }
651d3c12277SMatthias Ringwald 
6520ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
653f61072f5SMatthias Ringwald 
654d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
655d77906ffSMatthias Ringwald 
65669f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65769f82ad8SMatthias Ringwald 
6580ccf6c9cSMatthias Ringwald     uint8_t event[13];
6590ccf6c9cSMatthias 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);
6600ccf6c9cSMatthias Ringwald     event[11] = status;
6610ccf6c9cSMatthias Ringwald     event[12] = reason;
6620ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6630ccf6c9cSMatthias Ringwald }
6640ccf6c9cSMatthias Ringwald 
6653deb3ec6SMatthias Ringwald // SMP Timeout implementation
6663deb3ec6SMatthias Ringwald 
6673deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6683deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6693deb3ec6SMatthias Ringwald //
6703deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6713deb3ec6SMatthias Ringwald //
6723deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6733deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6743deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6753deb3ec6SMatthias Ringwald // established.
6763deb3ec6SMatthias Ringwald 
677ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6783deb3ec6SMatthias Ringwald     log_info("SM timeout");
679c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6803deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68168a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6820ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6833deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6843deb3ec6SMatthias Ringwald 
6853deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6863deb3ec6SMatthias Ringwald     sm_run();
6873deb3ec6SMatthias Ringwald }
6883deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
689528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
69091a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
691528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
692528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
693528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6943deb3ec6SMatthias Ringwald }
6953deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
696528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6993deb3ec6SMatthias Ringwald     sm_timeout_stop();
7003deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7013deb3ec6SMatthias Ringwald }
7023deb3ec6SMatthias Ringwald 
7033deb3ec6SMatthias Ringwald // end of sm timeout
7043deb3ec6SMatthias Ringwald 
7053deb3ec6SMatthias Ringwald // GAP Random Address updates
7063deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
707ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7083deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7093deb3ec6SMatthias Ringwald 
7103deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
711899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
712d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
713fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71470b44dd4SMatthias Ringwald     sm_trigger_run();
7153deb3ec6SMatthias Ringwald }
7163deb3ec6SMatthias Ringwald 
717ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7189ec2630cSMatthias Ringwald     UNUSED(timer);
7199ec2630cSMatthias Ringwald 
7203deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
721528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
722528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7233deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7243deb3ec6SMatthias Ringwald }
7253deb3ec6SMatthias Ringwald 
7263deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
727528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
728528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
729528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7303deb3ec6SMatthias Ringwald }
7313deb3ec6SMatthias Ringwald 
7323deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
733528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7343deb3ec6SMatthias Ringwald }
7353deb3ec6SMatthias Ringwald 
7363deb3ec6SMatthias Ringwald // ah(k,r) helper
7373deb3ec6SMatthias Ringwald // r = padding || r
7383deb3ec6SMatthias Ringwald // r - 24 bit value
7394a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7403deb3ec6SMatthias Ringwald     // r'= padding || r
7413deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7426535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7433deb3ec6SMatthias Ringwald }
7443deb3ec6SMatthias Ringwald 
7453deb3ec6SMatthias Ringwald // d1 helper
7463deb3ec6SMatthias Ringwald // d' = padding || r || d
7473deb3ec6SMatthias Ringwald // d,r - 16 bit values
7484a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7493deb3ec6SMatthias Ringwald     // d'= padding || r || d
7503deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
751f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
752f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7533deb3ec6SMatthias Ringwald }
7543deb3ec6SMatthias Ringwald 
7553deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7564a6806f3SMatthias 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){
7573deb3ec6SMatthias Ringwald 
7583deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7593deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7603deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7613deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7623deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7633deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7643deb3ec6SMatthias Ringwald 
7653deb3ec6SMatthias Ringwald     sm_key_t p1;
7669c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7679c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7683deb3ec6SMatthias Ringwald     p1[14] = rat;
7693deb3ec6SMatthias Ringwald     p1[15] = iat;
7708314c363SMatthias Ringwald     log_info_key("p1", p1);
7718314c363SMatthias Ringwald     log_info_key("r", r);
7723deb3ec6SMatthias Ringwald 
7733deb3ec6SMatthias Ringwald     // t1 = r xor p1
7743deb3ec6SMatthias Ringwald     int i;
7753deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7763deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7773deb3ec6SMatthias Ringwald     }
7788314c363SMatthias Ringwald     log_info_key("t1", t1);
7793deb3ec6SMatthias Ringwald }
7803deb3ec6SMatthias Ringwald 
7813deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7824a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7833deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7843deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7853deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7863deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7873deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7883deb3ec6SMatthias Ringwald 
7893deb3ec6SMatthias Ringwald     sm_key_t p2;
7903deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7916535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7926535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7938314c363SMatthias Ringwald     log_info_key("p2", p2);
7943deb3ec6SMatthias Ringwald 
7953deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7963deb3ec6SMatthias Ringwald     int i;
7973deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7983deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7993deb3ec6SMatthias Ringwald     }
8008314c363SMatthias Ringwald     log_info_key("t3", t3);
8013deb3ec6SMatthias Ringwald }
8023deb3ec6SMatthias Ringwald 
8034a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8048314c363SMatthias Ringwald     log_info_key("r1", r1);
8058314c363SMatthias Ringwald     log_info_key("r2", r2);
8066535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8076535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8083deb3ec6SMatthias Ringwald }
8093deb3ec6SMatthias Ringwald 
810fbe050beSMatthias Ringwald 
8113deb3ec6SMatthias Ringwald // decide on stk generation based on
8123deb3ec6SMatthias Ringwald // - pairing request
8133deb3ec6SMatthias Ringwald // - io capabilities
8143deb3ec6SMatthias Ringwald // - OOB data availability
8153deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8163deb3ec6SMatthias Ringwald 
8178334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8188334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8198334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8208334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8218334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8228334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8238334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8248334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8258334d3d8SMatthias Ringwald     };
8268334d3d8SMatthias Ringwald 
8278334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8288334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8298334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8308334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8318334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8328334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8338334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8348334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8358334d3d8SMatthias Ringwald     };
8368334d3d8SMatthias Ringwald #endif
8378334d3d8SMatthias Ringwald 
8383deb3ec6SMatthias Ringwald     // default: just works
8393deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8403deb3ec6SMatthias Ringwald 
84127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84227c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84327c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8444ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84527c32905SMatthias Ringwald #else
84627c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84727c32905SMatthias Ringwald #endif
84898d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84927c32905SMatthias Ringwald 
85065a9a04eSMatthias Ringwald 
85165a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8521979f09cSMatthias Ringwald     bool use_oob;
85365a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85465a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85565a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8561979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85765a9a04eSMatthias Ringwald     } else {
85865a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85965a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8601979f09cSMatthias 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;
86165a9a04eSMatthias Ringwald     }
86265a9a04eSMatthias Ringwald     if (use_oob){
86365a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86465a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86565a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86665a9a04eSMatthias Ringwald         return;
86765a9a04eSMatthias Ringwald     }
86865a9a04eSMatthias Ringwald 
86927c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
87027c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87127c32905SMatthias Ringwald     // model shall be used.
8724ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8734ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87427c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87527c32905SMatthias Ringwald         return;
87627c32905SMatthias Ringwald     }
87727c32905SMatthias Ringwald 
8783deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8793deb3ec6SMatthias Ringwald     sm_reset_tk();
8803deb3ec6SMatthias Ringwald 
8813deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8828da2e96dSMatthias 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)){
8833deb3ec6SMatthias Ringwald         return;
8843deb3ec6SMatthias Ringwald     }
8853deb3ec6SMatthias Ringwald 
8863deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8873deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88827c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88927c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
89027c32905SMatthias Ringwald 
89127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
892c6b7cbd9SMatthias Ringwald     // table not define by default
89327c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89427c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89527c32905SMatthias Ringwald     }
89627c32905SMatthias Ringwald #endif
89727c32905SMatthias 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)];
89827c32905SMatthias Ringwald 
8993deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
9001ad129beSMatthias 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);
9013deb3ec6SMatthias Ringwald }
9023deb3ec6SMatthias Ringwald 
9033deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9043deb3ec6SMatthias Ringwald     int flags = 0;
9053deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9073deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9083deb3ec6SMatthias Ringwald     }
9093deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9113deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9123deb3ec6SMatthias Ringwald     }
9133deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9143deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9153deb3ec6SMatthias Ringwald     }
9163deb3ec6SMatthias Ringwald     return flags;
9173deb3ec6SMatthias Ringwald }
9183deb3ec6SMatthias Ringwald 
9199a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9203deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9219a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9229a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
923715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9249790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
925715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9269790be5fSMatthias Ringwald #endif
9273deb3ec6SMatthias Ringwald }
9283deb3ec6SMatthias Ringwald 
9293deb3ec6SMatthias Ringwald // CSRK Key Lookup
9303deb3ec6SMatthias Ringwald 
9313deb3ec6SMatthias Ringwald 
9323deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9333deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9343deb3ec6SMatthias Ringwald }
9353deb3ec6SMatthias Ringwald 
936711e6c80SMatthias 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){
9376535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9383deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9393deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9403deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9413deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
942711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9433deb3ec6SMatthias Ringwald }
9443deb3ec6SMatthias Ringwald 
9453deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9463deb3ec6SMatthias Ringwald     // check if already in list
947665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9483deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
949665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
950665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
951665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9523deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9533deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9543deb3ec6SMatthias Ringwald         // already in list
9553deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9563deb3ec6SMatthias Ringwald     }
9573deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9583deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9593deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9606535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
961665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96270b44dd4SMatthias Ringwald     sm_trigger_run();
9633deb3ec6SMatthias Ringwald     return 0;
9643deb3ec6SMatthias Ringwald }
9653deb3ec6SMatthias Ringwald 
966d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
967d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
968514d35fcSMatthias Ringwald 
969d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
970d1a1f6a4SMatthias Ringwald     UNUSED(arg);
971d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
972d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97370b44dd4SMatthias Ringwald     sm_trigger_run();
9743deb3ec6SMatthias Ringwald }
975514d35fcSMatthias Ringwald 
9764dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9774ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9783deb3ec6SMatthias Ringwald }
9796d80b495SMatthias Ringwald #endif
9803deb3ec6SMatthias Ringwald 
9816d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
982514d35fcSMatthias Ringwald // generic cmac calculation
983d1a1f6a4SMatthias 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)){
984d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
985d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
986d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9873deb3ec6SMatthias Ringwald }
9887a766ebfSMatthias Ringwald #endif
9893deb3ec6SMatthias Ringwald 
990514d35fcSMatthias Ringwald // cmac for ATT Message signing
9917a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
992d1a1f6a4SMatthias Ringwald 
993d1a1f6a4SMatthias 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)){
994d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
995d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
996d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
997d1a1f6a4SMatthias Ringwald }
998d1a1f6a4SMatthias Ringwald 
9994dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
1000d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1001d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10024dfd504aSMatthias Ringwald         return 0;
10034dfd504aSMatthias Ringwald     }
10044dfd504aSMatthias Ringwald 
1005d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10064dfd504aSMatthias Ringwald 
1007d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10084dfd504aSMatthias Ringwald     if (offset < 3){
1009d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10104dfd504aSMatthias Ringwald     }
1011d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10124dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1013d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10144dfd504aSMatthias Ringwald     }
1015d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10164dfd504aSMatthias Ringwald }
10174dfd504aSMatthias Ringwald 
10184dfd504aSMatthias 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)){
1019514d35fcSMatthias Ringwald     // ATT Message Signing
1020d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1021d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1022d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1023514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1024d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1025d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1026d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10273deb3ec6SMatthias Ringwald }
10287a766ebfSMatthias Ringwald #endif
10293deb3ec6SMatthias Ringwald 
1030ea9b6796SMatthias Ringwald static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){
1031ea9b6796SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10325baa755bSMatthias Ringwald     uint8_t event[12];
1033f6a153d5SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10345baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
1035f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1036ea9b6796SMatthias Ringwald }
1037ea9b6796SMatthias Ringwald 
1038ea9b6796SMatthias Ringwald static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn){
10395baa755bSMatthias Ringwald     uint8_t event[16];
1040f6a153d5SMatthias Ringwald     uint32_t passkey = big_endian_read_32(setup->sm_tk, 12);
1041f6a153d5SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle,
1042f6a153d5SMatthias Ringwald                         sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10435baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
10445baa755bSMatthias Ringwald     little_endian_store_32(event, 12, passkey);
1045f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1046ea9b6796SMatthias Ringwald }
1047ea9b6796SMatthias Ringwald 
10483deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1049446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10503deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1051d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10523deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10533deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
105442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1055ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10563deb3ec6SMatthias Ringwald             } else {
1057ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10583deb3ec6SMatthias Ringwald             }
10593deb3ec6SMatthias Ringwald             break;
10603deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
106142134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1062ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10633deb3ec6SMatthias Ringwald             } else {
1064ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10653deb3ec6SMatthias Ringwald             }
10663deb3ec6SMatthias Ringwald             break;
106747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
1068ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10693deb3ec6SMatthias Ringwald             break;
107047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1071ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST);
107227c32905SMatthias Ringwald             break;
10733deb3ec6SMatthias Ringwald         case JUST_WORKS:
1074ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST);
10753deb3ec6SMatthias Ringwald             break;
10763deb3ec6SMatthias Ringwald         case OOB:
10773deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10783deb3ec6SMatthias Ringwald             break;
10797bbeb3adSMilanka Ringwald         default:
10807bbeb3adSMilanka Ringwald             btstack_assert(false);
10817bbeb3adSMilanka Ringwald             break;
10823deb3ec6SMatthias Ringwald     }
10833deb3ec6SMatthias Ringwald }
10843deb3ec6SMatthias Ringwald 
108561d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
10865fa700b1SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, setup->sm_key_distribution_expected_set);
1087b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10883deb3ec6SMatthias Ringwald }
10893deb3ec6SMatthias Ringwald 
1090711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10917149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10923deb3ec6SMatthias Ringwald         sm_timeout_stop();
10937149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1094711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1095c085d9ffSMatthias Ringwald 
1096c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1097c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1098c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1099c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1100c085d9ffSMatthias Ringwald         }
1101c085d9ffSMatthias Ringwald #endif
11023deb3ec6SMatthias Ringwald     }
11033deb3ec6SMatthias Ringwald }
11043deb3ec6SMatthias Ringwald 
11057d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11061dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11070ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11081dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11091dca9d8aSMatthias Ringwald }
11101dca9d8aSMatthias Ringwald 
11113deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1112bb09604fSMatthias Ringwald 
1113bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11143deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1115bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11163deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1117bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1118bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1119bb09604fSMatthias Ringwald #endif
11207ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11217ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11227ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11237ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11247ece0eaaSMatthias Ringwald         }
11257ece0eaaSMatthias Ringwald #endif
11263deb3ec6SMatthias Ringwald     }
11273deb3ec6SMatthias Ringwald     return flags;
11283deb3ec6SMatthias Ringwald }
11293deb3ec6SMatthias Ringwald 
1130d7471931SMatthias Ringwald static void sm_reset_setup(void){
11313deb3ec6SMatthias Ringwald     // fill in sm setup
1132901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1133dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1134d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11353deb3ec6SMatthias Ringwald     sm_reset_tk();
1136d7471931SMatthias Ringwald }
1137d7471931SMatthias Ringwald 
1138d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1139d7471931SMatthias Ringwald     // fill in sm setup
11403deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11416535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11423deb3ec6SMatthias Ringwald 
1143a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11449305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1145a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11463deb3ec6SMatthias Ringwald     }
11473deb3ec6SMatthias Ringwald 
1148a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1149a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11504acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11514acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1152a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11539305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11544acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1155a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1156a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1157a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1158a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11594acf7b7bSMatthias Ringwald                     setup->sm_ra);
11604acf7b7bSMatthias Ringwald             } else {
11614acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11624acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11634acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11644acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11654acf7b7bSMatthias Ringwald                     setup->sm_rb);
11664acf7b7bSMatthias Ringwald             }
1167a680ba6bSMatthias Ringwald         } else {
1168a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1169a680ba6bSMatthias Ringwald         }
1170a680ba6bSMatthias Ringwald     }
1171a680ba6bSMatthias Ringwald #endif
1172a680ba6bSMatthias Ringwald 
11733deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11753deb3ec6SMatthias Ringwald         // slave
11763deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11773deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1178d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11796535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1180d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11813deb3ec6SMatthias Ringwald     } else {
11823deb3ec6SMatthias Ringwald         // master
11833deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11843deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1185d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11866535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1187d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11883deb3ec6SMatthias Ringwald 
1189d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11901ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11911ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11923deb3ec6SMatthias Ringwald     }
11933deb3ec6SMatthias Ringwald 
119457132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1195d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11962c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11972c041b42SMatthias Ringwald     // enable SC for SC only mode
11982c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11992c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1200d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
12012c041b42SMatthias Ringwald     }
12022c041b42SMatthias Ringwald #endif
120357132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120457132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120557132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120657132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120757132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120857132f12SMatthias Ringwald 	}
120957132f12SMatthias Ringwald #endif
12101ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1211a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1212df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1213d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12143deb3ec6SMatthias Ringwald }
12153deb3ec6SMatthias Ringwald 
12163deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12173deb3ec6SMatthias Ringwald 
12183deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12199a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12209a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
122142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
122252f9cf63SMatthias Ringwald         // slave / responder
12233deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12249a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12259a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12263deb3ec6SMatthias Ringwald     } else {
12273deb3ec6SMatthias Ringwald         // master / initiator
12283deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12299a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12309a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12313deb3ec6SMatthias Ringwald     }
12323deb3ec6SMatthias Ringwald 
12333deb3ec6SMatthias Ringwald     // check key size
12342c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12352c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12362c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12372c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12382c041b42SMatthias Ringwald     }
12392c041b42SMatthias Ringwald #endif
12401ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12414ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12423deb3ec6SMatthias Ringwald 
1243eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12443deb3ec6SMatthias Ringwald     sm_setup_tk();
12453deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12463deb3ec6SMatthias Ringwald 
12473deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12483deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12493deb3ec6SMatthias Ringwald 
1250eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12512c041b42SMatthias Ringwald     // Check LE SC Only mode
12523cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12533cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12543cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12553cdbe9dbSMatthias Ringwald     }
12563cdbe9dbSMatthias Ringwald 
12579a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1258eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12599a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12609a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1261eddc894fSMatthias Ringwald     }
1262eddc894fSMatthias Ringwald #endif
1263eddc894fSMatthias Ringwald 
126452f9cf63SMatthias Ringwald     // identical to responder
12659a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
126652f9cf63SMatthias Ringwald 
12673deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1268c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     return 0;
12713deb3ec6SMatthias Ringwald }
12723deb3ec6SMatthias Ringwald 
12733deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12743deb3ec6SMatthias Ringwald 
12753deb3ec6SMatthias Ringwald     // cache and reset context
12763deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12773deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12783deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12793deb3ec6SMatthias Ringwald 
12803deb3ec6SMatthias Ringwald     // reset context
12813deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12823deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12833deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1284711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12853deb3ec6SMatthias Ringwald 
12863deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1287d2e90122SMatthias Ringwald     sm_key_t ltk;
12881979f09cSMatthias Ringwald     bool have_ltk;
12896c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12901979f09cSMatthias Ringwald     bool trigger_pairing;
129142134bc6SMatthias Ringwald #endif
12923deb3ec6SMatthias Ringwald     switch (mode){
12933deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12943deb3ec6SMatthias Ringwald             break;
12953deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12963deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1297711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12986c44b759SMatthias Ringwald 
12996c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
13006c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
13016c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
13026c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
13036c44b759SMatthias Ringwald 
13043deb3ec6SMatthias Ringwald             switch (event){
1305a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13063deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13073deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1308a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13096c44b759SMatthias Ringwald 
13106c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13116c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13126c44b759SMatthias Ringwald 
13136c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13146c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1315212d735eSMatthias Ringwald                         // IRK required before, continue
13166c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13176c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13186c39055aSMatthias Ringwald                             break;
13196c39055aSMatthias Ringwald                         }
1320212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1321212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1322212d735eSMatthias Ringwald                             break;
1323212d735eSMatthias Ringwald                         }
13247af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13257af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13266c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13277af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13287af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13296c44b759SMatthias Ringwald #endif
13307af5dcd5SMatthias Ringwald 
13317af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13321979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13337af5dcd5SMatthias Ringwald 
13347af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13357af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13367af5dcd5SMatthias Ringwald                             if (have_ltk){
13377af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13387af5dcd5SMatthias Ringwald                             } else {
13397af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13407af5dcd5SMatthias Ringwald                             }
13417af5dcd5SMatthias Ringwald                             sm_trigger_run();
13426c44b759SMatthias Ringwald                         }
13436c44b759SMatthias Ringwald #endif
13446c44b759SMatthias Ringwald                     } else {
13456c44b759SMatthias Ringwald 
134642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13476c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13486c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13496c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13501979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13513deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
135209ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
135332bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1354c245ca32SMatthias Ringwald 
1355d4af1595SMatthias Ringwald                         if (have_ltk){
13566a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1357b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135832bc5d65SMatthias Ringwald #else
135932bc5d65SMatthias Ringwald                             if (trigger_pairing){
136032bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
136132bc5d65SMatthias Ringwald                             } else {
136232bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
136332bc5d65SMatthias Ringwald                             }
136432bc5d65SMatthias Ringwald #endif
136532bc5d65SMatthias Ringwald                         }
136632bc5d65SMatthias Ringwald 
136732bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13686c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13695567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1370d4af1595SMatthias Ringwald                             break;
1371d4af1595SMatthias Ringwald                         }
13726c44b759SMatthias Ringwald 
13736c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13746c44b759SMatthias Ringwald                         if (trigger_pairing){
13753deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1376d4af1595SMatthias Ringwald                             break;
13773deb3ec6SMatthias Ringwald                         }
137842134bc6SMatthias Ringwald #endif
1379298ab52bSMatthias Ringwald                     }
13803deb3ec6SMatthias Ringwald                     break;
13813deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13823deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13836c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13847af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13856c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13866c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13876c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13886c39055aSMatthias Ringwald                         }
13897af5dcd5SMatthias Ringwald                         // send security request if requested
13907af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13917af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13927af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13937af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13947af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13957af5dcd5SMatthias Ringwald                         }
13966c39055aSMatthias Ringwald                         break;
13977af5dcd5SMatthias Ringwald #endif
13986c39055aSMatthias Ringwald                     }
139942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
140009ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
14013deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
140209ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
14033deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
140442134bc6SMatthias Ringwald #endif
14053deb3ec6SMatthias Ringwald                     break;
14067bbeb3adSMilanka Ringwald 
14077bbeb3adSMilanka Ringwald                 default:
14087bbeb3adSMilanka Ringwald                     btstack_assert(false);
14097bbeb3adSMilanka Ringwald                     break;
14103deb3ec6SMatthias Ringwald             }
14113deb3ec6SMatthias Ringwald             break;
14123deb3ec6SMatthias Ringwald         default:
14133deb3ec6SMatthias Ringwald             break;
14143deb3ec6SMatthias Ringwald     }
14153deb3ec6SMatthias Ringwald 
14163deb3ec6SMatthias Ringwald     switch (event){
1417a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1418711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14193deb3ec6SMatthias Ringwald             break;
14203deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1421711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14223deb3ec6SMatthias Ringwald             break;
14237bbeb3adSMilanka Ringwald         default:
14247bbeb3adSMilanka Ringwald             btstack_assert(false);
14257bbeb3adSMilanka Ringwald             break;
14263deb3ec6SMatthias Ringwald     }
14273deb3ec6SMatthias Ringwald }
14283deb3ec6SMatthias Ringwald 
142955f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14303deb3ec6SMatthias Ringwald     int le_db_index = -1;
14313deb3ec6SMatthias Ringwald 
14323deb3ec6SMatthias Ringwald     // lookup device based on IRK
14333deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14343deb3ec6SMatthias Ringwald         int i;
1435092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14363deb3ec6SMatthias Ringwald             sm_key_t irk;
14373deb3ec6SMatthias Ringwald             bd_addr_t address;
1438c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14393deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1440adf5eaa9SMatthias Ringwald             // skip unused entries
1441c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
144211d10bdaSMatthias Ringwald             // compare Identity Address
144311d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
144411d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1445c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1446c7e2c1a5SMatthias Ringwald 
14473deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14483deb3ec6SMatthias Ringwald             le_db_index = i;
14493deb3ec6SMatthias Ringwald             break;
14503deb3ec6SMatthias Ringwald         }
1451c7e2c1a5SMatthias Ringwald     } else {
1452c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1453c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14543deb3ec6SMatthias Ringwald     }
14553deb3ec6SMatthias Ringwald 
14563deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14573deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1458c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14593deb3ec6SMatthias Ringwald         int i;
1460092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14613deb3ec6SMatthias Ringwald             bd_addr_t address;
1462adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14633deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1464adf5eaa9SMatthias Ringwald             // skip unused entries
1465adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14663deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14675df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14683deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14693deb3ec6SMatthias Ringwald                 le_db_index = i;
14703deb3ec6SMatthias Ringwald                 break;
14713deb3ec6SMatthias Ringwald             }
14723deb3ec6SMatthias Ringwald         }
14733deb3ec6SMatthias Ringwald     }
14743deb3ec6SMatthias Ringwald 
14753deb3ec6SMatthias Ringwald     // if not found, add to db
147602b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14773deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14783deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147902b02cffSMatthias Ringwald         new_to_le_device_db = true;
14803deb3ec6SMatthias Ringwald     }
14813deb3ec6SMatthias Ringwald 
14823deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14833deb3ec6SMatthias Ringwald 
148402b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148502b02cffSMatthias Ringwald         if (!new_to_le_device_db){
148602b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148702b02cffSMatthias Ringwald         }
148802b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148902b02cffSMatthias Ringwald #else
149002b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
149102b02cffSMatthias Ringwald #endif
149202b02cffSMatthias Ringwald 
149348163929SMatthias Ringwald         sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index);
1494e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14957710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
149648163929SMatthias Ringwald 
1497eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14983deb3ec6SMatthias Ringwald         // store local CSRK
1499715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1500715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15013deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
15023deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15033deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
15043deb3ec6SMatthias Ringwald         }
15053deb3ec6SMatthias Ringwald 
15063deb3ec6SMatthias Ringwald         // store remote CSRK
15073deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15083deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
15093deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15103deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15113deb3ec6SMatthias Ringwald         }
1512eda85fbfSMatthias Ringwald #endif
151378f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
151478f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1515e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151678f44163SMatthias Ringwald             uint8_t zero_rand[8];
151778f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
151878f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15193dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
152078f44163SMatthias Ringwald         }
152178f44163SMatthias Ringwald 
1522e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152378f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
152478f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1525e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15263deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15273dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152878f44163SMatthias Ringwald 
15293deb3ec6SMatthias Ringwald         }
15303deb3ec6SMatthias Ringwald     }
153155f09f49SMatthias Ringwald }
153255f09f49SMatthias Ringwald 
15338980298aSMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
15348980298aSMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
15358980298aSMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
15368980298aSMatthias Ringwald }
15378980298aSMatthias Ringwald 
1538*321397a4SMatthias Ringwald static int sm_lookup_by_address(void) {
15391a55487aSMatthias Ringwald     int i;
15401a55487aSMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
15411a55487aSMatthias Ringwald         bd_addr_t address;
15421a55487aSMatthias Ringwald         int address_type = BD_ADDR_TYPE_UNKNOWN;
15431a55487aSMatthias Ringwald         le_device_db_info(i, &address_type, address, NULL);
15441a55487aSMatthias Ringwald         // skip unused entries
15451a55487aSMatthias Ringwald         if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
15461a55487aSMatthias Ringwald         if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
15471a55487aSMatthias Ringwald             return i;
15481a55487aSMatthias Ringwald         }
15491a55487aSMatthias Ringwald     }
15501a55487aSMatthias Ringwald     return -1;
15511a55487aSMatthias Ringwald }
15521a55487aSMatthias Ringwald 
15532e08b70bSMatthias Ringwald static void sm_remove_le_device_db_entry(uint16_t i) {
15542e08b70bSMatthias Ringwald     le_device_db_remove(i);
1555672dc582SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1556672dc582SMatthias Ringwald     // to remove an entry from the resolving list requires its identity address, which was already deleted
1557672dc582SMatthias Ringwald     // fully reload resolving list instead
1558672dc582SMatthias Ringwald     gap_load_resolving_list_from_le_device_db();
1559672dc582SMatthias Ringwald #endif
15602e08b70bSMatthias Ringwald }
15612e08b70bSMatthias Ringwald 
15628980298aSMatthias Ringwald static uint8_t sm_key_distribution_validate_received(sm_connection_t * sm_conn){
15631a55487aSMatthias Ringwald     // if identity is provided, abort if we have bonding with same address but different irk
15641a55487aSMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
1565*321397a4SMatthias Ringwald         int index = sm_lookup_by_address();
15661a55487aSMatthias Ringwald         if (index >= 0){
15671a55487aSMatthias Ringwald             sm_key_t irk;
15681a55487aSMatthias Ringwald             le_device_db_info(index, NULL, NULL, irk);
15691a55487aSMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0){
15701a55487aSMatthias Ringwald                 // IRK doesn't match, delete bonding information
15711a55487aSMatthias Ringwald                 log_info("New IRK for %s (type %u) does not match stored IRK -> delete bonding information", bd_addr_to_str(sm_conn->sm_peer_address), sm_conn->sm_peer_addr_type);
15729202d845SMatthias Ringwald                 sm_remove_le_device_db_entry(index);
15731a55487aSMatthias Ringwald             }
15741a55487aSMatthias Ringwald         }
15751a55487aSMatthias Ringwald     }
15768980298aSMatthias Ringwald     return 0;
15778980298aSMatthias Ringwald }
15788980298aSMatthias Ringwald 
157955f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
158055f09f49SMatthias Ringwald 
15818980298aSMatthias Ringwald     // abort pairing if received keys are not valid
15828980298aSMatthias Ringwald     uint8_t reason = sm_key_distribution_validate_received(sm_conn);
15838980298aSMatthias Ringwald     if (reason != 0){
15848980298aSMatthias Ringwald         sm_pairing_error(sm_conn, reason);
15858980298aSMatthias Ringwald         return;
15868980298aSMatthias Ringwald     }
15878980298aSMatthias Ringwald 
158855f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
158955f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
159055f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
159155f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
159255f09f49SMatthias Ringwald 
159355f09f49SMatthias Ringwald     if (bonding_enabled){
159455f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
159527ef8bc8SMatthias Ringwald     } else {
159627ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
159727ef8bc8SMatthias Ringwald     }
15983deb3ec6SMatthias Ringwald }
15993deb3ec6SMatthias Ringwald 
1600688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1601688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1602688a08f9SMatthias Ringwald }
1603688a08f9SMatthias Ringwald 
16049af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1605688a08f9SMatthias Ringwald 
1606dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1607945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1608f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1609dc300847SMatthias Ringwald 
1610b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1611b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
16121f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1613b90c4e75SMatthias Ringwald     } else {
1614b90c4e75SMatthias 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);
1615b35a3de2SMatthias Ringwald     }
1616b35a3de2SMatthias Ringwald }
1617b35a3de2SMatthias Ringwald 
1618688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
161942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1620688a08f9SMatthias Ringwald         // Responder
16214acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
16224acf7b7bSMatthias Ringwald             // generate Nb
16234acf7b7bSMatthias Ringwald             log_info("Generate Nb");
16246ca80073SMatthias 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);
16254acf7b7bSMatthias Ringwald         } else {
1626688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
16274acf7b7bSMatthias Ringwald         }
1628688a08f9SMatthias Ringwald     } else {
1629688a08f9SMatthias Ringwald         // Initiator role
1630688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1631688a08f9SMatthias Ringwald             case JUST_WORKS:
1632dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1633688a08f9SMatthias Ringwald                 break;
1634688a08f9SMatthias Ringwald 
163547fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1636bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1637688a08f9SMatthias Ringwald                 break;
1638688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1639688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
164047fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
16414ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1642b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1643688a08f9SMatthias Ringwald                 } else {
1644dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1645688a08f9SMatthias Ringwald                 }
1646688a08f9SMatthias Ringwald                 break;
1647688a08f9SMatthias Ringwald             case OOB:
164865a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1649688a08f9SMatthias Ringwald                 break;
16507bbeb3adSMilanka Ringwald             default:
16517bbeb3adSMilanka Ringwald                 btstack_assert(false);
16527bbeb3adSMilanka Ringwald                 break;
1653688a08f9SMatthias Ringwald         }
1654688a08f9SMatthias Ringwald     }
1655688a08f9SMatthias Ringwald }
1656688a08f9SMatthias Ringwald 
1657aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1658688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1659688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1660688a08f9SMatthias Ringwald 
1661c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1662c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1663a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1664c59d0c92SMatthias Ringwald         return;
1665c59d0c92SMatthias Ringwald     }
1666c59d0c92SMatthias Ringwald 
1667bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1668bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16696857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16702bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1671b4f65634SMatthias Ringwald #endif
1672bd57ffebSMatthias Ringwald 
1673bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1674aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16756535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1676bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1677aec94140SMatthias Ringwald             break;
1678688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1679688a08f9SMatthias Ringwald             // check
1680688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1681bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1682688a08f9SMatthias Ringwald                 break;
1683688a08f9SMatthias Ringwald             }
1684bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1685688a08f9SMatthias Ringwald             break;
1686901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1687901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1688901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1689901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1690901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1691019005a0SMatthias Ringwald             break;
1692019005a0SMatthias Ringwald         }
16930346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16946535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1695bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16960346c37cSMatthias Ringwald             break;
16970346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16986535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1699bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
17000346c37cSMatthias Ringwald             break;
17010346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1702b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1703b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1704b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1705b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
17066535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
17076535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1708893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1709bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1710019005a0SMatthias Ringwald             break;
1711901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
17126535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
171342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1714901c000fSMatthias Ringwald                 // responder
1715901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1716901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1717901c000fSMatthias Ringwald                 } else {
1718901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1719901c000fSMatthias Ringwald                 }
1720901c000fSMatthias Ringwald             } else {
1721901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1722901c000fSMatthias Ringwald             }
1723901c000fSMatthias Ringwald             break;
1724901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1725901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1726901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1727aec94140SMatthias Ringwald                 break;
1728aec94140SMatthias Ringwald             }
172942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1730901c000fSMatthias Ringwald                 // responder
1731901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1732901c000fSMatthias Ringwald             } else {
1733901c000fSMatthias Ringwald                 // initiator
1734901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1735bd57ffebSMatthias Ringwald             }
1736901c000fSMatthias Ringwald             break;
17376857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
173857132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
17396535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
174057132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
17412bacf595SMatthias Ringwald             break;
174257132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
17432bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
17442bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
17452bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
17468974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
174755160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
17488974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
17492bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
17502bacf595SMatthias Ringwald             } else {
17512bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
17522bacf595SMatthias Ringwald             }
17530ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17542bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17552bacf595SMatthias Ringwald             break;
1756e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1757e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1758e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1759e0a03c85SMatthias Ringwald             break;
1760e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1761e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1762e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1763e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1764e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1765e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1766e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1767c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1768e0a03c85SMatthias Ringwald             break;
1769bdb14b0eSMatthias Ringwald #endif
1770bd57ffebSMatthias Ringwald         default:
1771bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1772bd57ffebSMatthias Ringwald             break;
1773bd57ffebSMatthias Ringwald     }
177470b44dd4SMatthias Ringwald     sm_trigger_run();
1775aec94140SMatthias Ringwald }
1776aec94140SMatthias Ringwald 
1777688a08f9SMatthias 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){
1778dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1779aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17806535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17816535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1782aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1783aec94140SMatthias Ringwald     log_info("f4 key");
1784aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1785aec94140SMatthias Ringwald     log_info("f4 message");
1786dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1787d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1788aec94140SMatthias Ringwald }
1789aec94140SMatthias Ringwald 
17900346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17910346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17920346c37cSMatthias Ringwald 
17930346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17948334d3d8SMatthias Ringwald 
17958334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17968334d3d8SMatthias Ringwald 
179740c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17980346c37cSMatthias Ringwald     // calculate salt for f5
17990346c37cSMatthias Ringwald     const uint16_t message_len = 32;
18000346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1802d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18030346c37cSMatthias Ringwald }
18040346c37cSMatthias Ringwald 
18050346c37cSMatthias 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){
18060346c37cSMatthias Ringwald     const uint16_t message_len = 53;
18070346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18080346c37cSMatthias Ringwald 
18090346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
18100346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
18126535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
18136535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
18146535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
18156535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
18166535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
18170346c37cSMatthias Ringwald     log_info("f5 key");
18180346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18190346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
18200346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1821d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18220346c37cSMatthias Ringwald }
18230346c37cSMatthias Ringwald 
18240346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
18250346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
18260346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
18270346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18286535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18296535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
183042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
18310346c37cSMatthias Ringwald         // responder
18320346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
18330346c37cSMatthias Ringwald     } else {
18340346c37cSMatthias Ringwald         // initiator
18350346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
18360346c37cSMatthias Ringwald     }
18370346c37cSMatthias Ringwald }
18380346c37cSMatthias Ringwald 
18390346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
18400346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
18410346c37cSMatthias Ringwald     const uint16_t message_len = 53;
18420346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18430346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
18440346c37cSMatthias Ringwald     // 1..52 setup before
18450346c37cSMatthias Ringwald     log_info("f5 key");
18460346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18470346c37cSMatthias Ringwald     log_info("f5 message for LTK");
18480346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1849d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18500346c37cSMatthias Ringwald }
1851f92edc8eSMatthias Ringwald 
18520346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
18530346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
18540346c37cSMatthias Ringwald }
18550346c37cSMatthias Ringwald 
185631f061fbSMatthias 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){
18576535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18586535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18596535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18606535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18616535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18626535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
186331f061fbSMatthias Ringwald }
186431f061fbSMatthias Ringwald 
186531f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
186631f061fbSMatthias Ringwald     const uint16_t message_len = 65;
186731f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1868dc300847SMatthias Ringwald     log_info("f6 key");
1869dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1870dc300847SMatthias Ringwald     log_info("f6 message");
1871dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1872d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1873dc300847SMatthias Ringwald }
1874dc300847SMatthias Ringwald 
1875f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1876f92edc8eSMatthias Ringwald // - U is 256 bits
1877f92edc8eSMatthias Ringwald // - V is 256 bits
1878f92edc8eSMatthias Ringwald // - X is 128 bits
1879f92edc8eSMatthias Ringwald // - Y is 128 bits
1880bd57ffebSMatthias 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){
1881bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1882bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18836535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18846535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18856535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1886f92edc8eSMatthias Ringwald     log_info("g2 key");
1887f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1888f92edc8eSMatthias Ringwald     log_info("g2 message");
18892bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1890d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1891f92edc8eSMatthias Ringwald }
1892f92edc8eSMatthias Ringwald 
1893b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1894f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
189542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1896f92edc8eSMatthias Ringwald         // responder
1897fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1898f92edc8eSMatthias Ringwald     } else {
1899f92edc8eSMatthias Ringwald         // initiator
1900fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1901f92edc8eSMatthias Ringwald     }
1902f92edc8eSMatthias Ringwald }
1903f92edc8eSMatthias Ringwald 
1904945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
19059af0f475SMatthias Ringwald     uint8_t z = 0;
190640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
19079af0f475SMatthias Ringwald         // some form of passkey
19089af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
19094ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
19109af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
19119af0f475SMatthias Ringwald     }
1912fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
19139af0f475SMatthias Ringwald }
1914688a08f9SMatthias Ringwald 
1915688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1916a680ba6bSMatthias Ringwald     // OOB
1917a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
19184acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
19194acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
19204acf7b7bSMatthias Ringwald         } else {
19214acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
19224acf7b7bSMatthias Ringwald         }
1923a680ba6bSMatthias Ringwald         return;
1924a680ba6bSMatthias Ringwald     }
1925a680ba6bSMatthias Ringwald 
1926688a08f9SMatthias Ringwald     uint8_t z = 0;
192740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1928688a08f9SMatthias Ringwald         // some form of passkey
1929688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1930688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
19314ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1932688a08f9SMatthias Ringwald     }
1933fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1934688a08f9SMatthias Ringwald }
1935688a08f9SMatthias Ringwald 
19360346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1937505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
19383cf37b8cSMatthias Ringwald 
19393cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
19403cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
19413cf37b8cSMatthias Ringwald         return;
19423cf37b8cSMatthias Ringwald     } else {
19433cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
19443cf37b8cSMatthias Ringwald     }
1945d1a1f6a4SMatthias Ringwald }
19463cf37b8cSMatthias Ringwald 
1947d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1948f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1949f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1950f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1951f3582630SMatthias Ringwald 
1952d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1953d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1954d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1955d1a1f6a4SMatthias Ringwald     // trigger next step
1956d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1957d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1958d1a1f6a4SMatthias Ringwald     }
195970b44dd4SMatthias Ringwald     sm_trigger_run();
1960dc300847SMatthias Ringwald }
1961dc300847SMatthias Ringwald 
1962dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1963dc300847SMatthias Ringwald     // calculate DHKCheck
1964dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1965dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1966dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19676535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19686535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1969dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1970dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1971dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1972dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1973dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1974dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1975dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1976dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
197742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1978dc300847SMatthias Ringwald         // responder
197931f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
198031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1981dc300847SMatthias Ringwald     } else {
1982dc300847SMatthias Ringwald         // initiator
198331f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
198431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1985dc300847SMatthias Ringwald     }
1986dc300847SMatthias Ringwald }
1987dc300847SMatthias Ringwald 
1988019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1989019005a0SMatthias Ringwald     // validate E = f6()
1990019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1991019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1992019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19936535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19946535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1995019005a0SMatthias Ringwald 
1996019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1997019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1998019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1999019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
2000019005a0SMatthias Ringwald     uint8_t iocap_b[3];
2001019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
2002019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
2003019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
200442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
2005019005a0SMatthias Ringwald         // responder
200631f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
200731f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
2008019005a0SMatthias Ringwald     } else {
2009019005a0SMatthias Ringwald         // initiator
201031f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
201131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
2012019005a0SMatthias Ringwald     }
2013019005a0SMatthias Ringwald }
20142bacf595SMatthias Ringwald 
201555c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
20162bacf595SMatthias Ringwald 
20172bacf595SMatthias Ringwald //
20182bacf595SMatthias Ringwald // Link Key Conversion Function h6
20192bacf595SMatthias Ringwald //
202057132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
20212bacf595SMatthias Ringwald // - W is 128 bits
20222bacf595SMatthias Ringwald // - keyID is 32 bits
20232bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
20242bacf595SMatthias Ringwald     const uint16_t message_len = 4;
20252bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
20262bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
20272bacf595SMatthias Ringwald     log_info("h6 key");
20282bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
20292bacf595SMatthias Ringwald     log_info("h6 message");
20302bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
2031d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
20322bacf595SMatthias Ringwald }
203357132f12SMatthias Ringwald //
203457132f12SMatthias Ringwald // Link Key Conversion Function h7
203557132f12SMatthias Ringwald //
203657132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
203757132f12SMatthias Ringwald // - SALT is 128 bits
203857132f12SMatthias Ringwald // - W    is 128 bits
203957132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
204057132f12SMatthias Ringwald 	const uint16_t message_len = 16;
204157132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
204257132f12SMatthias Ringwald 	log_info("h7 key");
204357132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
204457132f12SMatthias Ringwald 	log_info("h7 message");
204557132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
204657132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
204757132f12SMatthias Ringwald }
20482bacf595SMatthias Ringwald 
2049b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
2050b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
2051b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
2052b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
205357132f12SMatthias Ringwald 
2054c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
2055b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
20562bacf595SMatthias Ringwald }
20572bacf595SMatthias Ringwald 
2058e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2059e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2060e0a03c85SMatthias Ringwald }
2061e0a03c85SMatthias Ringwald 
20622bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20632bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20642bacf595SMatthias Ringwald }
20652bacf595SMatthias Ringwald 
2066e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2067e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2068e0a03c85SMatthias Ringwald }
2069e0a03c85SMatthias Ringwald 
2070c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
207157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
207257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
207357132f12SMatthias Ringwald }
2074e0a03c85SMatthias Ringwald 
2075e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2076e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2077e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2078e0a03c85SMatthias Ringwald }
2079e0a03c85SMatthias Ringwald 
2080c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2081e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2082e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2083e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2084e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2085e0a03c85SMatthias Ringwald }
2086e0a03c85SMatthias Ringwald 
2087c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2088c18be159SMatthias 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;
2089c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2090c18be159SMatthias Ringwald }
2091c18be159SMatthias Ringwald 
20929af0f475SMatthias Ringwald #endif
20939af0f475SMatthias Ringwald 
209455c62cf5SMatthias Ringwald #endif
209555c62cf5SMatthias Ringwald 
2096613da3deSMatthias Ringwald // key management legacy connections:
2097613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2098613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2099613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2100613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2101613da3deSMatthias Ringwald 
2102613da3deSMatthias Ringwald // key management secure connections:
2103613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2104613da3deSMatthias Ringwald 
210542134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
21065829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
21075829ebe2SMatthias Ringwald     int encryption_key_size;
21085829ebe2SMatthias Ringwald     int authenticated;
21095829ebe2SMatthias Ringwald     int authorized;
21103dc3a67dSMatthias Ringwald     int secure_connection;
21115829ebe2SMatthias Ringwald 
21125829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
21135829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
21143dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
21153dc3a67dSMatthias 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);
21165829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
21175829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
21185829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
21193dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
21205829ebe2SMatthias Ringwald }
212142134bc6SMatthias Ringwald #endif
2122bd57ffebSMatthias Ringwald 
212342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
212459066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
21256535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
212659066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
212759066796SMatthias Ringwald     // re-establish used key encryption size
212859066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
21294ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
213059066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
21314ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
21323dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
21333dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
213459066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
213559066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
213659066796SMatthias Ringwald }
213742134bc6SMatthias Ringwald #endif
213859066796SMatthias Ringwald 
21393deb3ec6SMatthias Ringwald // distributed key generation
2140d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
21413deb3ec6SMatthias Ringwald     switch (dkg_state){
21423deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
21433deb3ec6SMatthias Ringwald             // already busy?
21443deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2145d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
21463deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2147d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2148d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2149d1a1f6a4SMatthias 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);
2150d7f1c72eSMatthias Ringwald                 return true;
21513deb3ec6SMatthias Ringwald             }
21523deb3ec6SMatthias Ringwald             break;
21533deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
21543deb3ec6SMatthias Ringwald             // already busy?
21553deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2156d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
21573deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2158d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2159d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2160d1a1f6a4SMatthias 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);
2161d7f1c72eSMatthias Ringwald                 return true;
21623deb3ec6SMatthias Ringwald             }
21633deb3ec6SMatthias Ringwald             break;
21643deb3ec6SMatthias Ringwald         default:
21653deb3ec6SMatthias Ringwald             break;
21663deb3ec6SMatthias Ringwald     }
2167d7f1c72eSMatthias Ringwald     return false;
2168d7f1c72eSMatthias Ringwald }
21693deb3ec6SMatthias Ringwald 
21703deb3ec6SMatthias Ringwald // random address updates
2171d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21723deb3ec6SMatthias Ringwald     switch (rau_state){
2173fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2174fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21755b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2176d7f1c72eSMatthias Ringwald             return true;
21773deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21783deb3ec6SMatthias Ringwald             // already busy?
21793deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2180d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2181d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2182d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2183d7f1c72eSMatthias Ringwald                 return true;
21843deb3ec6SMatthias Ringwald             }
21853deb3ec6SMatthias Ringwald             break;
21863deb3ec6SMatthias Ringwald         default:
21873deb3ec6SMatthias Ringwald             break;
21883deb3ec6SMatthias Ringwald     }
2189d7f1c72eSMatthias Ringwald     return false;
2190d7f1c72eSMatthias Ringwald }
21913deb3ec6SMatthias Ringwald 
21923deb3ec6SMatthias Ringwald // CSRK Lookup
2193d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2194d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2195d7f1c72eSMatthias Ringwald 
21963deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21973deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21983deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2199665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2200665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22013deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
22023deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
22033deb3ec6SMatthias Ringwald                 // and start lookup
22043deb3ec6SMatthias 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);
22053deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
22063deb3ec6SMatthias Ringwald                 break;
22073deb3ec6SMatthias Ringwald             }
22083deb3ec6SMatthias Ringwald         }
22093deb3ec6SMatthias Ringwald     }
22103deb3ec6SMatthias Ringwald 
22113deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
22123deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2213665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
22143deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2215665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
22163deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
22173deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
22183deb3ec6SMatthias Ringwald         }
22193deb3ec6SMatthias Ringwald     }
22203deb3ec6SMatthias Ringwald 
2221ca685291SMatthias Ringwald     // -- Continue with device lookup by public or resolvable private address
22223deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2223092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2224adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
22253deb3ec6SMatthias Ringwald             bd_addr_t addr;
22263deb3ec6SMatthias Ringwald             sm_key_t irk;
22273deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
22283deb3ec6SMatthias Ringwald 
2229adf5eaa9SMatthias Ringwald             // skip unused entries
2230adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2231adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2232adf5eaa9SMatthias Ringwald                 continue;
2233adf5eaa9SMatthias Ringwald             }
2234adf5eaa9SMatthias Ringwald 
2235ca685291SMatthias Ringwald             log_info("LE Device Lookup: device %u of %u", sm_address_resolution_test, le_device_db_max_count());
2236ca685291SMatthias Ringwald 
22375df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
2238ca685291SMatthias Ringwald                 log_info("LE Device Lookup: found by { addr_type, address} ");
2239a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
22403deb3ec6SMatthias Ringwald                 break;
22413deb3ec6SMatthias Ringwald             }
22423deb3ec6SMatthias Ringwald 
2243a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2244a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
22453deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
22463deb3ec6SMatthias Ringwald                 continue;
22473deb3ec6SMatthias Ringwald             }
22483deb3ec6SMatthias Ringwald 
22498cc81b50SMatthias Ringwald             // skip AH if no IRK
22508cc81b50SMatthias Ringwald             if (sm_is_null_key(irk)){
22518cc81b50SMatthias Ringwald                 sm_address_resolution_test++;
22528cc81b50SMatthias Ringwald                 continue;
22538cc81b50SMatthias Ringwald             }
22548cc81b50SMatthias Ringwald 
22553deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
22563deb3ec6SMatthias Ringwald 
22573deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
22588314c363SMatthias Ringwald             log_info_key("IRK", irk);
22593deb3ec6SMatthias Ringwald 
22606535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2261d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
22623deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2263d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2264d1a1f6a4SMatthias 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);
2265d7f1c72eSMatthias Ringwald             return true;
22663deb3ec6SMatthias Ringwald         }
22673deb3ec6SMatthias Ringwald 
2268092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22693deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22703deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22713deb3ec6SMatthias Ringwald         }
22723deb3ec6SMatthias Ringwald     }
2273d7f1c72eSMatthias Ringwald     return false;
2274d7f1c72eSMatthias Ringwald }
22753deb3ec6SMatthias Ringwald 
2276d7f1c72eSMatthias Ringwald // SC OOB
2277d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2278c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2279c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2280c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2281c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2282c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2283c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2284d7f1c72eSMatthias Ringwald             return true;
2285c59d0c92SMatthias Ringwald         default:
2286c59d0c92SMatthias Ringwald             break;
2287c59d0c92SMatthias Ringwald     }
2288c59d0c92SMatthias Ringwald #endif
2289d7f1c72eSMatthias Ringwald     return false;
2290d7f1c72eSMatthias Ringwald }
2291275aafe8SMatthias Ringwald 
2292687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2293687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2294687a03c8SMatthias Ringwald }
2295687a03c8SMatthias Ringwald 
229641d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2297d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2298d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
229941d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2300e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
230141d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
230241d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
230341d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2304f4935286SMatthias Ringwald 
2305f4935286SMatthias Ringwald             // general
2306f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2307f4935286SMatthias Ringwald                 uint8_t buffer[2];
2308f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2309f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2310f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2311687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2312f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2313f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2314f4935286SMatthias Ringwald                 break;
2315f4935286SMatthias Ringwald             }
2316f4935286SMatthias Ringwald 
231741d32297SMatthias Ringwald             // responder side
231841d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
231941d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
232041d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2321d7f1c72eSMatthias Ringwald                 return true;
23224b8b5afeSMatthias Ringwald 
23234b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
23244b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
23254b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
23264b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2327e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
23284b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
23294b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2330d7f1c72eSMatthias Ringwald                         return true;
23314b8b5afeSMatthias Ringwald                     default:
23324b8b5afeSMatthias Ringwald                         break;
23334b8b5afeSMatthias Ringwald                 }
23344b8b5afeSMatthias Ringwald                 break;
23354b8b5afeSMatthias Ringwald #endif
233641d32297SMatthias Ringwald             default:
233741d32297SMatthias Ringwald                 break;
233841d32297SMatthias Ringwald         }
233941d32297SMatthias Ringwald     }
2340d7f1c72eSMatthias Ringwald     return false;
2341d7f1c72eSMatthias Ringwald }
23423deb3ec6SMatthias Ringwald 
2343d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
23443deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2345d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
23463deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
23477149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2348665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
23493deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
23503deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
23511979f09cSMatthias Ringwald         bool done = true;
23523deb3ec6SMatthias Ringwald         int err;
235342134bc6SMatthias Ringwald         UNUSED(err);
235434b6528fSMatthias Ringwald 
235534b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
235634b6528fSMatthias Ringwald         // assert ec key is ready
2357505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2358178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2359178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
236034b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
236134b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
236234b6528fSMatthias Ringwald             }
236334b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
236434b6528fSMatthias Ringwald                 continue;
236534b6528fSMatthias Ringwald             }
236634b6528fSMatthias Ringwald         }
236734b6528fSMatthias Ringwald #endif
236834b6528fSMatthias Ringwald 
23693deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
237042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23713deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23723deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
237342134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2374549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
237506cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
237687014f74SMatthias Ringwald #endif
237787014f74SMatthias Ringwald #endif
237834c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23795567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
238034c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2381549ad5d2SMatthias Ringwald #endif
2382c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2383c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2384c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2385c18be159SMatthias Ringwald #endif
238687014f74SMatthias Ringwald 				// just lock context
238787014f74SMatthias Ringwald 				break;
23883deb3ec6SMatthias Ringwald             default:
23891979f09cSMatthias Ringwald                 done = false;
23903deb3ec6SMatthias Ringwald                 break;
23913deb3ec6SMatthias Ringwald         }
23923deb3ec6SMatthias Ringwald         if (done){
23937149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23947149bde5SMatthias 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);
23953deb3ec6SMatthias Ringwald         }
23963deb3ec6SMatthias Ringwald     }
2397d7f1c72eSMatthias Ringwald }
2398d7f1c72eSMatthias Ringwald 
2399403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2400403280b9SMatthias Ringwald     int i;
2401403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2402403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2403403280b9SMatthias Ringwald     uint8_t action = 0;
2404403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2405403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2406403280b9SMatthias Ringwald             bool clear_flag = true;
2407403280b9SMatthias Ringwald             switch (i){
2408403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2409403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2410403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2411403280b9SMatthias Ringwald                 default:
2412403280b9SMatthias Ringwald                     break;
2413403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2414403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2415403280b9SMatthias Ringwald                     num_actions--;
2416403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2417403280b9SMatthias Ringwald                     break;
2418403280b9SMatthias Ringwald             }
2419403280b9SMatthias Ringwald             if (clear_flag){
2420403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2421403280b9SMatthias Ringwald             }
2422403280b9SMatthias Ringwald             action = i;
2423403280b9SMatthias Ringwald             break;
2424403280b9SMatthias Ringwald         }
2425403280b9SMatthias Ringwald     }
2426403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2427403280b9SMatthias Ringwald 
2428403280b9SMatthias Ringwald     // send keypress notification
2429403280b9SMatthias Ringwald     uint8_t buffer[2];
2430403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2431403280b9SMatthias Ringwald     buffer[1] = action;
2432687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2433403280b9SMatthias Ringwald 
2434403280b9SMatthias Ringwald     // try
2435384eabd3SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2436403280b9SMatthias Ringwald }
2437403280b9SMatthias Ringwald 
2438403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2439403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2440403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2441403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2442403280b9SMatthias Ringwald         uint8_t buffer[17];
2443403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2444403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2445687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2446403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2447403280b9SMatthias Ringwald         return;
2448403280b9SMatthias Ringwald     }
2449403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2450403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2451403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2452403280b9SMatthias Ringwald         uint8_t buffer[11];
2453403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2454403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2455403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2456687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2457403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2458403280b9SMatthias Ringwald         return;
2459403280b9SMatthias Ringwald     }
2460403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2461403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2462403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2463403280b9SMatthias Ringwald         uint8_t buffer[17];
2464403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2465403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2466687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2467403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2468403280b9SMatthias Ringwald         return;
2469403280b9SMatthias Ringwald     }
2470403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2471403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2472403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2473403280b9SMatthias Ringwald         bd_addr_t local_address;
2474403280b9SMatthias Ringwald         uint8_t buffer[8];
2475403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2476403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2477403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2478403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2479403280b9SMatthias Ringwald                 // public or static random
2480403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2481403280b9SMatthias Ringwald                 break;
2482403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2483403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2484403280b9SMatthias Ringwald                 // fallback to public
2485403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2486403280b9SMatthias Ringwald                 buffer[1] = 0;
2487403280b9SMatthias Ringwald                 break;
2488403280b9SMatthias Ringwald             default:
2489403280b9SMatthias Ringwald                 btstack_assert(false);
2490403280b9SMatthias Ringwald                 break;
2491403280b9SMatthias Ringwald         }
2492403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2493687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2494403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2495403280b9SMatthias Ringwald         return;
2496403280b9SMatthias Ringwald     }
2497403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2498403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2499403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2500403280b9SMatthias Ringwald 
2501403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2502403280b9SMatthias Ringwald         // hack to reproduce test runs
2503403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2504403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2505403280b9SMatthias Ringwald                     }
2506403280b9SMatthias Ringwald 
2507403280b9SMatthias Ringwald                     // store local CSRK
2508403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2509403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2510403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2511403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2512403280b9SMatthias Ringwald                     }
2513403280b9SMatthias Ringwald #endif
2514403280b9SMatthias Ringwald 
2515403280b9SMatthias Ringwald         uint8_t buffer[17];
2516403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2517403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2518687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2519403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2520403280b9SMatthias Ringwald         return;
2521403280b9SMatthias Ringwald     }
2522403280b9SMatthias Ringwald     btstack_assert(false);
2523403280b9SMatthias Ringwald }
2524403280b9SMatthias Ringwald 
2525bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2526bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2527bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2528bbd73538SMatthias Ringwald     // - use secure connections
2529bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2530bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2531bbd73538SMatthias 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;
2532bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2533bbd73538SMatthias Ringwald     // - need identity address / public addr
2534bbd73538SMatthias 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);
2535bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2536bbd73538SMatthias 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)
2537bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2538bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2539bbd73538SMatthias 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.
2540bbd73538SMatthias Ringwald     uint8_t link_key[16];
2541bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2542bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
25437040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2544bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2545bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2546bbd73538SMatthias Ringwald         return false;
2547bbd73538SMatthias Ringwald     }
2548bbd73538SMatthias Ringwald     // get started (all of the above are true)
2549bbd73538SMatthias Ringwald     return true;
2550bbd73538SMatthias Ringwald #else
2551bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2552bbd73538SMatthias Ringwald 	return false;
2553bbd73538SMatthias Ringwald #endif
2554bbd73538SMatthias Ringwald }
2555bbd73538SMatthias Ringwald 
25566f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
25576f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
25586f7422f1SMatthias 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;
25596f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
25606f7422f1SMatthias Ringwald     } else {
25616f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25626f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25636f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25646f7422f1SMatthias Ringwald     }
25656f7422f1SMatthias Ringwald }
25666f7422f1SMatthias Ringwald 
2567af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2568af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2569af7ef9d1SMatthias 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;
2570af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2571af7ef9d1SMatthias Ringwald     } else {
2572af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2573af7ef9d1SMatthias Ringwald     }
2574af7ef9d1SMatthias Ringwald }
2575af7ef9d1SMatthias Ringwald 
2576d7f1c72eSMatthias Ringwald static void sm_run(void){
2577d7f1c72eSMatthias Ringwald 
2578d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2579d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2580d7f1c72eSMatthias Ringwald 
2581d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2582d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2583d7f1c72eSMatthias Ringwald 
2584d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2585d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2586d7f1c72eSMatthias Ringwald 
2587d7f1c72eSMatthias Ringwald     bool done;
2588d7f1c72eSMatthias Ringwald 
2589d7f1c72eSMatthias Ringwald     //
2590d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2591d7f1c72eSMatthias Ringwald     //
2592d7f1c72eSMatthias Ringwald 
2593d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2594d7f1c72eSMatthias Ringwald     if (done) return;
2595d7f1c72eSMatthias Ringwald 
2596d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2597d7f1c72eSMatthias Ringwald     if (done) return;
2598d7f1c72eSMatthias Ringwald 
2599d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2600d7f1c72eSMatthias Ringwald     if (done) return;
2601d7f1c72eSMatthias Ringwald 
2602d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2603d7f1c72eSMatthias Ringwald     if (done) return;
2604d7f1c72eSMatthias Ringwald 
2605d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2606d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2607d7f1c72eSMatthias Ringwald 
2608d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2609d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2610d7f1c72eSMatthias Ringwald     if (done) return;
2611d7f1c72eSMatthias Ringwald 
2612d7f1c72eSMatthias Ringwald     //
2613d7f1c72eSMatthias Ringwald     // active connection handling
2614d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2615d7f1c72eSMatthias Ringwald 
2616d7f1c72eSMatthias Ringwald     while (true) {
2617d7f1c72eSMatthias Ringwald 
2618d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2619d7f1c72eSMatthias Ringwald 
2620d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
26213deb3ec6SMatthias Ringwald 
26223deb3ec6SMatthias Ringwald         //
26233deb3ec6SMatthias Ringwald         // active connection handling
26243deb3ec6SMatthias Ringwald         //
26253deb3ec6SMatthias Ringwald 
26263cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
26273cf37b8cSMatthias Ringwald         if (!connection) {
26283cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
26293cf37b8cSMatthias Ringwald             return;
26303cf37b8cSMatthias Ringwald         }
26313cf37b8cSMatthias Ringwald 
26323deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
2633384eabd3SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) {
26347149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
2635384eabd3SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2636b170b20fSMatthias Ringwald             return;
2637b170b20fSMatthias Ringwald         }
26383deb3ec6SMatthias Ringwald 
26393d7fe1e9SMatthias Ringwald         // send keypress notifications
2640dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2641403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2642d7471931SMatthias Ringwald             return;
26433d7fe1e9SMatthias Ringwald         }
26443d7fe1e9SMatthias Ringwald 
26453deb3ec6SMatthias Ringwald         int key_distribution_flags;
264642134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2647b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2648b6afa23eSMatthias Ringwald         int err;
26499b75de03SMatthias Ringwald         bool have_ltk;
26509b75de03SMatthias Ringwald         uint8_t ltk[16];
2651b6f39a74SMatthias Ringwald #endif
26523deb3ec6SMatthias Ringwald 
26533deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2654384eabd3SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) {
2655dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2656dd4a08fbSMatthias Ringwald         }
26573deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
26583deb3ec6SMatthias Ringwald 
2659f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2660aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2661aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2662aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2663aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2664aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2665aec94140SMatthias Ringwald                 break;
2666688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2667688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2668688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2669688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2670688a08f9SMatthias Ringwald                 break;
2671dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2672dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2673dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2674dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2675dc300847SMatthias Ringwald                 break;
2676019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2677b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2678019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26790346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26800346c37cSMatthias Ringwald                 break;
26810346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2682b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26830346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26840346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26850346c37cSMatthias Ringwald                 break;
26860346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2687b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26880346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26890346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26900346c37cSMatthias Ringwald                 break;
26910346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2692b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26930346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26940346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2695019005a0SMatthias Ringwald                 break;
2696bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2697b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2698bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2699b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2700bd57ffebSMatthias Ringwald                 break;
2701e0a03c85SMatthias Ringwald #endif
2702e0a03c85SMatthias Ringwald 
270342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
27043deb3ec6SMatthias Ringwald             // initiator side
2705f32b7a88SMatthias Ringwald 
27065567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2707f32b7a88SMatthias Ringwald 				sm_reset_setup();
2708f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2709daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2710f32b7a88SMatthias Ringwald 
27113deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
27129c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
27135567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
27143deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2715c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2716c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
27173deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
27183deb3ec6SMatthias Ringwald                 return;
27193deb3ec6SMatthias Ringwald             }
27203deb3ec6SMatthias Ringwald 
2721b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2722b26f445fSMatthias Ringwald 				sm_reset_setup();
2723b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2724b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2725d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2726b26f445fSMatthias Ringwald 
27271ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
27283deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2729687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
27303deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
27313deb3ec6SMatthias Ringwald                 break;
273242134bc6SMatthias Ringwald #endif
27333deb3ec6SMatthias Ringwald 
273427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
273541d32297SMatthias Ringwald 
2736c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
27371979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
27381979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
273927c32905SMatthias Ringwald                 uint8_t buffer[65];
274027c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
274127c32905SMatthias Ringwald                 //
2742fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2743fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2744e53be891SMatthias Ringwald 
2745349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2746349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2747349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2748349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2749349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2750349d0adbSMatthias Ringwald                 }
2751349d0adbSMatthias Ringwald #endif
2752349d0adbSMatthias Ringwald 
275345a61d50SMatthias Ringwald                 // stk generation method
275445a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
275545a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
275645a61d50SMatthias Ringwald                     case JUST_WORKS:
275747fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
275842134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
275907036a04SMatthias Ringwald                             // responder
27601979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2761b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
276227c32905SMatthias Ringwald                         } else {
276307036a04SMatthias Ringwald                             // initiator
2764c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
276527c32905SMatthias Ringwald                         }
276645a61d50SMatthias Ringwald                         break;
276745a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
276845a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
276947fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
277007036a04SMatthias Ringwald                         // use random TK for display
27716535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27726535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
277345a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
277407036a04SMatthias Ringwald 
277542134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
277645a61d50SMatthias Ringwald                             // responder
2777c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
277845a61d50SMatthias Ringwald                         } else {
277945a61d50SMatthias Ringwald                             // initiator
2780c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
278145a61d50SMatthias Ringwald                         }
27821979f09cSMatthias Ringwald                         trigger_user_response = true;
278345a61d50SMatthias Ringwald                         break;
278445a61d50SMatthias Ringwald                     case OOB:
278565a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
278665a9a04eSMatthias Ringwald                             // responder
278765a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
278865a9a04eSMatthias Ringwald                         } else {
278965a9a04eSMatthias Ringwald                             // initiator
279065a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
279165a9a04eSMatthias Ringwald                         }
279245a61d50SMatthias Ringwald                         break;
27937bbeb3adSMilanka Ringwald                     default:
27947bbeb3adSMilanka Ringwald                         btstack_assert(false);
27957bbeb3adSMilanka Ringwald                         break;
279645a61d50SMatthias Ringwald                 }
279745a61d50SMatthias Ringwald 
2798687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
279927c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2800644c6a1dSMatthias Ringwald 
2801b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2802644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2803644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2804644c6a1dSMatthias Ringwald                 }
2805b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2806b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2807b90c4e75SMatthias Ringwald                 }
280827c32905SMatthias Ringwald                 break;
280927c32905SMatthias Ringwald             }
2810c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2811e53be891SMatthias Ringwald                 uint8_t buffer[17];
2812e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
28139af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
281442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2815c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2816e53be891SMatthias Ringwald                 } else {
2817c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2818e53be891SMatthias Ringwald                 }
2819687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2820e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2821e53be891SMatthias Ringwald                 break;
2822e53be891SMatthias Ringwald             }
2823c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2824e53be891SMatthias Ringwald                 uint8_t buffer[17];
2825e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2826e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
28279d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
28284ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
282940c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
283042134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
283145a61d50SMatthias Ringwald                         // responder
2832c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
283345a61d50SMatthias Ringwald                     } else {
283445a61d50SMatthias Ringwald                         // initiator
2835c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
283645a61d50SMatthias Ringwald                     }
283745a61d50SMatthias Ringwald                 } else {
283840c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
283942134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2840e53be891SMatthias Ringwald                         // responder
284147fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
284240c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2843901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
28442886623dSMatthias Ringwald                         } else {
284540c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
28462886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2847446a8c36SMatthias Ringwald                         }
2848e53be891SMatthias Ringwald                     } else {
2849136d331aSMatthias Ringwald                         // initiator
2850c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2851e53be891SMatthias Ringwald                     }
285245a61d50SMatthias Ringwald                 }
2853687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2854e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2855e53be891SMatthias Ringwald                 break;
2856e53be891SMatthias Ringwald             }
2857c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2858e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2859e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2860e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2861dc300847SMatthias Ringwald 
286242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2863c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2864e53be891SMatthias Ringwald                 } else {
2865c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2866e53be891SMatthias Ringwald                 }
2867e083ca23SMatthias Ringwald 
2868687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2869e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2870e53be891SMatthias Ringwald                 break;
2871e53be891SMatthias Ringwald             }
2872e53be891SMatthias Ringwald 
2873e53be891SMatthias Ringwald #endif
287442134bc6SMatthias Ringwald 
287542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2876dd12a62bSMatthias Ringwald 
287787014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
287887014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
287987014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2880687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2881c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
288287014f74SMatthias Ringwald 				break;
288387014f74SMatthias Ringwald 			}
288487014f74SMatthias Ringwald 
288538196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
288638196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
288738196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
288838196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
288938196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
289038196718SMatthias Ringwald 						// start using context by loading security info
289138196718SMatthias Ringwald 						sm_reset_setup();
289238196718SMatthias Ringwald 						sm_load_security_info(connection);
289338196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
289438196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
289538196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
289642646f38SMatthias Ringwald                             sm_reencryption_started(connection);
289738196718SMatthias Ringwald                             sm_trigger_run();
289838196718SMatthias Ringwald 							break;
289938196718SMatthias Ringwald 						}
290038196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
290138196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
290238196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
290338196718SMatthias Ringwald 						return;
290438196718SMatthias Ringwald 					default:
290538196718SMatthias Ringwald 						// just wait until IRK lookup is completed
290638196718SMatthias Ringwald 						break;
290738196718SMatthias Ringwald 				}
290838196718SMatthias Ringwald 				break;
290938196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
291038196718SMatthias Ringwald 
2911b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2912b6afa23eSMatthias Ringwald                 sm_reset_setup();
29139b75de03SMatthias Ringwald 
29149b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
29159b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
29169b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
29179b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
29189b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
29199b75de03SMatthias Ringwald                         if (have_ltk){
29209b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
292119a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
29229b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
29239b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
29249b75de03SMatthias Ringwald                         }
29259b75de03SMatthias Ringwald                         break;
29269b75de03SMatthias Ringwald                     default:
29279b75de03SMatthias Ringwald                         break;
29289b75de03SMatthias Ringwald                 }
29299b75de03SMatthias Ringwald 
2930b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2931d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
293239543d07SMatthias Ringwald 
2933b6afa23eSMatthias Ringwald 				// recover pairing request
2934b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2935b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2936b6afa23eSMatthias Ringwald 
2937b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2938b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2939b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2940b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2941b6afa23eSMatthias Ringwald                     }
2942b6afa23eSMatthias Ringwald #endif
29439305033eSMatthias Ringwald 				if (err != 0){
2944f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2945b6afa23eSMatthias Ringwald 					sm_trigger_run();
2946b6afa23eSMatthias Ringwald 					break;
2947b6afa23eSMatthias Ringwald 				}
2948b6afa23eSMatthias Ringwald 
2949b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2950b6afa23eSMatthias Ringwald 
2951b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2952b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2953b6afa23eSMatthias 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);
2954b6afa23eSMatthias Ringwald 					break;
2955b6afa23eSMatthias Ringwald 				}
2956b6afa23eSMatthias Ringwald 
2957b6afa23eSMatthias Ringwald 				/* fall through */
2958b6afa23eSMatthias Ringwald 
29593deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29601ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2961f55bd529SMatthias Ringwald 
2962f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29633deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29641ad129beSMatthias Ringwald 
2965f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2966f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2967f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2968f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2969f55bd529SMatthias Ringwald                 }
2970f55bd529SMatthias Ringwald #endif
2971f55bd529SMatthias Ringwald                 // setup in response
2972f55bd529SMatthias 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);
2973f55bd529SMatthias 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);
2974f55bd529SMatthias Ringwald 
2975f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29769a90d41aSMatthias 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));
2977f55bd529SMatthias Ringwald 
297827c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2979c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29800b8af2a5SMatthias Ringwald                 } else {
29810b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
298227c32905SMatthias Ringwald                 }
29830b8af2a5SMatthias Ringwald 
2984687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29853deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2986446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2987c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29883deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2989446a8c36SMatthias Ringwald                 }
29903deb3ec6SMatthias Ringwald                 return;
299142134bc6SMatthias Ringwald #endif
29923deb3ec6SMatthias Ringwald 
29933deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29943deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29953deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29969c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
299742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29983deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29993deb3ec6SMatthias Ringwald                 } else {
30003deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
30013deb3ec6SMatthias Ringwald                 }
3002687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30033deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30043deb3ec6SMatthias Ringwald                 break;
30053deb3ec6SMatthias Ringwald             }
30063deb3ec6SMatthias Ringwald 
3007d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
30083deb3ec6SMatthias Ringwald                 // already busy?
30093deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3010d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
3011d1a1f6a4SMatthias 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);
3012d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
3013d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3014f3582630SMatthias 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);
30153deb3ec6SMatthias Ringwald                 break;
30163deb3ec6SMatthias Ringwald 
30173deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
30183deb3ec6SMatthias Ringwald                 // already busy?
30193deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30203deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
3021d1a1f6a4SMatthias 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);
3022d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
3023d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3024f3582630SMatthias 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);
30253deb3ec6SMatthias Ringwald                 break;
3026d1a1f6a4SMatthias Ringwald 
30273deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
30283deb3ec6SMatthias Ringwald                 // already busy?
30293deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30303deb3ec6SMatthias Ringwald                 // calculate STK
303142134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
3032d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
30333deb3ec6SMatthias Ringwald                 } else {
3034d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
30353deb3ec6SMatthias Ringwald                 }
3036d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
3037d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3038f3582630SMatthias 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);
30393deb3ec6SMatthias Ringwald                 break;
3040d1a1f6a4SMatthias Ringwald 
30413deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
30423deb3ec6SMatthias Ringwald                 // already busy?
30433deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30443deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
30459ad0dd7cSMatthias Ringwald 
30469ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
30479ad0dd7cSMatthias Ringwald                 // r' = padding || r
30489ad0dd7cSMatthias Ringwald                 // r - 64 bit value
30499ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30506535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
30519ad0dd7cSMatthias Ringwald 
30523deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3053d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
3054d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3055f3582630SMatthias 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);
3056d1a1f6a4SMatthias Ringwald                 break;
3057d1a1f6a4SMatthias Ringwald 
30583deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30593deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30603deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30619c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
306242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30633deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30643deb3ec6SMatthias Ringwald                 } else {
30653deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30663deb3ec6SMatthias Ringwald                 }
3067687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30683deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30693deb3ec6SMatthias Ringwald                 return;
30703deb3ec6SMatthias Ringwald             }
307142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30723deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30733deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30749c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30753deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30763deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30773deb3ec6SMatthias Ringwald                 return;
30783deb3ec6SMatthias Ringwald             }
3079d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3080b96d60a6SMatthias Ringwald                 // allow to override LTK
3081b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3082b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3083b96d60a6SMatthias Ringwald                 }
30843deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30859c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30865567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30873deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30883deb3ec6SMatthias Ringwald                 return;
30893deb3ec6SMatthias Ringwald             }
3090dd12a62bSMatthias Ringwald 
3091dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30923deb3ec6SMatthias Ringwald                 // already busy?
30933deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30943deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3095c61cfe5aSMatthias Ringwald 
3096dd12a62bSMatthias Ringwald 				sm_reset_setup();
3097dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3098dd12a62bSMatthias Ringwald 
309942646f38SMatthias Ringwald 				sm_reencryption_started(connection);
310042646f38SMatthias Ringwald 
3101c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3102c61cfe5aSMatthias Ringwald                 // r' = padding || r
3103c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3104c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
31056535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3106c61cfe5aSMatthias Ringwald 
31073deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3108d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3109d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3110f3582630SMatthias 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);
31113deb3ec6SMatthias Ringwald                 return;
311242134bc6SMatthias Ringwald #endif
311342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
311442134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
311542134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
311642134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
311742134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
311842134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
311942134bc6SMatthias Ringwald                 return;
312042134bc6SMatthias Ringwald             }
312142134bc6SMatthias Ringwald #endif
31223deb3ec6SMatthias Ringwald 
31233deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3124e94757aeSMatthias Ringwald                 // send next key
3125403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3126403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
3127e94757aeSMatthias Ringwald                 }
3128e94757aeSMatthias Ringwald 
3129e94757aeSMatthias Ringwald                 // more to send?
3130e94757aeSMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
31313deb3ec6SMatthias Ringwald                     return;
31323deb3ec6SMatthias Ringwald                 }
31333deb3ec6SMatthias Ringwald 
31343deb3ec6SMatthias Ringwald                 // keys are sent
313542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
31363deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
313761d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
31383deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3139f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3140f5020412SMatthias Ringwald                         // start CTKD right away
3141f5020412SMatthias Ringwald                         continue;
31423deb3ec6SMatthias Ringwald                     } else {
31433deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
31443deb3ec6SMatthias Ringwald                     }
31453deb3ec6SMatthias Ringwald                 } else {
31461dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
31473deb3ec6SMatthias Ringwald                 }
31483deb3ec6SMatthias Ringwald                 break;
31493deb3ec6SMatthias Ringwald 
3150c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3151c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3152c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3153c18be159SMatthias Ringwald                 sm_reset_setup();
3154c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3155c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3156c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3157c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3158c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3159c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3160c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3161c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3162c18be159SMatthias Ringwald 
3163c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3164c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3165c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3166c18be159SMatthias Ringwald                 // Plus signing key if supported
3167c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3168c18be159SMatthias Ringwald #endif
3169c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3170c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3171c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3172c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3173c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3174c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3175c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3176c18be159SMatthias Ringwald 
3177c18be159SMatthias Ringwald                 // set state and send pairing response
3178c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3179c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3180c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3181c18be159SMatthias Ringwald                 break;
3182c18be159SMatthias Ringwald 
3183c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3184c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3185c18be159SMatthias Ringwald                 sm_reset_setup();
3186c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3187c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3188c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3189c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3190c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3191c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3192c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3193c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3194c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3195c18be159SMatthias Ringwald 
3196c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3197c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3198c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3199c18be159SMatthias Ringwald                 // Plus signing key if supported
3200c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3201c18be159SMatthias Ringwald #endif
3202c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3203c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3204c18be159SMatthias Ringwald 
3205c18be159SMatthias 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:
3206c18be159SMatthias Ringwald                 // - the IO Capability field,
3207c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3208c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3209c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3210c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3211c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3212c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3213c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3214c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3215c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3216c18be159SMatthias Ringwald 
3217c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3218c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3219c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3220c18be159SMatthias Ringwald 
3221c18be159SMatthias Ringwald                 // set state and send pairing response
3222c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3223c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3224c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3225c18be159SMatthias Ringwald                 break;
3226c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3227c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3228c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3229c18be159SMatthias Ringwald                     return;
3230c18be159SMatthias Ringwald                 }
3231c18be159SMatthias Ringwald                 // keys are sent
3232c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3233c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
323461d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3235c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3236c18be159SMatthias Ringwald                         break;
3237c18be159SMatthias Ringwald                     }
3238c18be159SMatthias Ringwald                 }
3239c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3240c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3241c18be159SMatthias Ringwald                 continue;
3242c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3243c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3244c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3245c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3246c18be159SMatthias Ringwald                 break;
3247c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3248c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3249c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3250c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3251c18be159SMatthias Ringwald                 break;
3252c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3253c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3254c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3255c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3256c18be159SMatthias Ringwald                 break;
3257c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3258c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3259c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3260c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3261c18be159SMatthias Ringwald                 break;
3262c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3263c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3264c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3265c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3266c18be159SMatthias Ringwald                 break;
3267c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3268c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3269c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3270c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3271c18be159SMatthias Ringwald                 break;
3272c18be159SMatthias Ringwald #endif
3273c18be159SMatthias Ringwald 
32743deb3ec6SMatthias Ringwald             default:
32753deb3ec6SMatthias Ringwald                 break;
32763deb3ec6SMatthias Ringwald         }
32773deb3ec6SMatthias Ringwald 
32783deb3ec6SMatthias Ringwald         // check again if active connection was released
32797149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32803deb3ec6SMatthias Ringwald     }
32813deb3ec6SMatthias Ringwald }
32823deb3ec6SMatthias Ringwald 
3283d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3284d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3285f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
328604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
328704678764SMatthias Ringwald 
3288f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3289f3582630SMatthias Ringwald     if (connection == NULL) return;
3290f3582630SMatthias Ringwald 
3291d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
329204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3293f3582630SMatthias 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);
3294d1a1f6a4SMatthias Ringwald }
32953deb3ec6SMatthias Ringwald 
3296d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3297f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
329804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329904678764SMatthias Ringwald 
3300f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3301f3582630SMatthias Ringwald     if (connection == NULL) return;
3302f3582630SMatthias Ringwald 
33038314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
33043deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
330570b44dd4SMatthias Ringwald     sm_trigger_run();
3306d1a1f6a4SMatthias Ringwald }
3307d1a1f6a4SMatthias Ringwald 
3308d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3309d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3310f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
331104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
331204678764SMatthias Ringwald 
3313f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3314f3582630SMatthias Ringwald     if (connection == NULL) return;
3315f3582630SMatthias Ringwald 
3316d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
331704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3318f3582630SMatthias 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);
3319d1a1f6a4SMatthias Ringwald }
3320d1a1f6a4SMatthias Ringwald 
3321d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3322f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
332304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
332404678764SMatthias Ringwald 
3325f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3326f3582630SMatthias Ringwald     if (connection == NULL) return;
3327f3582630SMatthias Ringwald 
3328d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3329d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3330f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
333170b44dd4SMatthias Ringwald         sm_trigger_run();
33323deb3ec6SMatthias Ringwald         return;
33333deb3ec6SMatthias Ringwald     }
333442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33353deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
333670b44dd4SMatthias Ringwald         sm_trigger_run();
33373deb3ec6SMatthias Ringwald     } else {
3338d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3339d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3340f3582630SMatthias 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);
33413deb3ec6SMatthias Ringwald     }
33423deb3ec6SMatthias Ringwald }
3343d1a1f6a4SMatthias Ringwald 
3344d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
334504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3346f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
334704678764SMatthias Ringwald 
3348f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3349f3582630SMatthias Ringwald     if (connection == NULL) return;
3350f3582630SMatthias Ringwald 
33513deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33528314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
335342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33543deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
33553deb3ec6SMatthias Ringwald     } else {
33563deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
33573deb3ec6SMatthias Ringwald     }
335870b44dd4SMatthias Ringwald     sm_trigger_run();
3359d1a1f6a4SMatthias Ringwald }
3360d1a1f6a4SMatthias Ringwald 
3361d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3362d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3363f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
336404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
336504678764SMatthias Ringwald 
3366f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3367f3582630SMatthias Ringwald     if (connection == NULL) return;
3368f3582630SMatthias Ringwald 
3369d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33703deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33713deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33723deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33733deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33743deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33753deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3376d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
337704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3378f3582630SMatthias 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);
33793deb3ec6SMatthias Ringwald }
3380d1a1f6a4SMatthias Ringwald 
33812a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3382d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3383d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
338404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3385f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
338604678764SMatthias Ringwald 
3387f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3388f3582630SMatthias Ringwald     if (connection == NULL) return;
3389f3582630SMatthias Ringwald 
3390d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33913deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33923deb3ec6SMatthias Ringwald 
33933deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33943deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33953deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33963deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33973deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3398d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
339904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3400f3582630SMatthias 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);
34013deb3ec6SMatthias Ringwald }
34022a526f21SMatthias Ringwald #endif
3403d1a1f6a4SMatthias Ringwald 
3404d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3406f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
340704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
340804678764SMatthias Ringwald 
3409f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3410f3582630SMatthias Ringwald     if (connection == NULL) return;
3411f3582630SMatthias Ringwald 
34128314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
34133deb3ec6SMatthias Ringwald     // calc CSRK next
3414d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
341504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3416f3582630SMatthias 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);
3417d1a1f6a4SMatthias Ringwald }
3418d1a1f6a4SMatthias Ringwald 
3419d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3420f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
342104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342204678764SMatthias Ringwald 
3423f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3424f3582630SMatthias Ringwald     if (connection == NULL) return;
3425f3582630SMatthias Ringwald 
3426d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
34278314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
34283deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
34293deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
34303deb3ec6SMatthias Ringwald     } else {
34313deb3ec6SMatthias Ringwald         // no keys to send, just continue
343242134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
343361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3434c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3435c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3436c5a72e35SMatthias Ringwald             } else {
34373deb3ec6SMatthias Ringwald                 // slave -> receive master keys
34383deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3439c5a72e35SMatthias Ringwald             }
34403deb3ec6SMatthias Ringwald         } else {
3441af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
34423deb3ec6SMatthias Ringwald         }
34432bacf595SMatthias Ringwald     }
344470b44dd4SMatthias Ringwald     sm_trigger_run();
3445d1a1f6a4SMatthias Ringwald }
3446d1a1f6a4SMatthias Ringwald 
344742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3448d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3449f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
345004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
345104678764SMatthias Ringwald 
3452f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3453f3582630SMatthias Ringwald     if (connection == NULL) return;
3454f3582630SMatthias Ringwald 
34553deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
34568314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3457d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
345870b44dd4SMatthias Ringwald     sm_trigger_run();
3459d1a1f6a4SMatthias Ringwald }
3460d1a1f6a4SMatthias Ringwald #endif
3461d1a1f6a4SMatthias Ringwald 
3462d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3463d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3464d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
346504678764SMatthias Ringwald 
3466d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3467d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3468d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3469d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3470d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3471a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
347270b44dd4SMatthias Ringwald         sm_trigger_run();
34733deb3ec6SMatthias Ringwald         return;
34743deb3ec6SMatthias Ringwald     }
3475d1a1f6a4SMatthias Ringwald     // no match, try next
3476d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
347770b44dd4SMatthias Ringwald     sm_trigger_run();
34783deb3ec6SMatthias Ringwald }
34793deb3ec6SMatthias Ringwald 
3480d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3481d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3482d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
348304678764SMatthias Ringwald 
3484d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3485d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
348670b44dd4SMatthias Ringwald     sm_trigger_run();
34877df18c15SMatthias Ringwald }
3488d1a1f6a4SMatthias Ringwald 
3489d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3490d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3491d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
349204678764SMatthias Ringwald 
3493d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3494d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
349570b44dd4SMatthias Ringwald     sm_trigger_run();
34967df18c15SMatthias Ringwald }
3497d1a1f6a4SMatthias Ringwald 
3498d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3499d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3500d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
350104678764SMatthias Ringwald 
35026535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3503e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3504e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3505e91ddb40SMatthias Ringwald 
350670b44dd4SMatthias Ringwald     sm_trigger_run();
350751fa0b28SMatthias Ringwald }
35087df18c15SMatthias Ringwald 
3509d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3510d1a1f6a4SMatthias Ringwald     UNUSED(arg);
35113deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
35123deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
35133deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
35143deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
35153deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
35164ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35174ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
35183deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
35193deb3ec6SMatthias Ringwald             break;
35203deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
35213deb3ec6SMatthias Ringwald         default:
35223deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
35234ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35242954e6c6SMatthias Ringwald             rau_state = RAU_IDLE;
3525e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
35263deb3ec6SMatthias Ringwald             break;
35273deb3ec6SMatthias Ringwald     }
352870b44dd4SMatthias Ringwald     sm_trigger_run();
35293deb3ec6SMatthias Ringwald }
35303deb3ec6SMatthias Ringwald 
3531c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
35326ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3533f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3534f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3535f3582630SMatthias Ringwald     if (connection == NULL) return;
3536c59d0c92SMatthias Ringwald 
353765a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
353870b44dd4SMatthias Ringwald     sm_trigger_run();
353965a9a04eSMatthias Ringwald }
3540d1a1f6a4SMatthias Ringwald 
35416ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
35426ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
35436ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
35446ca80073SMatthias Ringwald     if (connection == NULL) return;
35456ca80073SMatthias Ringwald 
3546b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
354770b44dd4SMatthias Ringwald     sm_trigger_run();
3548d1a1f6a4SMatthias Ringwald }
3549f1c1783eSMatthias Ringwald #endif
3550f1c1783eSMatthias Ringwald 
3551d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3552f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3553f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3554f3582630SMatthias Ringwald     if (connection == NULL) return;
3555f3582630SMatthias Ringwald 
3556d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
355770b44dd4SMatthias Ringwald     sm_trigger_run();
3558d1a1f6a4SMatthias Ringwald }
3559d1a1f6a4SMatthias Ringwald 
3560d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3561f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3562f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3563f3582630SMatthias Ringwald     if (connection == NULL) return;
3564f3582630SMatthias Ringwald 
3565caf15bf3SMatthias Ringwald     sm_reset_tk();
3566caf15bf3SMatthias Ringwald     uint32_t tk;
35675ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
35683deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3569d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
35703deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35714ea43905SMatthias Ringwald         if (tk >= 999999u){
35724ea43905SMatthias Ringwald             tk = tk - 999999u;
35733deb3ec6SMatthias Ringwald         }
3574caf15bf3SMatthias Ringwald     } else {
3575caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35764b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3577caf15bf3SMatthias Ringwald     }
3578f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
357942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35803deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35813deb3ec6SMatthias Ringwald     } else {
3582b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3583b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3584b41539d5SMatthias Ringwald         } else {
35853deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35863deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35873deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35883deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3589f3582630SMatthias 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);
35903deb3ec6SMatthias Ringwald             }
35913deb3ec6SMatthias Ringwald         }
3592b41539d5SMatthias Ringwald     }
359370b44dd4SMatthias Ringwald     sm_trigger_run();
35943deb3ec6SMatthias Ringwald }
3595d1a1f6a4SMatthias Ringwald 
3596d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3597f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3598f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3599f3582630SMatthias Ringwald     if (connection == NULL) return;
3600f3582630SMatthias Ringwald 
3601d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3602d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3603d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3604d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
360570b44dd4SMatthias Ringwald     sm_trigger_run();
3606d1a1f6a4SMatthias Ringwald }
3607d1a1f6a4SMatthias Ringwald 
3608d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3609f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3610f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3611f3582630SMatthias Ringwald     if (connection == NULL) return;
3612f3582630SMatthias Ringwald 
3613d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
36143deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
36154ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
36163deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
36174ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
36188b3ffec5SMatthias 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);
36193deb3ec6SMatthias Ringwald }
3620899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3621899e6e02SMatthias Ringwald     // warn about default ER/IR
36221979f09cSMatthias Ringwald     bool warning = false;
3623899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
36241979f09cSMatthias Ringwald         warning = true;
3625899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3626899e6e02SMatthias Ringwald     }
3627899e6e02SMatthias Ringwald     if (sm_er_is_default()){
36281979f09cSMatthias Ringwald         warning = true;
3629899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3630899e6e02SMatthias Ringwald     }
363121045273SMatthias Ringwald     if (warning) {
3632899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3633899e6e02SMatthias Ringwald     }
363421045273SMatthias Ringwald }
3635899e6e02SMatthias Ringwald 
3636899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
36371979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36389305033eSMatthias Ringwald     if (arg != NULL){
3639899e6e02SMatthias Ringwald         // key generated, store in tlv
36404ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3641899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3642e0d13a19SMilanka Ringwald         UNUSED(status);
3643899e6e02SMatthias Ringwald     }
3644899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
36458d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3646841468bbSMatthias Ringwald 
3647841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3648841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3649841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3650841468bbSMatthias Ringwald     }
3651841468bbSMatthias Ringwald 
365270b44dd4SMatthias Ringwald     sm_trigger_run();
3653899e6e02SMatthias Ringwald }
3654899e6e02SMatthias Ringwald 
3655899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
36561979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36579305033eSMatthias Ringwald     if (arg != 0){
3658899e6e02SMatthias Ringwald         // key generated, store in tlv
36594ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3660899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3661e0d13a19SMilanka Ringwald         UNUSED(status);
3662899e6e02SMatthias Ringwald     }
3663899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3664899e6e02SMatthias Ringwald 
3665899e6e02SMatthias Ringwald     // try load ir
36664ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3667899e6e02SMatthias Ringwald     if (key_size == 16){
3668899e6e02SMatthias Ringwald         // ok, let's continue
3669899e6e02SMatthias Ringwald         log_info("IR from TLV");
3670899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3671899e6e02SMatthias Ringwald     } else {
3672899e6e02SMatthias Ringwald         // invalid, generate new random one
36731979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3674899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3675899e6e02SMatthias Ringwald     }
3676899e6e02SMatthias Ringwald }
36773deb3ec6SMatthias Ringwald 
3678f664b5e8SMatthias 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){
3679f664b5e8SMatthias Ringwald 
3680f664b5e8SMatthias Ringwald     // connection info
3681f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3682f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3683f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3684f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3685f664b5e8SMatthias Ringwald 
3686f664b5e8SMatthias Ringwald     // security properties
3687f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3688f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3689f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3690f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3691f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3692f664b5e8SMatthias Ringwald 
3693f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3694f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3695f664b5e8SMatthias Ringwald 
3696f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3697f664b5e8SMatthias Ringwald }
3698f664b5e8SMatthias Ringwald 
3699d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
37003deb3ec6SMatthias Ringwald 
3701cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3702cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
37039ec2630cSMatthias Ringwald 
37043deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3705711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3706fbe050beSMatthias Ringwald     uint8_t           status;
3707f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3708f664b5e8SMatthias Ringwald 
37093deb3ec6SMatthias Ringwald     switch (packet_type) {
37103deb3ec6SMatthias Ringwald 
37113deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
37120e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
37133deb3ec6SMatthias Ringwald 
37143deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
3715745015f6SMatthias Ringwald                     switch (btstack_event_state_get_state(packet)){
3716745015f6SMatthias Ringwald                         case HCI_STATE_WORKING:
37173deb3ec6SMatthias Ringwald                             log_info("HCI Working!");
3718899e6e02SMatthias Ringwald                             // setup IR/ER with TLV
3719899e6e02SMatthias Ringwald                             btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
37209305033eSMatthias Ringwald                             if (sm_tlv_impl != NULL){
37214ea43905SMatthias Ringwald                                 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3722899e6e02SMatthias Ringwald                                 if (key_size == 16){
3723899e6e02SMatthias Ringwald                                     // ok, let's continue
3724899e6e02SMatthias Ringwald                                     log_info("ER from TLV");
3725899e6e02SMatthias Ringwald                                     sm_handle_random_result_er( NULL );
3726899e6e02SMatthias Ringwald                                 } else {
3727899e6e02SMatthias Ringwald                                     // invalid, generate random one
37281979f09cSMatthias Ringwald                                     sm_persistent_keys_random_active = true;
3729899e6e02SMatthias Ringwald                                     btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3730899e6e02SMatthias Ringwald                                 }
3731899e6e02SMatthias Ringwald                             } else {
3732899e6e02SMatthias Ringwald                                 sm_validate_er_ir();
37338d9b6072SMatthias Ringwald                                 dkg_state = DKG_CALC_IRK;
3734841468bbSMatthias Ringwald 
3735841468bbSMatthias Ringwald                                 if (test_use_fixed_local_irk){
3736841468bbSMatthias Ringwald                                     log_info_key("IRK", sm_persistent_irk);
3737841468bbSMatthias Ringwald                                     dkg_state = DKG_CALC_DHK;
3738841468bbSMatthias Ringwald                                 }
3739899e6e02SMatthias Ringwald                             }
37401bf086daSMatthias Ringwald 
374115211b85SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
374215211b85SMatthias Ringwald                             // trigger ECC key generation
374315211b85SMatthias Ringwald                             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
374415211b85SMatthias Ringwald                                 sm_ec_generate_new_key();
374515211b85SMatthias Ringwald                             }
374615211b85SMatthias Ringwald #endif
374715211b85SMatthias Ringwald 
37481bf086daSMatthias Ringwald                             // restart random address updates after power cycle
37494a688bd1SMatthias Ringwald                             if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){
37504a688bd1SMatthias Ringwald                                 gap_random_address_set(sm_random_address);
37514a688bd1SMatthias Ringwald                             } else {
37521bf086daSMatthias Ringwald                                 gap_random_address_set_mode(gap_random_adress_type);
37534a688bd1SMatthias Ringwald                             }
3754745015f6SMatthias Ringwald                             break;
3755745015f6SMatthias Ringwald 
3756745015f6SMatthias Ringwald                         case HCI_STATE_OFF:
37577f775357SMatthias Ringwald                         case HCI_STATE_HALTING:
3758cbdd51cfSMatthias Ringwald                             log_info("SM: reset state");
3759745015f6SMatthias Ringwald                             // stop random address update
3760745015f6SMatthias Ringwald                             gap_random_address_update_stop();
3761cbdd51cfSMatthias Ringwald                             // reset state
3762cbdd51cfSMatthias Ringwald                             sm_state_reset();
3763745015f6SMatthias Ringwald                             break;
3764745015f6SMatthias Ringwald 
3765745015f6SMatthias Ringwald                         default:
3766745015f6SMatthias Ringwald                             break;
37673deb3ec6SMatthias Ringwald                     }
37683deb3ec6SMatthias Ringwald 					break;
3769c18be159SMatthias Ringwald 
37702d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
37712d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
37722d095694SMatthias Ringwald 			        // ignore if connection failed
37732d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
37743deb3ec6SMatthias Ringwald 
37752d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
37762d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
37772d095694SMatthias Ringwald 			        if (!sm_conn) break;
37782d095694SMatthias Ringwald 
37792d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
37802d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
37812d095694SMatthias Ringwald                                        con_handle,
37822d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3783f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
37842d095694SMatthias Ringwald                                        addr);
37852d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
37862d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
37872d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
37882d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3789c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
37902d095694SMatthias Ringwald 			        break;
37912d095694SMatthias Ringwald #endif
3792c18be159SMatthias Ringwald 
3793c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3794c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3795c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3796c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3797c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3798c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3799c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3800c18be159SMatthias Ringwald 			        break;
3801c18be159SMatthias Ringwald #endif
3802c18be159SMatthias Ringwald 
38033deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
38043deb3ec6SMatthias Ringwald                     switch (packet[2]) {
38053deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3806f664b5e8SMatthias Ringwald                             // ignore if connection failed
3807f664b5e8SMatthias Ringwald                             if (packet[3]) return;
38083deb3ec6SMatthias Ringwald 
3809711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3810711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38113deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38123deb3ec6SMatthias Ringwald 
3813f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3814f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3815f664b5e8SMatthias Ringwald                                                con_handle,
3816f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3817f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3818f664b5e8SMatthias Ringwald                                                addr);
3819687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3820f664b5e8SMatthias Ringwald 
3821f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3822b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3823b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3824ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3825ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3826f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3827b892db1cSMatthias Ringwald                             }
3828b892db1cSMatthias Ringwald #endif
3829b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3830b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3831ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3832ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
38333deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38343deb3ec6SMatthias Ringwald                             }
3835b892db1cSMatthias Ringwald #endif
38363deb3ec6SMatthias Ringwald                             break;
38373deb3ec6SMatthias Ringwald 
38383deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3839711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3840711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38413deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38423deb3ec6SMatthias Ringwald 
38433deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
38443deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
38453deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
38463deb3ec6SMatthias Ringwald                                 break;
38473deb3ec6SMatthias Ringwald                             }
3848c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3849778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3850778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3851e53be891SMatthias Ringwald                                 break;
3852e53be891SMatthias Ringwald                             }
38533deb3ec6SMatthias Ringwald 
38543deb3ec6SMatthias Ringwald                             // store rand and ediv
38559c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3856f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3857549ad5d2SMatthias Ringwald 
3858549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3859549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
38604ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
38616c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
386206cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3863549ad5d2SMatthias Ringwald                                     break;
3864549ad5d2SMatthias Ringwald                                 }
38656c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
38666c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
38676c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
38686c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
38696c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
38706c39055aSMatthias Ringwald                                         break;
38716c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
38726c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
38736c39055aSMatthias Ringwald                                         break;
38746c39055aSMatthias Ringwald                                     default:
38756c39055aSMatthias Ringwald                                         // wait for irk look doen
38766c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
38776c39055aSMatthias Ringwald                                         break;
38786c39055aSMatthias Ringwald                                 }
38796c39055aSMatthias Ringwald                                 break;
38806c39055aSMatthias Ringwald                             }
3881549ad5d2SMatthias Ringwald 
3882549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
388306cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3884549ad5d2SMatthias Ringwald #else
3885549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3886549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3887549ad5d2SMatthias Ringwald #endif
38883deb3ec6SMatthias Ringwald                             break;
3889804d3e67SMatthias Ringwald 
38903deb3ec6SMatthias Ringwald                         default:
38913deb3ec6SMatthias Ringwald                             break;
38923deb3ec6SMatthias Ringwald                     }
38933deb3ec6SMatthias Ringwald                     break;
38943deb3ec6SMatthias Ringwald 
38953deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
38968601e696SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
38973b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3898711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38993deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39003deb3ec6SMatthias Ringwald 
39013b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
39023deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
39033deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
39043deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
390503a9359aSMatthias Ringwald 
3906fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3907fbe050beSMatthias Ringwald 
39085567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
390903a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3910fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3911fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
39128d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
39138d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39148d4eef95SMatthias Ringwald                                 } else {
391503a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39168d4eef95SMatthias Ringwald                                 }
3917fbe050beSMatthias Ringwald                             } else {
3918e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3919cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
39203b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3921cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
39223b7fd749SMatthias Ringwald                             }
3923fbe050beSMatthias Ringwald 
3924fbe050beSMatthias Ringwald                             // emit re-encryption complete
392573102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3926fbe050beSMatthias Ringwald 
3927c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3928c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3929c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
39300ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
393103a9359aSMatthias Ringwald                             }
393203a9359aSMatthias Ringwald 
39333deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39343deb3ec6SMatthias Ringwald                             break;
3935fbe050beSMatthias Ringwald 
39363deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3937fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3938dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
393942134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39403deb3ec6SMatthias Ringwald                                 // slave
3941bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3942bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3943bbf8db22SMatthias Ringwald                                 } else {
3944f3582630SMatthias 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);
3945bbf8db22SMatthias Ringwald                                 }
39463deb3ec6SMatthias Ringwald                             } else {
39473deb3ec6SMatthias Ringwald                                 // master
394861d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
39493deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
39503deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3951f3582630SMatthias 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);
39523deb3ec6SMatthias Ringwald                                 } else {
39533deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39543deb3ec6SMatthias Ringwald                                 }
39553deb3ec6SMatthias Ringwald                             }
39563deb3ec6SMatthias Ringwald                             break;
3957c18be159SMatthias Ringwald 
3958c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3959c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3960c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3961c18be159SMatthias Ringwald                             // prepare for pairing request
3962c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3963c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3964c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3965c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3966c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3967c18be159SMatthias Ringwald                             }
3968c18be159SMatthias Ringwald                             break;
3969c18be159SMatthias Ringwald #endif
39703deb3ec6SMatthias Ringwald                         default:
39713deb3ec6SMatthias Ringwald                             break;
39723deb3ec6SMatthias Ringwald                     }
39733deb3ec6SMatthias Ringwald                     break;
39743deb3ec6SMatthias Ringwald 
39753deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3976711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3977711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39783deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39793deb3ec6SMatthias Ringwald 
39803deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
39813deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
39823deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
39833deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39845567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
39855567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
39865567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39875567aa60SMatthias Ringwald                             } else {
39883deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39895567aa60SMatthias Ringwald                             }
39903deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39913deb3ec6SMatthias Ringwald                             break;
39923deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
399342134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39943deb3ec6SMatthias Ringwald                                 // slave
3995f3582630SMatthias 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);
39963deb3ec6SMatthias Ringwald                             } else {
39973deb3ec6SMatthias Ringwald                                 // master
39983deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39993deb3ec6SMatthias Ringwald                             }
40003deb3ec6SMatthias Ringwald                             break;
40013deb3ec6SMatthias Ringwald                         default:
40023deb3ec6SMatthias Ringwald                             break;
40033deb3ec6SMatthias Ringwald                     }
40043deb3ec6SMatthias Ringwald                     break;
40053deb3ec6SMatthias Ringwald 
40063deb3ec6SMatthias Ringwald 
40073deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
4008711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
4009711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
4010711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
40113deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
40123deb3ec6SMatthias Ringwald 
401303f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
40147f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
40157f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
40167f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
40177f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
40187f3f442dSMatthias Ringwald                             break;
40197f3f442dSMatthias Ringwald                         default:
402068a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
40210ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
40227f3f442dSMatthias Ringwald                             break;
402303f736b1SMatthias Ringwald                     }
4024accbde80SMatthias Ringwald 
40253deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
40263deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
40273deb3ec6SMatthias Ringwald                     break;
40283deb3ec6SMatthias Ringwald 
40293deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
4030f7811256SMatthias Ringwald                     if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) {
40319091c5f5SMatthias Ringwald                         // set local addr for le device db
403233373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
40330c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
403433373e40SMatthias Ringwald                     }
403565b44ffdSMatthias Ringwald                     break;
403665b44ffdSMatthias Ringwald                 default:
403765b44ffdSMatthias Ringwald                     break;
40383deb3ec6SMatthias Ringwald 			}
403965b44ffdSMatthias Ringwald             break;
404065b44ffdSMatthias Ringwald         default:
404165b44ffdSMatthias Ringwald             break;
40423deb3ec6SMatthias Ringwald 	}
40433deb3ec6SMatthias Ringwald 
40443deb3ec6SMatthias Ringwald     sm_run();
40453deb3ec6SMatthias Ringwald }
40463deb3ec6SMatthias Ringwald 
40473deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
40483deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
40493deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
40503deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
40513deb3ec6SMatthias Ringwald }
40523deb3ec6SMatthias Ringwald 
4053945888f5SMatthias Ringwald 
405431c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4055945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
4056945888f5SMatthias Ringwald     switch (method){
4057945888f5SMatthias Ringwald         case JUST_WORKS:
405847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
4059945888f5SMatthias Ringwald             return 1;
4060945888f5SMatthias Ringwald         default:
4061945888f5SMatthias Ringwald             return 0;
4062945888f5SMatthias Ringwald     }
4063945888f5SMatthias Ringwald }
406407036a04SMatthias Ringwald // responder
4065945888f5SMatthias Ringwald 
4066688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
4067688a08f9SMatthias Ringwald     switch (method){
4068688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
4069688a08f9SMatthias Ringwald             return 1;
4070688a08f9SMatthias Ringwald         default:
4071688a08f9SMatthias Ringwald             return 0;
4072688a08f9SMatthias Ringwald     }
4073688a08f9SMatthias Ringwald }
407440c5d850SMatthias Ringwald 
407540c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
407640c5d850SMatthias Ringwald     switch (method){
407740c5d850SMatthias Ringwald         case PK_RESP_INPUT:
407840c5d850SMatthias Ringwald         case PK_INIT_INPUT:
407947fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
408040c5d850SMatthias Ringwald             return 1;
408140c5d850SMatthias Ringwald         default:
408240c5d850SMatthias Ringwald             return 0;
408340c5d850SMatthias Ringwald     }
408440c5d850SMatthias Ringwald }
408540c5d850SMatthias Ringwald 
408631c09488SMatthias Ringwald #endif
4087688a08f9SMatthias Ringwald 
40883deb3ec6SMatthias Ringwald /**
40893deb3ec6SMatthias Ringwald  * @return ok
40903deb3ec6SMatthias Ringwald  */
40913deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
40923deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
40933deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
40943deb3ec6SMatthias Ringwald         case JUST_WORKS:
40954ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
40963deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
40973deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
409847fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
40994ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
41003deb3ec6SMatthias Ringwald         case OOB:
41014ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
410247fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
41034ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
41043deb3ec6SMatthias Ringwald         default:
41053deb3ec6SMatthias Ringwald             return 0;
41063deb3ec6SMatthias Ringwald     }
41073deb3ec6SMatthias Ringwald }
41083deb3ec6SMatthias Ringwald 
410936f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
411036f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
411136f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
411236f0defaSMatthias Ringwald     if (sm_sc_only_mode){
411336f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
411436f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
411536f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
411636f0defaSMatthias Ringwald             return;
411736f0defaSMatthias Ringwald         }
411836f0defaSMatthias Ringwald     }
411936f0defaSMatthias Ringwald #else
412036f0defaSMatthias Ringwald     UNUSED(packet);
412136f0defaSMatthias Ringwald #endif
412236f0defaSMatthias Ringwald 
412336f0defaSMatthias Ringwald     int have_ltk;
412436f0defaSMatthias Ringwald     uint8_t ltk[16];
412536f0defaSMatthias Ringwald 
412636f0defaSMatthias Ringwald     // IRK complete?
412736f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
412836f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
412936f0defaSMatthias Ringwald             // start pairing
413036f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
413136f0defaSMatthias Ringwald             break;
413236f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
413336f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
413436f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
413536f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
413636f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
413736f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
413836f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
413936f0defaSMatthias Ringwald             } else {
414036f0defaSMatthias Ringwald                 // start pairing
414136f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
414236f0defaSMatthias Ringwald             }
414336f0defaSMatthias Ringwald             break;
414436f0defaSMatthias Ringwald         default:
414536f0defaSMatthias Ringwald             // otherwise, store security request
414636f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
414736f0defaSMatthias Ringwald             break;
414836f0defaSMatthias Ringwald     }
414936f0defaSMatthias Ringwald }
415036f0defaSMatthias Ringwald #endif
415136f0defaSMatthias Ringwald 
41528334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
41538334d3d8SMatthias Ringwald 
41544c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
41554c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
41564c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
41574c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
41584c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
41594c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
41604c1d1092SMatthias Ringwald             17, // 0x04 pairing random
41614c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
41624c1d1092SMatthias Ringwald             17, // 0x06 encryption information
41637a2e6387SMatthias Ringwald             11, // 0x07 master identification
41644c1d1092SMatthias Ringwald             17, // 0x08 identification information
41654c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
41664c1d1092SMatthias Ringwald             17, // 0x0a signing information
41674c1d1092SMatthias Ringwald             2,  // 0x0b security request
41684c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
41694c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
41704c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
41714c1d1092SMatthias Ringwald     };
41723deb3ec6SMatthias Ringwald 
4173c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4174b170b20fSMatthias Ringwald         sm_run();
4175b170b20fSMatthias Ringwald     }
4176b170b20fSMatthias Ringwald 
41773deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
41784ea43905SMatthias Ringwald     if (size == 0u) return;
41794c1d1092SMatthias Ringwald 
41804c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
41814c1d1092SMatthias Ringwald 
41824c1d1092SMatthias Ringwald     // validate pdu size
41834c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
41847a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
41853deb3ec6SMatthias Ringwald 
4186711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
41873deb3ec6SMatthias Ringwald     if (!sm_conn) return;
41883deb3ec6SMatthias Ringwald 
41894c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
419068a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
41910ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4192accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
41933deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
41943deb3ec6SMatthias Ringwald         return;
41953deb3ec6SMatthias Ringwald     }
41963deb3ec6SMatthias Ringwald 
41974c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
41983deb3ec6SMatthias Ringwald 
41993deb3ec6SMatthias Ringwald     int err;
420042134bc6SMatthias Ringwald     UNUSED(err);
42013deb3ec6SMatthias Ringwald 
42024c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
42033d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
42043d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
42053d7fe1e9SMatthias Ringwald         buffer[1] = 3;
42063d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
42073d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
42083d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
42093d7fe1e9SMatthias Ringwald         return;
42103d7fe1e9SMatthias Ringwald     }
42113d7fe1e9SMatthias Ringwald 
42123deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
42133deb3ec6SMatthias Ringwald 
4214c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
42153deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
42163deb3ec6SMatthias Ringwald             return;
42173deb3ec6SMatthias Ringwald 
421842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
421942134bc6SMatthias Ringwald 
42203deb3ec6SMatthias Ringwald         // Initiator
42213deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
42224c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
42233deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42243deb3ec6SMatthias Ringwald                 break;
42253deb3ec6SMatthias Ringwald             }
422636f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4227dc8ca372SMatthias Ringwald             break;
42283deb3ec6SMatthias Ringwald 
42293deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4230aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4231aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4232aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4233aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4234aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4235aacfafc3SMatthias Ringwald                 break;
4236aacfafc3SMatthias Ringwald             }
4237aacfafc3SMatthias Ringwald 
4238aacfafc3SMatthias Ringwald             // all other pdus are incorrect
42394c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
42403deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42413deb3ec6SMatthias Ringwald                 break;
42423deb3ec6SMatthias Ringwald             }
42430af429c6SMatthias Ringwald 
42443deb3ec6SMatthias Ringwald             // store pairing request
42456535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
42466535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
42473deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
42480af429c6SMatthias Ringwald 
42490af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
42500af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
42510af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
42520af429c6SMatthias Ringwald                 err = test_pairing_failure;
42530af429c6SMatthias Ringwald             }
42540af429c6SMatthias Ringwald #endif
42550af429c6SMatthias Ringwald 
42569305033eSMatthias Ringwald             if (err != 0){
4257f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
42583deb3ec6SMatthias Ringwald                 break;
42593deb3ec6SMatthias Ringwald             }
4260b41539d5SMatthias Ringwald 
4261b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4262b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4263f3582630SMatthias 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);
4264b41539d5SMatthias Ringwald                 break;
4265b41539d5SMatthias Ringwald             }
4266b41539d5SMatthias Ringwald 
4267136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4268136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
42698cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
42708cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4271136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4272136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4273136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4274c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4275136d331aSMatthias Ringwald                     }
42768cba5ca3SMatthias Ringwald                 } else {
4277c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
42788cba5ca3SMatthias Ringwald                 }
4279136d331aSMatthias Ringwald                 break;
4280136d331aSMatthias Ringwald             }
4281136d331aSMatthias Ringwald #endif
42823deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42833deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
42843deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
42853deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4286f3582630SMatthias 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);
42873deb3ec6SMatthias Ringwald             }
42883deb3ec6SMatthias Ringwald             break;
42893deb3ec6SMatthias Ringwald 
42903deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
42914c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42923deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42933deb3ec6SMatthias Ringwald                 break;
42943deb3ec6SMatthias Ringwald             }
42953deb3ec6SMatthias Ringwald 
42963deb3ec6SMatthias Ringwald             // store s_confirm
42979c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4298192365feSMatthias Ringwald 
4299aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4300aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4301aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4302aa9b34e5SMatthias Ringwald                 break;
4303aa9b34e5SMatthias Ringwald             }
4304aa9b34e5SMatthias Ringwald 
4305192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4306192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4307192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4308192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4309192365feSMatthias Ringwald             }
4310192365feSMatthias Ringwald #endif
43113deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
43123deb3ec6SMatthias Ringwald             break;
43133deb3ec6SMatthias Ringwald 
43143deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
43154c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
43163deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43173deb3ec6SMatthias Ringwald                 break;;
43183deb3ec6SMatthias Ringwald             }
43193deb3ec6SMatthias Ringwald 
43203deb3ec6SMatthias Ringwald             // received random value
43219c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
43223deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
43233deb3ec6SMatthias Ringwald             break;
432442134bc6SMatthias Ringwald #endif
43253deb3ec6SMatthias Ringwald 
432642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43273deb3ec6SMatthias Ringwald         // Responder
43283deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
43293deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
43303deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
43314c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
43323deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43333deb3ec6SMatthias Ringwald                 break;;
43343deb3ec6SMatthias Ringwald             }
43353deb3ec6SMatthias Ringwald 
43363deb3ec6SMatthias Ringwald             // store pairing request
4337212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4338212d735eSMatthias Ringwald 
4339212d735eSMatthias Ringwald             // check if IRK completed
4340212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4341212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4342212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
43433deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
43443deb3ec6SMatthias Ringwald                     break;
4345212d735eSMatthias Ringwald                 default:
4346212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4347212d735eSMatthias Ringwald                     break;
4348212d735eSMatthias Ringwald             }
4349212d735eSMatthias Ringwald             break;
435042134bc6SMatthias Ringwald #endif
43513deb3ec6SMatthias Ringwald 
435227c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4353c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
43544c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
435527c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
435627c32905SMatthias Ringwald                 break;
435727c32905SMatthias Ringwald             }
4358bccf5e67SMatthias Ringwald 
4359e53be891SMatthias Ringwald             // store public key for DH Key calculation
4360fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4361fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4362bccf5e67SMatthias Ringwald 
436302658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
436402658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
436502658749SMatthias Ringwald                 log_info("Remote PK matches ours");
436602658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
436702658749SMatthias Ringwald                 break;
436802658749SMatthias Ringwald             }
436902658749SMatthias Ringwald 
4370d1a1f6a4SMatthias Ringwald             // validate public key
4371d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
43729305033eSMatthias Ringwald             if (err != 0){
437302658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4374349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4375bccf5e67SMatthias Ringwald                 break;
4376bccf5e67SMatthias Ringwald             }
4377891bb64aSMatthias Ringwald 
4378d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4379f3582630SMatthias 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);
43803cf37b8cSMatthias Ringwald 
438165a9a04eSMatthias Ringwald 
438265a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
438342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4384136d331aSMatthias Ringwald                 // responder
4385c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4386136d331aSMatthias Ringwald             } else {
4387136d331aSMatthias Ringwald                 // initiator
4388a1e31e9cSMatthias Ringwald                 // stk generation method
4389a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4390a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4391a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
439247fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4393c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4394a1e31e9cSMatthias Ringwald                         break;
4395a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
439607036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
439707036a04SMatthias Ringwald                         break;
439807036a04SMatthias Ringwald                     case PK_INIT_INPUT:
439947fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
440007036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
440107036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
440207036a04SMatthias Ringwald                             break;
440307036a04SMatthias Ringwald                         }
4404b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4405a1e31e9cSMatthias Ringwald                         break;
4406a1e31e9cSMatthias Ringwald                     case OOB:
4407d1a1f6a4SMatthias Ringwald                         // generate Nx
44084acf7b7bSMatthias Ringwald                         log_info("Generate Na");
44096ca80073SMatthias 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);
4410a1e31e9cSMatthias Ringwald                         break;
44117bbeb3adSMilanka Ringwald                     default:
44127bbeb3adSMilanka Ringwald                         btstack_assert(false);
44137bbeb3adSMilanka Ringwald                         break;
4414a1e31e9cSMatthias Ringwald                 }
4415136d331aSMatthias Ringwald             }
441627c32905SMatthias Ringwald             break;
4417e53be891SMatthias Ringwald 
4418c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
44194c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
442045a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
442145a61d50SMatthias Ringwald                 break;
442245a61d50SMatthias Ringwald             }
442345a61d50SMatthias Ringwald             // received confirm value
442445a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
442545a61d50SMatthias Ringwald 
4426192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4427192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4428192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4429192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4430192365feSMatthias Ringwald             }
4431192365feSMatthias Ringwald #endif
443242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
443345a61d50SMatthias Ringwald                 // responder
443407036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
443507036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
443607036a04SMatthias Ringwald                         // still waiting for passkey
443707036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
443807036a04SMatthias Ringwald                         break;
443907036a04SMatthias Ringwald                     }
444007036a04SMatthias Ringwald                 }
4441b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
444245a61d50SMatthias Ringwald             } else {
444345a61d50SMatthias Ringwald                 // initiator
4444945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
44456ca80073SMatthias 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);
4446f1c1783eSMatthias Ringwald                 } else {
4447c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
444845a61d50SMatthias Ringwald                 }
4449f1c1783eSMatthias Ringwald             }
445045a61d50SMatthias Ringwald             break;
445145a61d50SMatthias Ringwald 
4452c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
44534c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4454e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4455136d331aSMatthias Ringwald                 break;
4456e53be891SMatthias Ringwald             }
4457e53be891SMatthias Ringwald 
4458e53be891SMatthias Ringwald             // received random value
4459e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4460e53be891SMatthias Ringwald 
44615a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4462ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4463d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4464d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4465d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
446665a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4467d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4468688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4469ae451ec5SMatthias Ringwald                  break;
44705a293e6eSMatthias Ringwald             }
44716f52a196SMatthias Ringwald 
44724acf7b7bSMatthias Ringwald             // OOB
44734acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
44744acf7b7bSMatthias Ringwald 
44754acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
44764acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
44774acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
44784ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
44794acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
44804acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
44814acf7b7bSMatthias Ringwald                     } else {
44826535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
44834acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
44844acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
44854acf7b7bSMatthias Ringwald                     }
44864acf7b7bSMatthias Ringwald                 }  else {
44874ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
44884acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
44894acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
44904acf7b7bSMatthias Ringwald                     } else {
44916535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
44924acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
44934acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
44944acf7b7bSMatthias Ringwald                     }
44954acf7b7bSMatthias Ringwald                 }
44964acf7b7bSMatthias Ringwald 
4497a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
44984acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4499a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4500a680ba6bSMatthias Ringwald                      break;
4501a680ba6bSMatthias Ringwald                 }
45024acf7b7bSMatthias Ringwald             }
4503a680ba6bSMatthias Ringwald 
4504a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4505688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4506e53be891SMatthias Ringwald             break;
4507e53be891SMatthias Ringwald 
4508901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4509901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
45103cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4511901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4512901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4513901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4514901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4515901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4516901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4517901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4518c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4519901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4520d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
45214c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4522e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4523e53be891SMatthias Ringwald                 break;
4524e53be891SMatthias Ringwald             }
4525e53be891SMatthias Ringwald             // store DHKey Check
4526901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4527e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4528446a8c36SMatthias Ringwald 
4529901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4530901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4531019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4532bd57ffebSMatthias Ringwald             }
4533bd57ffebSMatthias Ringwald             break;
453427c32905SMatthias Ringwald #endif
453527c32905SMatthias Ringwald 
453642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
45373deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
45384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
45393deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
454027c32905SMatthias Ringwald                 break;
45413deb3ec6SMatthias Ringwald             }
45423deb3ec6SMatthias Ringwald 
45433deb3ec6SMatthias Ringwald             // received confirm value
45449c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
45453deb3ec6SMatthias Ringwald 
4546192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4547192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4548192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4549192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4550192365feSMatthias Ringwald             }
4551192365feSMatthias Ringwald #endif
45523deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
45533deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
45545611a760SMatthias 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);
45553deb3ec6SMatthias Ringwald             }
45563deb3ec6SMatthias Ringwald 
45573deb3ec6SMatthias Ringwald             // handle user cancel pairing?
45583deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4559f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
45603deb3ec6SMatthias Ringwald                 break;
45613deb3ec6SMatthias Ringwald             }
45623deb3ec6SMatthias Ringwald 
45633deb3ec6SMatthias Ringwald             // wait for user action?
45643deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
45653deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
45663deb3ec6SMatthias Ringwald                 break;
45673deb3ec6SMatthias Ringwald             }
45683deb3ec6SMatthias Ringwald 
45693deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4570f3582630SMatthias 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);
45713deb3ec6SMatthias Ringwald             break;
45723deb3ec6SMatthias Ringwald 
45733deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
45744c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
45753deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
45763deb3ec6SMatthias Ringwald                 break;;
45773deb3ec6SMatthias Ringwald             }
45783deb3ec6SMatthias Ringwald 
45793deb3ec6SMatthias Ringwald             // received random value
45809c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
45813deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
45823deb3ec6SMatthias Ringwald             break;
458342134bc6SMatthias Ringwald #endif
45843deb3ec6SMatthias Ringwald 
4585672dc582SMatthias Ringwald         case SM_PH2_W4_CONNECTION_ENCRYPTED:
45863deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
45874c1d1092SMatthias Ringwald             switch(sm_pdu_code){
45883deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
45893deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
45909c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
45913deb3ec6SMatthias Ringwald                     break;
45923deb3ec6SMatthias Ringwald 
45933deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
45943deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4595f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
45969c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
45973deb3ec6SMatthias Ringwald                     break;
45983deb3ec6SMatthias Ringwald 
45993deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
46003deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
46019c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
46023deb3ec6SMatthias Ringwald                     break;
46033deb3ec6SMatthias Ringwald 
46043deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
46053deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
46063deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4607724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
46083deb3ec6SMatthias Ringwald                     break;
46093deb3ec6SMatthias Ringwald 
46103deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
46113deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
46129c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
46133deb3ec6SMatthias Ringwald                     break;
46143deb3ec6SMatthias Ringwald                 default:
46153deb3ec6SMatthias Ringwald                     // Unexpected PDU
46163deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
46173deb3ec6SMatthias Ringwald                     break;
46183deb3ec6SMatthias Ringwald             }
46193deb3ec6SMatthias Ringwald             // done with key distribution?
462061d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
46213deb3ec6SMatthias Ringwald 
46223deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
46233deb3ec6SMatthias Ringwald 
462442134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
46256f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
46263deb3ec6SMatthias Ringwald                 } else {
4627625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4628625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4629bbf8db22SMatthias Ringwald                     } else {
4630f3582630SMatthias 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);
4631625f00b2SMatthias Ringwald                     }
46323deb3ec6SMatthias Ringwald                 }
46333deb3ec6SMatthias Ringwald             }
46343deb3ec6SMatthias Ringwald             break;
4635c18be159SMatthias Ringwald 
4636c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4637c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4638c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4639c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4640c18be159SMatthias Ringwald                 break;
4641c18be159SMatthias Ringwald             }
4642c18be159SMatthias Ringwald             // store pairing response
4643c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4644c18be159SMatthias Ringwald 
4645c18be159SMatthias Ringwald             // validate encryption key size
4646c18be159SMatthias 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));
4647c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4648c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4649c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4650c18be159SMatthias Ringwald             }
4651c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4652c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4653c18be159SMatthias Ringwald                 break;
4654c18be159SMatthias Ringwald             }
4655c18be159SMatthias Ringwald 
4656c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4657c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4658c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4659c18be159SMatthias Ringwald 
4660c18be159SMatthias Ringwald             // skip receive if there are none
466161d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4662c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4663c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4664c18be159SMatthias Ringwald             } else {
4665c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4666c18be159SMatthias Ringwald             }
4667c18be159SMatthias Ringwald             break;
4668c18be159SMatthias Ringwald 
4669c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4670c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4671c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4672c18be159SMatthias Ringwald                 break;
4673c18be159SMatthias Ringwald             }
4674c18be159SMatthias Ringwald             // store pairing request
4675c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4676c18be159SMatthias Ringwald             // validate encryption key size
4677c18be159SMatthias 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));
4678c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4679c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4680c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4681c18be159SMatthias Ringwald             }
4682c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4683c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4684c18be159SMatthias Ringwald                 break;
4685c18be159SMatthias Ringwald             }
4686c18be159SMatthias Ringwald             // trigger response
4687c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4688c18be159SMatthias Ringwald             break;
4689c18be159SMatthias Ringwald 
4690c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4691c18be159SMatthias Ringwald             switch(sm_pdu_code){
4692c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4693c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4694c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4695c18be159SMatthias Ringwald                     break;
4696c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4697c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4698c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4699c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4700c18be159SMatthias Ringwald                     break;
4701c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4702c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4703c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4704c18be159SMatthias Ringwald                     break;
4705c18be159SMatthias Ringwald                 default:
4706c18be159SMatthias Ringwald                     // Unexpected PDU
4707c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4708c18be159SMatthias Ringwald                     break;
4709c18be159SMatthias Ringwald             }
4710c18be159SMatthias Ringwald 
4711c18be159SMatthias Ringwald             // all keys received
471261d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4713c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4714c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4715c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4716c18be159SMatthias Ringwald                 } else {
4717c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4718c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4719c18be159SMatthias Ringwald                 }
4720c18be159SMatthias Ringwald             }
4721c18be159SMatthias Ringwald             break;
4722c18be159SMatthias Ringwald #endif
4723c18be159SMatthias Ringwald 
47243deb3ec6SMatthias Ringwald         default:
47253deb3ec6SMatthias Ringwald             // Unexpected PDU
47263deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
47272d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
47283deb3ec6SMatthias Ringwald             break;
47293deb3ec6SMatthias Ringwald     }
47303deb3ec6SMatthias Ringwald 
473170b44dd4SMatthias Ringwald     // try to send next pdu
473270b44dd4SMatthias Ringwald     sm_trigger_run();
47333deb3ec6SMatthias Ringwald }
47343deb3ec6SMatthias Ringwald 
47353deb3ec6SMatthias Ringwald // Security Manager Client API
4736a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
47373deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
47383deb3ec6SMatthias Ringwald }
47393deb3ec6SMatthias Ringwald 
47404acf7b7bSMatthias 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)){
4741a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4742a680ba6bSMatthias Ringwald }
4743a680ba6bSMatthias Ringwald 
4744b96d60a6SMatthias 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)){
4745b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4746b96d60a6SMatthias Ringwald }
4747b96d60a6SMatthias Ringwald 
474889a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
474989a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
475089a78d34SMatthias Ringwald }
475189a78d34SMatthias Ringwald 
475267f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
475367f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
475467f708e0SMatthias Ringwald }
475567f708e0SMatthias Ringwald 
47563deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
47573deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
47583deb3ec6SMatthias Ringwald }
47593deb3ec6SMatthias Ringwald 
47603deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
47613deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
47623deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
47633deb3ec6SMatthias Ringwald }
47643deb3ec6SMatthias Ringwald 
47653deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
476698d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
476798d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
476898d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
476998d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
477098d95509SMatthias Ringwald     }
477198d95509SMatthias Ringwald #endif
47723deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
47733deb3ec6SMatthias Ringwald }
47743deb3ec6SMatthias Ringwald 
47753deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
47763deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
47773deb3ec6SMatthias Ringwald }
47783deb3ec6SMatthias Ringwald 
477942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
47803deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
47813deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
47823deb3ec6SMatthias Ringwald }
478342134bc6SMatthias Ringwald #endif
47843deb3ec6SMatthias Ringwald 
47853deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
47866535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
47873deb3ec6SMatthias Ringwald }
47883deb3ec6SMatthias Ringwald 
47893deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
47906535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
47913deb3ec6SMatthias Ringwald }
47923deb3ec6SMatthias Ringwald 
47933deb3ec6SMatthias Ringwald // Testing support only
47943deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
47956535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4796103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4797841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
47983deb3ec6SMatthias Ringwald }
47993deb3ec6SMatthias Ringwald 
48003deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4801841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
48023deb3ec6SMatthias Ringwald }
48033deb3ec6SMatthias Ringwald 
4804d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4805d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4806d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4807d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
480834b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
480970b44dd4SMatthias Ringwald     sm_trigger_run();
4810d1a1f6a4SMatthias Ringwald }
4811674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
481234b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4813674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4814674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4815674e5b4aSMatthias Ringwald }
4816d1a1f6a4SMatthias Ringwald #endif
4817d1a1f6a4SMatthias Ringwald 
4818192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4819192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4820192365feSMatthias Ringwald     test_pairing_failure = reason;
4821192365feSMatthias Ringwald }
4822192365feSMatthias Ringwald #endif
4823192365feSMatthias Ringwald 
48247887cd92SMatthias Ringwald static void sm_state_reset(void) {
48257f775357SMatthias Ringwald #ifdef USE_CMAC_ENGINE
48267f775357SMatthias Ringwald     sm_cmac_active  = 0;
48277f775357SMatthias Ringwald #endif
48287f775357SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
48297f775357SMatthias Ringwald     rau_state = RAU_IDLE;
48307f775357SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
48317f775357SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
48327f775357SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
48337f775357SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
48347f775357SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
48357f775357SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
4836cbdd51cfSMatthias Ringwald     sm_persistent_keys_random_active = false;
48377f775357SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
483815211b85SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_IDLE;
48397f775357SMatthias Ringwald #endif
48407f775357SMatthias Ringwald }
48417f775357SMatthias Ringwald 
48423deb3ec6SMatthias Ringwald void sm_init(void){
48432d2d4d3cSMatthias Ringwald 
48442d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
48452d2d4d3cSMatthias Ringwald 
4846899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4847899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4848899e6e02SMatthias Ringwald 
48493deb3ec6SMatthias Ringwald     // defaults
48503deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
48513deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4852b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4853b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4854b4343428SMatthias Ringwald 
48553deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
48563deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
48573deb3ec6SMatthias Ringwald 
48585ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
48591979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4860caf15bf3SMatthias Ringwald 
48613deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
48623deb3ec6SMatthias Ringwald 
4863841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
48643deb3ec6SMatthias Ringwald 
48657f775357SMatthias Ringwald     // other
486684c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
486784c0c5c7SMatthias Ringwald 
4868e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4869e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4870e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4871e03e489aSMatthias Ringwald 
4872d1a1f6a4SMatthias Ringwald     //
4873d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4874d1a1f6a4SMatthias Ringwald 
487551bd74d1SMatthias Ringwald     // init le_device_db
487651bd74d1SMatthias Ringwald     le_device_db_init();
487751bd74d1SMatthias Ringwald 
4878b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4879e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4880384eabd3SMatthias Ringwald #ifdef ENABLE_CLASSIC
4881384eabd3SMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4882384eabd3SMatthias Ringwald #endif
488327c32905SMatthias Ringwald 
48847f775357SMatthias Ringwald     // state
48857f775357SMatthias Ringwald     sm_state_reset();
48862d2d4d3cSMatthias Ringwald 
48872d2d4d3cSMatthias Ringwald     sm_initialized = true;
48883deb3ec6SMatthias Ringwald }
48893deb3ec6SMatthias Ringwald 
489015537ea4SMatthias Ringwald void sm_deinit(void){
489115537ea4SMatthias Ringwald     sm_initialized = false;
489215537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
489315537ea4SMatthias Ringwald }
489415537ea4SMatthias Ringwald 
48954b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
48964b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4897caf15bf3SMatthias Ringwald }
4898caf15bf3SMatthias Ringwald 
48996c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
49001979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
49016c39055aSMatthias Ringwald }
49026c39055aSMatthias Ringwald 
4903711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4904711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
49053deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
49063deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
49073deb3ec6SMatthias Ringwald }
49083deb3ec6SMatthias Ringwald 
490977e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
491077e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
491177e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
491277e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
491377e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
491477e2e5edSMatthias Ringwald }
491577e2e5edSMatthias Ringwald #endif
491677e2e5edSMatthias Ringwald 
49176bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4918711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4919711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49203deb3ec6SMatthias Ringwald     if (!sm_conn) return;
49216bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
49226bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
49233deb3ec6SMatthias Ringwald }
49243deb3ec6SMatthias Ringwald 
49253deb3ec6SMatthias Ringwald // request pairing
4926711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4927711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49283deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49293deb3ec6SMatthias Ringwald 
49307af5dcd5SMatthias Ringwald     bool have_ltk;
49317af5dcd5SMatthias Ringwald     uint8_t ltk[16];
49323deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
493342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
493424c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
493524c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
493624c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
49377af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
49387af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
49397af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
49407af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
49417af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
49427af5dcd5SMatthias Ringwald                         if (have_ltk){
49437af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
494424c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
49457af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
49467af5dcd5SMatthias Ringwald                             break;
49477af5dcd5SMatthias Ringwald                         }
49487af5dcd5SMatthias Ringwald                         /* fall through */
49497af5dcd5SMatthias Ringwald 
49507af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
49517af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49527af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
49537af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
49547af5dcd5SMatthias Ringwald                         break;
49557af5dcd5SMatthias Ringwald                     default:
49567af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
49577af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49587af5dcd5SMatthias Ringwald                         break;
49597af5dcd5SMatthias Ringwald                 }
496024c20dc4SMatthias Ringwald                 break;
496124c20dc4SMatthias Ringwald             default:
496224c20dc4SMatthias Ringwald                 break;
496324c20dc4SMatthias Ringwald         }
49643deb3ec6SMatthias Ringwald     } else {
49653deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4966175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4967175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
49683deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
49693deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
49703dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4971f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4972f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4973f53ec649SMatthias Ringwald                         if (have_ltk){
4974c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
49755567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4976c245ca32SMatthias Ringwald                             break;
4977f53ec649SMatthias Ringwald                         }
4978cf373d3aSMatthias Ringwald                         /* fall through */
4979c245ca32SMatthias Ringwald 
498034c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
49813deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
49823deb3ec6SMatthias Ringwald                         break;
49833deb3ec6SMatthias Ringwald                     default:
4984d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
498509ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49863deb3ec6SMatthias Ringwald                         break;
49873deb3ec6SMatthias Ringwald                 }
4988175b7faaSMatthias Ringwald                 break;
4989cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4990cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4991cb6d7eb0SMatthias Ringwald                 break;
4992175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
499309ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4994175b7faaSMatthias Ringwald                 break;
4995175b7faaSMatthias Ringwald             default:
4996175b7faaSMatthias Ringwald                 break;
49973deb3ec6SMatthias Ringwald         }
49983deb3ec6SMatthias Ringwald     }
499970b44dd4SMatthias Ringwald     sm_trigger_run();
50003deb3ec6SMatthias Ringwald }
50013deb3ec6SMatthias Ringwald 
50023deb3ec6SMatthias Ringwald // called by client app on authorization request
5003711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
5004711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50053deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50063deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
5007589f5a99SMatthias 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);
50083deb3ec6SMatthias Ringwald }
50093deb3ec6SMatthias Ringwald 
5010711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
5011711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50123deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50133deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
5014589f5a99SMatthias 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);
50153deb3ec6SMatthias Ringwald }
50163deb3ec6SMatthias Ringwald 
50173deb3ec6SMatthias Ringwald // GAP Bonding API
50183deb3ec6SMatthias Ringwald 
5019711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
5020711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50213deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50223deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
50230af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
50240af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
50250af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
50260af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
50270af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
50280af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
50290af429c6SMatthias Ringwald #endif
50300af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
5031de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
5032de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
5033de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
503447fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
50350af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
5036de2fd182SMatthias Ringwald                     break;
503747fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
5038de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
5039de2fd182SMatthias Ringwald                     break;
5040de2fd182SMatthias Ringwald                 case JUST_WORKS:
5041de2fd182SMatthias Ringwald                 case OOB:
5042de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
5043de2fd182SMatthias Ringwald                     break;
50447bbeb3adSMilanka Ringwald                 default:
50457bbeb3adSMilanka Ringwald                     btstack_assert(false);
50467bbeb3adSMilanka Ringwald                     break;
5047de2fd182SMatthias Ringwald             }
50480af429c6SMatthias Ringwald             break;
50490af429c6SMatthias Ringwald         default:
50500af429c6SMatthias Ringwald             break;
50513deb3ec6SMatthias Ringwald     }
505270b44dd4SMatthias Ringwald     sm_trigger_run();
50533deb3ec6SMatthias Ringwald }
50543deb3ec6SMatthias Ringwald 
5055711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
5056711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50573deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50583deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
50593deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5060136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
5061c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
5062bbf8db22SMatthias Ringwald         } else {
5063f3582630SMatthias 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);
5064136d331aSMatthias Ringwald         }
50653deb3ec6SMatthias Ringwald     }
50660346c37cSMatthias Ringwald 
50670346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5068c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
5069dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
5070446a8c36SMatthias Ringwald     }
50710346c37cSMatthias Ringwald #endif
50720346c37cSMatthias Ringwald 
507370b44dd4SMatthias Ringwald     sm_trigger_run();
50743deb3ec6SMatthias Ringwald }
50753deb3ec6SMatthias Ringwald 
5076c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
5077c8c46d51SMatthias Ringwald     // for now, it's the same
5078c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
5079c8c46d51SMatthias Ringwald }
5080c8c46d51SMatthias Ringwald 
5081711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
5082711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50833deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50843deb3ec6SMatthias Ringwald     sm_reset_tk();
5085f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
50863deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
50873deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5088f3582630SMatthias 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);
50893deb3ec6SMatthias Ringwald     }
50901c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
50916535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
50926535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
509307036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
509407036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
509507036a04SMatthias Ringwald     }
50961c516d8fSMatthias Ringwald #endif
509770b44dd4SMatthias Ringwald     sm_trigger_run();
50983deb3ec6SMatthias Ringwald }
50993deb3ec6SMatthias Ringwald 
51003d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
51013d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51023d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51033d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5104dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
51054ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5106dd4a08fbSMatthias Ringwald     switch (action){
5107dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5108dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
51094ea43905SMatthias Ringwald             flags |= (1u << action);
5110dd4a08fbSMatthias Ringwald             break;
5111dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5112dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
51134ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5114dd4a08fbSMatthias Ringwald             break;
5115dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
51164ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5117dd4a08fbSMatthias Ringwald                 // erase actions queued
5118dd4a08fbSMatthias Ringwald                 num_actions--;
51194ea43905SMatthias Ringwald                 if (num_actions == 0u){
5120dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
51214ea43905SMatthias Ringwald                     flags &= 0x19u;
5122dd4a08fbSMatthias Ringwald                 }
5123dd4a08fbSMatthias Ringwald                 break;
5124dd4a08fbSMatthias Ringwald             }
5125dd4a08fbSMatthias Ringwald             num_actions++;
51264ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5127dd4a08fbSMatthias Ringwald             break;
5128dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
51294ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5130dd4a08fbSMatthias Ringwald                 // enter actions queued
5131dd4a08fbSMatthias Ringwald                 num_actions--;
51324ea43905SMatthias Ringwald                 if (num_actions == 0u){
5133dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
51344ea43905SMatthias Ringwald                     flags &= 0x19u;
5135dd4a08fbSMatthias Ringwald                 }
5136dd4a08fbSMatthias Ringwald                 break;
5137dd4a08fbSMatthias Ringwald             }
5138dd4a08fbSMatthias Ringwald             num_actions++;
51394ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5140dd4a08fbSMatthias Ringwald             break;
5141dd4a08fbSMatthias Ringwald         default:
5142dd4a08fbSMatthias Ringwald             break;
5143dd4a08fbSMatthias Ringwald     }
5144dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
514570b44dd4SMatthias Ringwald     sm_trigger_run();
51463d7fe1e9SMatthias Ringwald }
51473d7fe1e9SMatthias Ringwald 
5148c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5149d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5150d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5151d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
515270b44dd4SMatthias Ringwald     sm_trigger_run();
5153d1a1f6a4SMatthias Ringwald }
5154c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
51558334d3d8SMatthias Ringwald 
51568334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
51578334d3d8SMatthias Ringwald 
5158c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5159c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5160d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5161d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5162c59d0c92SMatthias Ringwald     return 0;
5163c59d0c92SMatthias Ringwald }
5164c59d0c92SMatthias Ringwald #endif
5165c59d0c92SMatthias Ringwald 
51663deb3ec6SMatthias Ringwald /**
5167ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5168ba394633SMatthias Ringwald  * @param con_handle
5169ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5170ba394633SMatthias Ringwald  */
5171ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5172ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5173ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5174ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5175ba394633SMatthias Ringwald }
5176ba394633SMatthias Ringwald 
5177ba394633SMatthias Ringwald /**
51783deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
51793deb3ec6SMatthias Ringwald  * @param handle
51806b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
51813deb3ec6SMatthias Ringwald  */
5182711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5183711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51843deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
51853deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
51863deb3ec6SMatthias Ringwald }
51873deb3ec6SMatthias Ringwald 
51888f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
518947ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
519047ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
519147ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
519247ba4de1SMatthias Ringwald             return 0;
519347ba4de1SMatthias Ringwald         default:
51948f57b085SMatthias Ringwald             return 1;
51958f57b085SMatthias Ringwald     }
519647ba4de1SMatthias Ringwald }
5197d70217a2SMatthias Ringwald 
519833373e40SMatthias Ringwald static uint8_t own_address_type(void){
5199b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5200b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5201b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5202b95a5a35SMatthias Ringwald         default:
5203b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5204b95a5a35SMatthias Ringwald     }
520533373e40SMatthias Ringwald }
52068f57b085SMatthias Ringwald 
52073deb3ec6SMatthias Ringwald // GAP LE API
52083deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
52093deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
52103deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5211b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
52128f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
52133deb3ec6SMatthias Ringwald     gap_random_address_update_start();
52143deb3ec6SMatthias Ringwald     gap_random_address_trigger();
52153deb3ec6SMatthias Ringwald }
52163deb3ec6SMatthias Ringwald 
52173deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
52183deb3ec6SMatthias Ringwald     return gap_random_adress_type;
52193deb3ec6SMatthias Ringwald }
52203deb3ec6SMatthias Ringwald 
52213deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
52223deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
52238f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
52243deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
52253deb3ec6SMatthias Ringwald     gap_random_address_update_start();
52263deb3ec6SMatthias Ringwald }
52273deb3ec6SMatthias Ringwald 
5228667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
52298f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
52306535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5231e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
52327e252622SMatthias Ringwald }
52337e252622SMatthias Ringwald 
5234d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
52353deb3ec6SMatthias Ringwald /*
52363deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
52373deb3ec6SMatthias Ringwald  * @param adv_int_min
52383deb3ec6SMatthias Ringwald  * @param adv_int_max
52393deb3ec6SMatthias Ringwald  * @param adv_type
52403deb3ec6SMatthias Ringwald  * @param direct_address_type
52413deb3ec6SMatthias Ringwald  * @param direct_address
52423deb3ec6SMatthias Ringwald  * @param channel_map
52433deb3ec6SMatthias Ringwald  * @param filter_policy
52443deb3ec6SMatthias Ringwald  *
52453deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
52463deb3ec6SMatthias Ringwald  */
52473deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
52483deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5249b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
52503deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
52513deb3ec6SMatthias Ringwald }
5252d70217a2SMatthias Ringwald #endif
5253dcd6c9b5SMatthias Ringwald 
5254dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5255dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5256dcd6c9b5SMatthias Ringwald      // wrong connection
5257dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5258dcd6c9b5SMatthias Ringwald     // already encrypted
5259dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5260dcd6c9b5SMatthias Ringwald     // irk status?
5261dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5262dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5263dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5264dcd6c9b5SMatthias Ringwald             return 0;
5265dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5266dcd6c9b5SMatthias Ringwald             break;
5267dcd6c9b5SMatthias Ringwald         default:
5268dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5269dcd6c9b5SMatthias Ringwald             return 1;
5270dcd6c9b5SMatthias Ringwald     }
5271f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5272f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5273b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5274b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5275b15d5ceaSMatthias Ringwald     } else {
5276dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5277dcd6c9b5SMatthias Ringwald     }
5278b15d5ceaSMatthias Ringwald }
52793cdbe9dbSMatthias Ringwald 
52803cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
52813cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
52823cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
52833cdbe9dbSMatthias Ringwald #else
52843cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
52853cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
52863cdbe9dbSMatthias Ringwald #endif
52873cdbe9dbSMatthias Ringwald }
5288052bbdc5SMatthias Ringwald 
5289052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5290052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5291052bbdc5SMatthias Ringwald }
52924f384501SMatthias Ringwald 
52934f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
52944f384501SMatthias Ringwald     uint16_t i;
52954f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
52964f384501SMatthias Ringwald         bd_addr_t entry_address;
52974f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
52984f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
52994f384501SMatthias Ringwald         // skip unused entries
53004f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
53014f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
53022e08b70bSMatthias Ringwald             sm_remove_le_device_db_entry(i);
53034f384501SMatthias Ringwald             break;
53044f384501SMatthias Ringwald         }
53054f384501SMatthias Ringwald     }
53064f384501SMatthias Ringwald }
5307