xref: /btstack/src/ble/sm.c (revision 5fa700b13d25e1009a4d86ad32aba40ffc4ef28d)
13deb3ec6SMatthias Ringwald /*
23deb3ec6SMatthias Ringwald  * Copyright (C) 2014 BlueKitchen GmbH
33deb3ec6SMatthias Ringwald  *
43deb3ec6SMatthias Ringwald  * Redistribution and use in source and binary forms, with or without
53deb3ec6SMatthias Ringwald  * modification, are permitted provided that the following conditions
63deb3ec6SMatthias Ringwald  * are met:
73deb3ec6SMatthias Ringwald  *
83deb3ec6SMatthias Ringwald  * 1. Redistributions of source code must retain the above copyright
93deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer.
103deb3ec6SMatthias Ringwald  * 2. Redistributions in binary form must reproduce the above copyright
113deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer in the
123deb3ec6SMatthias Ringwald  *    documentation and/or other materials provided with the distribution.
133deb3ec6SMatthias Ringwald  * 3. Neither the name of the copyright holders nor the names of
143deb3ec6SMatthias Ringwald  *    contributors may be used to endorse or promote products derived
153deb3ec6SMatthias Ringwald  *    from this software without specific prior written permission.
163deb3ec6SMatthias Ringwald  * 4. Any redistribution, use, or modification is done solely for
173deb3ec6SMatthias Ringwald  *    personal benefit and not for any commercial purpose or for
183deb3ec6SMatthias Ringwald  *    monetary gain.
193deb3ec6SMatthias Ringwald  *
203deb3ec6SMatthias Ringwald  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
213deb3ec6SMatthias Ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
223deb3ec6SMatthias Ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
232fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
242fca4dadSMilanka Ringwald  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
253deb3ec6SMatthias Ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
263deb3ec6SMatthias Ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
273deb3ec6SMatthias Ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
283deb3ec6SMatthias Ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
293deb3ec6SMatthias Ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
303deb3ec6SMatthias Ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
313deb3ec6SMatthias Ringwald  * SUCH DAMAGE.
323deb3ec6SMatthias Ringwald  *
333deb3ec6SMatthias Ringwald  * Please inquire about commercial licensing options at
343deb3ec6SMatthias Ringwald  * [email protected]
353deb3ec6SMatthias Ringwald  *
363deb3ec6SMatthias Ringwald  */
37ab2c6ae4SMatthias Ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "sm.c"
393deb3ec6SMatthias Ringwald 
403deb3ec6SMatthias Ringwald #include <string.h>
413deb3ec6SMatthias Ringwald #include <inttypes.h>
423deb3ec6SMatthias Ringwald 
433edc84c5SMatthias Ringwald #include "ble/le_device_db.h"
4459c6af15SMatthias Ringwald #include "ble/core.h"
453edc84c5SMatthias Ringwald #include "ble/sm.h"
4661f37892SMatthias Ringwald #include "bluetooth_company_id.h"
47d7f1c72eSMatthias Ringwald #include "btstack_bool.h"
48d1a1f6a4SMatthias Ringwald #include "btstack_crypto.h"
490e2df43fSMatthias Ringwald #include "btstack_debug.h"
500e2df43fSMatthias Ringwald #include "btstack_event.h"
510e2df43fSMatthias Ringwald #include "btstack_linked_list.h"
520e2df43fSMatthias Ringwald #include "btstack_memory.h"
53899e6e02SMatthias Ringwald #include "btstack_tlv.h"
54f7a05cdaSMatthias Ringwald #include "gap.h"
550e2df43fSMatthias Ringwald #include "hci.h"
5613377825SMatthias Ringwald #include "hci_dump.h"
570e2df43fSMatthias Ringwald #include "l2cap.h"
583deb3ec6SMatthias Ringwald 
591a682202SMatthias Ringwald #if !defined(ENABLE_LE_PERIPHERAL) && !defined(ENABLE_LE_CENTRAL)
601a682202SMatthias Ringwald #error "LE Security Manager used, but neither ENABLE_LE_PERIPHERAL nor ENABLE_LE_CENTRAL defined. Please add at least one to btstack_config.h."
611a682202SMatthias Ringwald #endif
621a682202SMatthias Ringwald 
637ece0eaaSMatthias Ringwald #if defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION) && (!defined(ENABLE_CLASSIC) || !defined(ENABLE_LE_SECURE_CONNECTIONS))
647ece0eaaSMatthias Ringwald #error "Cross Transport Key Derivation requires support for LE Secure Connections and BR/EDR (Classic)"
656857ad8fSMatthias Ringwald #endif
666857ad8fSMatthias Ringwald 
67d1a1f6a4SMatthias Ringwald // assert SM Public Key can be sent/received
68d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
69d1a1f6a4SMatthias Ringwald #if HCI_ACL_PAYLOAD_SIZE < 69
70d1a1f6a4SMatthias Ringwald #error "HCI_ACL_PAYLOAD_SIZE must be at least 69 bytes when using LE Secure Conection. Please increase HCI_ACL_PAYLOAD_SIZE or disable ENABLE_LE_SECURE_CONNECTIONS"
71d1a1f6a4SMatthias Ringwald #endif
72d1a1f6a4SMatthias Ringwald #endif
73d1a1f6a4SMatthias Ringwald 
7442134bc6SMatthias Ringwald #if defined(ENABLE_LE_PERIPHERAL) && defined(ENABLE_LE_CENTRAL)
7542134bc6SMatthias Ringwald #define IS_RESPONDER(role) (role)
7642134bc6SMatthias Ringwald #else
7742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7842134bc6SMatthias Ringwald // only central - never responder (avoid 'unused variable' warnings)
7942134bc6SMatthias Ringwald #define IS_RESPONDER(role) (0 && role)
8042134bc6SMatthias Ringwald #else
8142134bc6SMatthias Ringwald // only peripheral - always responder (avoid 'unused variable' warnings)
8242134bc6SMatthias Ringwald #define IS_RESPONDER(role) (1 || role)
8342134bc6SMatthias Ringwald #endif
8442134bc6SMatthias Ringwald #endif
8542134bc6SMatthias Ringwald 
867a766ebfSMatthias Ringwald #if defined(ENABLE_LE_SIGNED_WRITE) || defined(ENABLE_LE_SECURE_CONNECTIONS)
87d1a1f6a4SMatthias Ringwald #define USE_CMAC_ENGINE
887a766ebfSMatthias Ringwald #endif
897a766ebfSMatthias Ringwald 
906857ad8fSMatthias Ringwald 
91968b2eafSMatthias Ringwald #define BTSTACK_TAG32(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))
92899e6e02SMatthias Ringwald 
933deb3ec6SMatthias Ringwald //
943deb3ec6SMatthias Ringwald // SM internal types and globals
953deb3ec6SMatthias Ringwald //
963deb3ec6SMatthias Ringwald 
973deb3ec6SMatthias Ringwald typedef enum {
983deb3ec6SMatthias Ringwald     DKG_W4_WORKING,
993deb3ec6SMatthias Ringwald     DKG_CALC_IRK,
1003deb3ec6SMatthias Ringwald     DKG_CALC_DHK,
1013deb3ec6SMatthias Ringwald     DKG_READY
1023deb3ec6SMatthias Ringwald } derived_key_generation_t;
1033deb3ec6SMatthias Ringwald 
1043deb3ec6SMatthias Ringwald typedef enum {
1053deb3ec6SMatthias Ringwald     RAU_IDLE,
106fbd4e238SMatthias Ringwald     RAU_GET_RANDOM,
1073deb3ec6SMatthias Ringwald     RAU_W4_RANDOM,
1083deb3ec6SMatthias Ringwald     RAU_GET_ENC,
1093deb3ec6SMatthias Ringwald     RAU_W4_ENC,
1103deb3ec6SMatthias Ringwald } random_address_update_t;
1113deb3ec6SMatthias Ringwald 
1123deb3ec6SMatthias Ringwald typedef enum {
1133deb3ec6SMatthias Ringwald     CMAC_IDLE,
1143deb3ec6SMatthias Ringwald     CMAC_CALC_SUBKEYS,
1153deb3ec6SMatthias Ringwald     CMAC_W4_SUBKEYS,
1163deb3ec6SMatthias Ringwald     CMAC_CALC_MI,
1173deb3ec6SMatthias Ringwald     CMAC_W4_MI,
1183deb3ec6SMatthias Ringwald     CMAC_CALC_MLAST,
1193deb3ec6SMatthias Ringwald     CMAC_W4_MLAST
1203deb3ec6SMatthias Ringwald } cmac_state_t;
1213deb3ec6SMatthias Ringwald 
1223deb3ec6SMatthias Ringwald typedef enum {
1233deb3ec6SMatthias Ringwald     JUST_WORKS,
12427c32905SMatthias Ringwald     PK_RESP_INPUT,       // Initiator displays PK, responder inputs PK
12527c32905SMatthias Ringwald     PK_INIT_INPUT,       // Responder displays PK, initiator inputs PK
12647fb4255SMatthias Ringwald     PK_BOTH_INPUT,       // Only input on both, both input PK
12747fb4255SMatthias Ringwald     NUMERIC_COMPARISON,  // Only numerical compparison (yes/no) on on both sides
12847fb4255SMatthias Ringwald     OOB                  // OOB available on one (SC) or both sides (legacy)
1293deb3ec6SMatthias Ringwald } stk_generation_method_t;
1303deb3ec6SMatthias Ringwald 
1313deb3ec6SMatthias Ringwald typedef enum {
1323deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_IDLE,
1333deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PENDING,
1343deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_CONFIRM,
1353deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PASSKEY,
1363deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_DECLINE
1373deb3ec6SMatthias Ringwald } sm_user_response_t;
1383deb3ec6SMatthias Ringwald 
1393deb3ec6SMatthias Ringwald typedef enum {
1403deb3ec6SMatthias Ringwald     SM_AES128_IDLE,
1413deb3ec6SMatthias Ringwald     SM_AES128_ACTIVE
1423deb3ec6SMatthias Ringwald } sm_aes128_state_t;
1433deb3ec6SMatthias Ringwald 
1443deb3ec6SMatthias Ringwald typedef enum {
1453deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_IDLE,
1463deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_GENERAL,
1473deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FOR_CONNECTION,
1483deb3ec6SMatthias Ringwald } address_resolution_mode_t;
1493deb3ec6SMatthias Ringwald 
1503deb3ec6SMatthias Ringwald typedef enum {
151a66b030fSMatthias Ringwald     ADDRESS_RESOLUTION_SUCCEEDED,
1523deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FAILED,
1533deb3ec6SMatthias Ringwald } address_resolution_event_t;
154901c000fSMatthias Ringwald 
155901c000fSMatthias Ringwald typedef enum {
15634b6528fSMatthias Ringwald     EC_KEY_GENERATION_IDLE,
1577df18c15SMatthias Ringwald     EC_KEY_GENERATION_ACTIVE,
1587df18c15SMatthias Ringwald     EC_KEY_GENERATION_DONE,
1597df18c15SMatthias Ringwald } ec_key_generation_state_t;
1607df18c15SMatthias Ringwald 
1617df18c15SMatthias Ringwald typedef enum {
1623cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_NEEDED = 1 << 0,
1633cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1,
1643cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2,
165901c000fSMatthias Ringwald } sm_state_var_t;
166901c000fSMatthias Ringwald 
167c59d0c92SMatthias Ringwald typedef enum {
168c59d0c92SMatthias Ringwald     SM_SC_OOB_IDLE,
169d1a1f6a4SMatthias Ringwald     SM_SC_OOB_W4_RANDOM,
170c59d0c92SMatthias Ringwald     SM_SC_OOB_W2_CALC_CONFIRM,
171c59d0c92SMatthias Ringwald     SM_SC_OOB_W4_CONFIRM,
172c59d0c92SMatthias Ringwald } sm_sc_oob_state_t;
173c59d0c92SMatthias Ringwald 
1746420f61eSMatthias Ringwald typedef uint8_t sm_key24_t[3];
1756420f61eSMatthias Ringwald typedef uint8_t sm_key56_t[7];
1766420f61eSMatthias Ringwald typedef uint8_t sm_key256_t[32];
1776420f61eSMatthias Ringwald 
1783deb3ec6SMatthias Ringwald //
1793deb3ec6SMatthias Ringwald // GLOBAL DATA
1803deb3ec6SMatthias Ringwald //
1813deb3ec6SMatthias Ringwald 
1822d2d4d3cSMatthias Ringwald static bool sm_initialized;
1832d2d4d3cSMatthias Ringwald 
184841468bbSMatthias Ringwald static bool test_use_fixed_local_csrk;
185841468bbSMatthias Ringwald static bool test_use_fixed_local_irk;
1863deb3ec6SMatthias Ringwald 
187192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
188192365feSMatthias Ringwald static uint8_t test_pairing_failure;
189192365feSMatthias Ringwald #endif
190192365feSMatthias Ringwald 
1913deb3ec6SMatthias Ringwald // configuration
1923deb3ec6SMatthias Ringwald static uint8_t sm_accepted_stk_generation_methods;
1933deb3ec6SMatthias Ringwald static uint8_t sm_max_encryption_key_size;
1943deb3ec6SMatthias Ringwald static uint8_t sm_min_encryption_key_size;
1953deb3ec6SMatthias Ringwald static uint8_t sm_auth_req = 0;
1963deb3ec6SMatthias Ringwald static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1974b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
1981979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
1993deb3ec6SMatthias Ringwald 
200b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
201b6f39a74SMatthias Ringwald static uint8_t sm_slave_request_security;
202b6f39a74SMatthias Ringwald #endif
203b6f39a74SMatthias Ringwald 
204c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
205c123d999SMatthias Ringwald static bool sm_sc_only_mode;
206c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
207c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
208c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
209c59d0c92SMatthias Ringwald #endif
210c59d0c92SMatthias Ringwald 
211899e6e02SMatthias Ringwald 
2121979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
213899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
214899e6e02SMatthias Ringwald static void *                sm_tlv_context;
215899e6e02SMatthias Ringwald 
2163deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2173deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2183deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2193deb3ec6SMatthias Ringwald 
2203deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2213deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2223deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2233deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2243deb3ec6SMatthias Ringwald 
2253deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2263deb3ec6SMatthias Ringwald // ..
2273deb3ec6SMatthias Ringwald 
2283deb3ec6SMatthias Ringwald // random address update
2293deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2303deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2313deb3ec6SMatthias Ringwald 
232d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
233514d35fcSMatthias Ringwald // CMAC Calculation: General
234d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
235d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
236d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
237d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2387a766ebfSMatthias Ringwald #endif
239514d35fcSMatthias Ringwald 
240514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2417a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
242d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
243d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
244d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
245d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2467a766ebfSMatthias Ringwald #endif
247514d35fcSMatthias Ringwald 
248514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
249514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
250aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
251514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
252514d35fcSMatthias Ringwald #endif
2533deb3ec6SMatthias Ringwald 
2543deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2553deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2563deb3ec6SMatthias Ringwald static int       sm_address_resolution_ah_calculation_active;
2573deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2583deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2593deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2603deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2618f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2623deb3ec6SMatthias Ringwald 
263d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2643deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2653deb3ec6SMatthias Ringwald 
266d1a1f6a4SMatthias Ringwald // crypto
267d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
268d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
269d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
270d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2717df1ef2fSMatthias Ringwald #endif
2727df1ef2fSMatthias Ringwald 
273d1a1f6a4SMatthias Ringwald // temp storage for random data
274d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
275d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
276d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
277d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2783deb3ec6SMatthias Ringwald 
279e03e489aSMatthias Ringwald // to receive hci events
280e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
281e03e489aSMatthias Ringwald 
28289a78d34SMatthias Ringwald /* to dispatch sm event */
28389a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28489a78d34SMatthias Ringwald 
285ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
286ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
287ece00d2dSMatthias Ringwald 
28809e4d397SMatthias Ringwald // LE Secure Connections
28909e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
29009e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
291fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
29209e4d397SMatthias Ringwald #endif
293df86eb96SMatthias Ringwald 
2943deb3ec6SMatthias Ringwald //
2953deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2963deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2973deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2983deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2993deb3ec6SMatthias Ringwald //
3003deb3ec6SMatthias Ringwald 
3013deb3ec6SMatthias Ringwald // data needed for security setup
3023deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3033deb3ec6SMatthias Ringwald 
304ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3053deb3ec6SMatthias Ringwald 
3063deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3073deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
308dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3093deb3ec6SMatthias Ringwald 
3103deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3139a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
314715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3153deb3ec6SMatthias Ringwald 
3163deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3173deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3183deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
319a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
32027c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3213deb3ec6SMatthias Ringwald 
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3233deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3243deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3273deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3283deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3293deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3303deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3313deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3323deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3333deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3343deb3ec6SMatthias Ringwald 
33568437d83SMatthias Ringwald     uint8_t   sm_state_vars;
336e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
337fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
338446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
339446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
340d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
341e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
342e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
343446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
344446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3452bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
346a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3477df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
348e53be891SMatthias Ringwald #endif
34927c32905SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // Phase 3
3513deb3ec6SMatthias Ringwald 
3523deb3ec6SMatthias Ringwald     // key distribution, we generate
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3543deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3553deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3563deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3583deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3593deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3603deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3613deb3ec6SMatthias Ringwald 
3623deb3ec6SMatthias Ringwald     // key distribution, received from peer
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3643deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3653deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3663deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3683deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3693deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3703deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3713deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
372715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
373715a43d1SMatthias Ringwald     int       sm_le_device_index;
374715a43d1SMatthias Ringwald #endif
375e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
376e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
377e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
378e0a03c85SMatthias Ringwald #endif
3793deb3ec6SMatthias Ringwald } sm_setup_context_t;
3803deb3ec6SMatthias Ringwald 
3813deb3ec6SMatthias Ringwald //
3823deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3833deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3843deb3ec6SMatthias Ringwald 
3853deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3867149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3873deb3ec6SMatthias Ringwald 
3886b65794dSMilanka Ringwald // @return 1 if oob data is available
3893deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3903deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3914acf7b7bSMatthias Ringwald static int (*sm_get_sc_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_sc_peer_confirm, uint8_t * oob_sc_peer_random);
392b96d60a6SMatthias Ringwald static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk);
3933deb3ec6SMatthias Ringwald 
3943deb3ec6SMatthias Ringwald static void sm_run(void);
395711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
396711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39777e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39877e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
39977e2e5edSMatthias Ringwald #endif
4003deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
4013deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4122a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4152a526f21SMatthias Ringwald #endif
416d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
417d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
418d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
419d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
420d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4216d80b495SMatthias Ringwald static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash));
42234b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4236ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4246ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4252a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
426d1a1f6a4SMatthias Ringwald #endif
4270ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4283deb3ec6SMatthias Ringwald 
4293deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4303deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4313deb3ec6SMatthias Ringwald }
4323deb3ec6SMatthias Ringwald 
4331fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4341fbd72c5SMatthias Ringwald //     return packet[0];
4351fbd72c5SMatthias Ringwald // }
4361fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4371fbd72c5SMatthias Ringwald     return packet[1];
4381fbd72c5SMatthias Ringwald }
4391fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4401fbd72c5SMatthias Ringwald     return packet[2];
4411fbd72c5SMatthias Ringwald }
4421fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4431fbd72c5SMatthias Ringwald     return packet[3];
4441fbd72c5SMatthias Ringwald }
4451fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4461fbd72c5SMatthias Ringwald     return packet[4];
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4491fbd72c5SMatthias Ringwald     return packet[5];
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4521fbd72c5SMatthias Ringwald     return packet[6];
4531fbd72c5SMatthias Ringwald }
4541fbd72c5SMatthias Ringwald 
4551fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4561fbd72c5SMatthias Ringwald     packet[0] = code;
4571fbd72c5SMatthias Ringwald }
4581fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4591fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4601fbd72c5SMatthias Ringwald }
4611fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4621fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4631fbd72c5SMatthias Ringwald }
4641fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4651fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4661fbd72c5SMatthias Ringwald }
4671fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4681fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4691fbd72c5SMatthias Ringwald }
4701fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4711fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4721fbd72c5SMatthias Ringwald }
4731fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4741fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4751fbd72c5SMatthias Ringwald }
4761fbd72c5SMatthias Ringwald 
4776b65794dSMilanka Ringwald // @return 1 if all bytes are 0
4781979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4793deb3ec6SMatthias Ringwald     int i;
4803764b551SMatthias Ringwald     for (i=0; i < size ; i++){
48184c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4821979f09cSMatthias Ringwald             return false;
48384c0c5c7SMatthias Ringwald         }
4843deb3ec6SMatthias Ringwald     }
4851979f09cSMatthias Ringwald     return true;
4863deb3ec6SMatthias Ringwald }
4873deb3ec6SMatthias Ringwald 
4881979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4893764b551SMatthias Ringwald     return sm_is_null(random, 8);
4903764b551SMatthias Ringwald }
4913764b551SMatthias Ringwald 
4921979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4933764b551SMatthias Ringwald     return sm_is_null(key, 16);
4943764b551SMatthias Ringwald }
4953764b551SMatthias Ringwald 
49670b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49770b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49870b44dd4SMatthias Ringwald 	UNUSED(ts);
49970b44dd4SMatthias Ringwald 	sm_run();
50070b44dd4SMatthias Ringwald }
50170b44dd4SMatthias Ringwald static void sm_trigger_run(void){
5022d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
50384c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50470b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50570b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50670b44dd4SMatthias Ringwald }
50770b44dd4SMatthias Ringwald 
5083deb3ec6SMatthias Ringwald // Key utils
5093deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5103deb3ec6SMatthias Ringwald     int i;
5113deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5123deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5133deb3ec6SMatthias Ringwald     }
5143deb3ec6SMatthias Ringwald }
5153deb3ec6SMatthias Ringwald 
5163deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5173deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5183deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5193deb3ec6SMatthias Ringwald     int i;
5203deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5213deb3ec6SMatthias Ringwald         key[15-i] = 0;
5223deb3ec6SMatthias Ringwald     }
5233deb3ec6SMatthias Ringwald }
5243deb3ec6SMatthias Ringwald 
525899e6e02SMatthias Ringwald // ER / IR checks
52621045273SMatthias Ringwald static void sm_er_ir_set_default(void){
527899e6e02SMatthias Ringwald     int i;
528899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
529899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
530899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
531899e6e02SMatthias Ringwald     }
532899e6e02SMatthias Ringwald }
533899e6e02SMatthias Ringwald 
534899e6e02SMatthias Ringwald static int sm_er_is_default(void){
535899e6e02SMatthias Ringwald     int i;
536899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
537899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
538899e6e02SMatthias Ringwald     }
539899e6e02SMatthias Ringwald     return 1;
540899e6e02SMatthias Ringwald }
541899e6e02SMatthias Ringwald 
542899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
543899e6e02SMatthias Ringwald     int i;
544899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
545899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
546899e6e02SMatthias Ringwald     }
547899e6e02SMatthias Ringwald     return 1;
548899e6e02SMatthias Ringwald }
549899e6e02SMatthias Ringwald 
55073102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
55173102768SMatthias Ringwald     UNUSED(channel);
55273102768SMatthias Ringwald 
55373102768SMatthias Ringwald     // log event
55473102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55573102768SMatthias Ringwald     // dispatch to all event handlers
55673102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55773102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55873102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55973102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
56073102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
56173102768SMatthias Ringwald     }
56273102768SMatthias Ringwald }
56373102768SMatthias Ringwald 
56473102768SMatthias Ringwald static void sm_setup_event_base(uint8_t * event, int event_size, uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56573102768SMatthias Ringwald     event[0] = type;
56673102768SMatthias Ringwald     event[1] = event_size - 2;
56773102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56873102768SMatthias Ringwald     event[4] = addr_type;
56973102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
57073102768SMatthias Ringwald }
57173102768SMatthias Ringwald 
57273102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
57373102768SMatthias Ringwald     uint8_t event[11];
57473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57573102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57673102768SMatthias Ringwald }
57773102768SMatthias Ringwald 
57873102768SMatthias Ringwald static void sm_notify_client_index(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint16_t index){
57973102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58073102768SMatthias Ringwald     bd_addr_t identity_address;
58173102768SMatthias Ringwald     int identity_address_type;
58273102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58373102768SMatthias Ringwald 
58473102768SMatthias Ringwald     uint8_t event[20];
58573102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58673102768SMatthias Ringwald     event[11] = identity_address_type;
58773102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
58873102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58973102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59073102768SMatthias Ringwald }
59173102768SMatthias Ringwald 
59273102768SMatthias 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){
59373102768SMatthias Ringwald     uint8_t event[12];
59473102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59573102768SMatthias Ringwald     event[11] = status;
59673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
59773102768SMatthias Ringwald }
59873102768SMatthias Ringwald 
59973102768SMatthias Ringwald 
60073102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60173102768SMatthias Ringwald 
6023ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6033ab61f77SMatthias Ringwald 
6047b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60573102768SMatthias Ringwald 
60673102768SMatthias Ringwald     int       identity_addr_type;
60773102768SMatthias Ringwald     bd_addr_t identity_addr;
6083c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6093c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61073102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6113c0e26deSMatthias Ringwald     } else {
6123c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6133c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6143c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6153c0e26deSMatthias Ringwald     }
61673102768SMatthias Ringwald 
61773102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
61873102768SMatthias Ringwald }
61973102768SMatthias Ringwald 
62073102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62173102768SMatthias Ringwald 
62260be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62360be5b21SMatthias Ringwald 
6247b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62573102768SMatthias Ringwald 
62673102768SMatthias Ringwald     int       identity_addr_type;
62773102768SMatthias Ringwald     bd_addr_t identity_addr;
6283c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6293c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63073102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6313c0e26deSMatthias Ringwald     } else {
6323c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6333c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6343c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6353c0e26deSMatthias Ringwald     }
63673102768SMatthias Ringwald 
63773102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
63873102768SMatthias Ringwald }
63973102768SMatthias Ringwald 
640d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
641d3c12277SMatthias Ringwald 
642d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
643d3c12277SMatthias Ringwald 
644d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
645d3c12277SMatthias Ringwald 
646d3c12277SMatthias Ringwald     uint8_t event[11];
647d3c12277SMatthias 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);
648d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
649d3c12277SMatthias Ringwald }
650d3c12277SMatthias Ringwald 
6510ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
652f61072f5SMatthias Ringwald 
653d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
654d77906ffSMatthias Ringwald 
65569f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65669f82ad8SMatthias Ringwald 
6570ccf6c9cSMatthias Ringwald     uint8_t event[13];
6580ccf6c9cSMatthias 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);
6590ccf6c9cSMatthias Ringwald     event[11] = status;
6600ccf6c9cSMatthias Ringwald     event[12] = reason;
6610ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6620ccf6c9cSMatthias Ringwald }
6630ccf6c9cSMatthias Ringwald 
6643deb3ec6SMatthias Ringwald // SMP Timeout implementation
6653deb3ec6SMatthias Ringwald 
6663deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6673deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6683deb3ec6SMatthias Ringwald //
6693deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6703deb3ec6SMatthias Ringwald //
6713deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6723deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6733deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6743deb3ec6SMatthias Ringwald // established.
6753deb3ec6SMatthias Ringwald 
676ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6773deb3ec6SMatthias Ringwald     log_info("SM timeout");
678c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6793deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68068a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6810ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6823deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6833deb3ec6SMatthias Ringwald 
6843deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6853deb3ec6SMatthias Ringwald     sm_run();
6863deb3ec6SMatthias Ringwald }
6873deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
688528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68991a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
690528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
691528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
692528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6933deb3ec6SMatthias Ringwald }
6943deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
695528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6963deb3ec6SMatthias Ringwald }
6973deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6983deb3ec6SMatthias Ringwald     sm_timeout_stop();
6993deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7003deb3ec6SMatthias Ringwald }
7013deb3ec6SMatthias Ringwald 
7023deb3ec6SMatthias Ringwald // end of sm timeout
7033deb3ec6SMatthias Ringwald 
7043deb3ec6SMatthias Ringwald // GAP Random Address updates
7053deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
706ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7073deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7083deb3ec6SMatthias Ringwald 
7093deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
710899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
711d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
712fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71370b44dd4SMatthias Ringwald     sm_trigger_run();
7143deb3ec6SMatthias Ringwald }
7153deb3ec6SMatthias Ringwald 
716ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7179ec2630cSMatthias Ringwald     UNUSED(timer);
7189ec2630cSMatthias Ringwald 
7193deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
720528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
721528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7223deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7233deb3ec6SMatthias Ringwald }
7243deb3ec6SMatthias Ringwald 
7253deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
726528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
727528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
728528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7293deb3ec6SMatthias Ringwald }
7303deb3ec6SMatthias Ringwald 
7313deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
732528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7333deb3ec6SMatthias Ringwald }
7343deb3ec6SMatthias Ringwald 
7353deb3ec6SMatthias Ringwald // ah(k,r) helper
7363deb3ec6SMatthias Ringwald // r = padding || r
7373deb3ec6SMatthias Ringwald // r - 24 bit value
7384a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7393deb3ec6SMatthias Ringwald     // r'= padding || r
7403deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7416535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7423deb3ec6SMatthias Ringwald }
7433deb3ec6SMatthias Ringwald 
7443deb3ec6SMatthias Ringwald // d1 helper
7453deb3ec6SMatthias Ringwald // d' = padding || r || d
7463deb3ec6SMatthias Ringwald // d,r - 16 bit values
7474a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7483deb3ec6SMatthias Ringwald     // d'= padding || r || d
7493deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
750f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
751f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7523deb3ec6SMatthias Ringwald }
7533deb3ec6SMatthias Ringwald 
7543deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7554a6806f3SMatthias 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){
7563deb3ec6SMatthias Ringwald 
7573deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7583deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7593deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7603deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7613deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7623deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7633deb3ec6SMatthias Ringwald 
7643deb3ec6SMatthias Ringwald     sm_key_t p1;
7659c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7669c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7673deb3ec6SMatthias Ringwald     p1[14] = rat;
7683deb3ec6SMatthias Ringwald     p1[15] = iat;
7698314c363SMatthias Ringwald     log_info_key("p1", p1);
7708314c363SMatthias Ringwald     log_info_key("r", r);
7713deb3ec6SMatthias Ringwald 
7723deb3ec6SMatthias Ringwald     // t1 = r xor p1
7733deb3ec6SMatthias Ringwald     int i;
7743deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7753deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7763deb3ec6SMatthias Ringwald     }
7778314c363SMatthias Ringwald     log_info_key("t1", t1);
7783deb3ec6SMatthias Ringwald }
7793deb3ec6SMatthias Ringwald 
7803deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7814a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7823deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7833deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7843deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7853deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7863deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7873deb3ec6SMatthias Ringwald 
7883deb3ec6SMatthias Ringwald     sm_key_t p2;
7893deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7906535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7916535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7928314c363SMatthias Ringwald     log_info_key("p2", p2);
7933deb3ec6SMatthias Ringwald 
7943deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7953deb3ec6SMatthias Ringwald     int i;
7963deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7973deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7983deb3ec6SMatthias Ringwald     }
7998314c363SMatthias Ringwald     log_info_key("t3", t3);
8003deb3ec6SMatthias Ringwald }
8013deb3ec6SMatthias Ringwald 
8024a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8038314c363SMatthias Ringwald     log_info_key("r1", r1);
8048314c363SMatthias Ringwald     log_info_key("r2", r2);
8056535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8066535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8073deb3ec6SMatthias Ringwald }
8083deb3ec6SMatthias Ringwald 
809fbe050beSMatthias Ringwald 
8103deb3ec6SMatthias Ringwald // decide on stk generation based on
8113deb3ec6SMatthias Ringwald // - pairing request
8123deb3ec6SMatthias Ringwald // - io capabilities
8133deb3ec6SMatthias Ringwald // - OOB data availability
8143deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8153deb3ec6SMatthias Ringwald 
8168334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8178334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8188334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8198334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8208334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8218334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8228334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8238334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8248334d3d8SMatthias Ringwald     };
8258334d3d8SMatthias Ringwald 
8268334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8278334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8288334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8298334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8308334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8318334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8328334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8338334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8348334d3d8SMatthias Ringwald     };
8358334d3d8SMatthias Ringwald #endif
8368334d3d8SMatthias Ringwald 
8373deb3ec6SMatthias Ringwald     // default: just works
8383deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8393deb3ec6SMatthias Ringwald 
84027c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84127c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84227c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8434ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84427c32905SMatthias Ringwald #else
84527c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84627c32905SMatthias Ringwald #endif
84798d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
84827c32905SMatthias Ringwald 
84965a9a04eSMatthias Ringwald 
85065a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8511979f09cSMatthias Ringwald     bool use_oob;
85265a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85365a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85465a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8551979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85665a9a04eSMatthias Ringwald     } else {
85765a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
85865a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8591979f09cSMatthias 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;
86065a9a04eSMatthias Ringwald     }
86165a9a04eSMatthias Ringwald     if (use_oob){
86265a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86365a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86465a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86565a9a04eSMatthias Ringwald         return;
86665a9a04eSMatthias Ringwald     }
86765a9a04eSMatthias Ringwald 
86827c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86927c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87027c32905SMatthias Ringwald     // model shall be used.
8714ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8724ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87327c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87427c32905SMatthias Ringwald         return;
87527c32905SMatthias Ringwald     }
87627c32905SMatthias Ringwald 
8773deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8783deb3ec6SMatthias Ringwald     sm_reset_tk();
8793deb3ec6SMatthias Ringwald 
8803deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8818da2e96dSMatthias 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)){
8823deb3ec6SMatthias Ringwald         return;
8833deb3ec6SMatthias Ringwald     }
8843deb3ec6SMatthias Ringwald 
8853deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8863deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
88727c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
88827c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88927c32905SMatthias Ringwald 
89027c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
891c6b7cbd9SMatthias Ringwald     // table not define by default
89227c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89327c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89427c32905SMatthias Ringwald     }
89527c32905SMatthias Ringwald #endif
89627c32905SMatthias 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)];
89727c32905SMatthias Ringwald 
8983deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8991ad129beSMatthias 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);
9003deb3ec6SMatthias Ringwald }
9013deb3ec6SMatthias Ringwald 
9023deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9033deb3ec6SMatthias Ringwald     int flags = 0;
9043deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9053deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9073deb3ec6SMatthias Ringwald     }
9083deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9143deb3ec6SMatthias Ringwald     }
9153deb3ec6SMatthias Ringwald     return flags;
9163deb3ec6SMatthias Ringwald }
9173deb3ec6SMatthias Ringwald 
9189a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9193deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9209a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9219a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
922715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9239790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
924715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9259790be5fSMatthias Ringwald #endif
9263deb3ec6SMatthias Ringwald }
9273deb3ec6SMatthias Ringwald 
9283deb3ec6SMatthias Ringwald // CSRK Key Lookup
9293deb3ec6SMatthias Ringwald 
9303deb3ec6SMatthias Ringwald 
9313deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9323deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9333deb3ec6SMatthias Ringwald }
9343deb3ec6SMatthias Ringwald 
935711e6c80SMatthias 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){
9366535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9373deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9383deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9393deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9403deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
941711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9423deb3ec6SMatthias Ringwald }
9433deb3ec6SMatthias Ringwald 
9443deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9453deb3ec6SMatthias Ringwald     // check if already in list
946665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9473deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
948665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
949665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
950665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9513deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9523deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9533deb3ec6SMatthias Ringwald         // already in list
9543deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9553deb3ec6SMatthias Ringwald     }
9563deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9573deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9583deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9596535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
960665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96170b44dd4SMatthias Ringwald     sm_trigger_run();
9623deb3ec6SMatthias Ringwald     return 0;
9633deb3ec6SMatthias Ringwald }
9643deb3ec6SMatthias Ringwald 
965d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
966d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
967514d35fcSMatthias Ringwald 
968d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
969d1a1f6a4SMatthias Ringwald     UNUSED(arg);
970d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
971d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97270b44dd4SMatthias Ringwald     sm_trigger_run();
9733deb3ec6SMatthias Ringwald }
974514d35fcSMatthias Ringwald 
9754dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9764ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9773deb3ec6SMatthias Ringwald }
9786d80b495SMatthias Ringwald #endif
9793deb3ec6SMatthias Ringwald 
9806d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
981514d35fcSMatthias Ringwald // generic cmac calculation
982d1a1f6a4SMatthias 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)){
983d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
984d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
985d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9863deb3ec6SMatthias Ringwald }
9877a766ebfSMatthias Ringwald #endif
9883deb3ec6SMatthias Ringwald 
989514d35fcSMatthias Ringwald // cmac for ATT Message signing
9907a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
991d1a1f6a4SMatthias Ringwald 
992d1a1f6a4SMatthias 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)){
993d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
994d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
995d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
996d1a1f6a4SMatthias Ringwald }
997d1a1f6a4SMatthias Ringwald 
9984dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
999d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1000d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10014dfd504aSMatthias Ringwald         return 0;
10024dfd504aSMatthias Ringwald     }
10034dfd504aSMatthias Ringwald 
1004d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10054dfd504aSMatthias Ringwald 
1006d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10074dfd504aSMatthias Ringwald     if (offset < 3){
1008d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10094dfd504aSMatthias Ringwald     }
1010d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10114dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1012d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10134dfd504aSMatthias Ringwald     }
1014d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10154dfd504aSMatthias Ringwald }
10164dfd504aSMatthias Ringwald 
10174dfd504aSMatthias 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)){
1018514d35fcSMatthias Ringwald     // ATT Message Signing
1019d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1020d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1021d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1022514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1023d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1024d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1025d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10263deb3ec6SMatthias Ringwald }
10277a766ebfSMatthias Ringwald #endif
10283deb3ec6SMatthias Ringwald 
1029ea9b6796SMatthias Ringwald static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){
1030ea9b6796SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10315baa755bSMatthias Ringwald     uint8_t event[12];
1032f6a153d5SMatthias 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);
10335baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
1034f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1035ea9b6796SMatthias Ringwald }
1036ea9b6796SMatthias Ringwald 
1037ea9b6796SMatthias Ringwald static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn){
10385baa755bSMatthias Ringwald     uint8_t event[16];
1039f6a153d5SMatthias Ringwald     uint32_t passkey = big_endian_read_32(setup->sm_tk, 12);
1040f6a153d5SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle,
1041f6a153d5SMatthias Ringwald                         sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10425baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
10435baa755bSMatthias Ringwald     little_endian_store_32(event, 12, passkey);
1044f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1045ea9b6796SMatthias Ringwald }
1046ea9b6796SMatthias Ringwald 
10473deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1048446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10493deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1050d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10513deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10523deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
105342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1054ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10553deb3ec6SMatthias Ringwald             } else {
1056ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10573deb3ec6SMatthias Ringwald             }
10583deb3ec6SMatthias Ringwald             break;
10593deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
106042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1061ea9b6796SMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn);
10623deb3ec6SMatthias Ringwald             } else {
1063ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10643deb3ec6SMatthias Ringwald             }
10653deb3ec6SMatthias Ringwald             break;
106647fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
1067ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10683deb3ec6SMatthias Ringwald             break;
106947fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1070ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST);
107127c32905SMatthias Ringwald             break;
10723deb3ec6SMatthias Ringwald         case JUST_WORKS:
1073ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST);
10743deb3ec6SMatthias Ringwald             break;
10753deb3ec6SMatthias Ringwald         case OOB:
10763deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10773deb3ec6SMatthias Ringwald             break;
10787bbeb3adSMilanka Ringwald         default:
10797bbeb3adSMilanka Ringwald             btstack_assert(false);
10807bbeb3adSMilanka Ringwald             break;
10813deb3ec6SMatthias Ringwald     }
10823deb3ec6SMatthias Ringwald }
10833deb3ec6SMatthias Ringwald 
108461d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
1085*5fa700b1SMatthias 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);
1086b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10873deb3ec6SMatthias Ringwald }
10883deb3ec6SMatthias Ringwald 
1089711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10907149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10913deb3ec6SMatthias Ringwald         sm_timeout_stop();
10927149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1093711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1094c085d9ffSMatthias Ringwald 
1095c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1096c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1097c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1098c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1099c085d9ffSMatthias Ringwald         }
1100c085d9ffSMatthias Ringwald #endif
11013deb3ec6SMatthias Ringwald     }
11023deb3ec6SMatthias Ringwald }
11033deb3ec6SMatthias Ringwald 
11047d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
11051dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
11060ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
11071dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
11081dca9d8aSMatthias Ringwald }
11091dca9d8aSMatthias Ringwald 
11103deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1111bb09604fSMatthias Ringwald 
1112bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11133deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1114bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11153deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1116bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1117bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1118bb09604fSMatthias Ringwald #endif
11197ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11207ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11217ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11227ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11237ece0eaaSMatthias Ringwald         }
11247ece0eaaSMatthias Ringwald #endif
11253deb3ec6SMatthias Ringwald     }
11263deb3ec6SMatthias Ringwald     return flags;
11273deb3ec6SMatthias Ringwald }
11283deb3ec6SMatthias Ringwald 
1129d7471931SMatthias Ringwald static void sm_reset_setup(void){
11303deb3ec6SMatthias Ringwald     // fill in sm setup
1131901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1132dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1133d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11343deb3ec6SMatthias Ringwald     sm_reset_tk();
1135d7471931SMatthias Ringwald }
1136d7471931SMatthias Ringwald 
1137d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1138d7471931SMatthias Ringwald     // fill in sm setup
11393deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11406535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11413deb3ec6SMatthias Ringwald 
1142a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11439305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1144a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11453deb3ec6SMatthias Ringwald     }
11463deb3ec6SMatthias Ringwald 
1147a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1148a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11494acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11504acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1151a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11529305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11534acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1154a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1155a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1156a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1157a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11584acf7b7bSMatthias Ringwald                     setup->sm_ra);
11594acf7b7bSMatthias Ringwald             } else {
11604acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11614acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11624acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11634acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11644acf7b7bSMatthias Ringwald                     setup->sm_rb);
11654acf7b7bSMatthias Ringwald             }
1166a680ba6bSMatthias Ringwald         } else {
1167a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1168a680ba6bSMatthias Ringwald         }
1169a680ba6bSMatthias Ringwald     }
1170a680ba6bSMatthias Ringwald #endif
1171a680ba6bSMatthias Ringwald 
11723deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
117342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11743deb3ec6SMatthias Ringwald         // slave
11753deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11763deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1177d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11786535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1179d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11803deb3ec6SMatthias Ringwald     } else {
11813deb3ec6SMatthias Ringwald         // master
11823deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11833deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1184d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11856535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1186d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11873deb3ec6SMatthias Ringwald 
1188d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11891ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11901ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11913deb3ec6SMatthias Ringwald     }
11923deb3ec6SMatthias Ringwald 
119357132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1194d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11952c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11962c041b42SMatthias Ringwald     // enable SC for SC only mode
11972c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11982c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1199d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
12002c041b42SMatthias Ringwald     }
12012c041b42SMatthias Ringwald #endif
120257132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
120357132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
120457132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
120557132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
120657132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
120757132f12SMatthias Ringwald 	}
120857132f12SMatthias Ringwald #endif
12091ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1210a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1211df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1212d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12133deb3ec6SMatthias Ringwald }
12143deb3ec6SMatthias Ringwald 
12153deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12163deb3ec6SMatthias Ringwald 
12173deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12189a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12199a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
122042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
122152f9cf63SMatthias Ringwald         // slave / responder
12223deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12239a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12249a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12253deb3ec6SMatthias Ringwald     } else {
12263deb3ec6SMatthias Ringwald         // master / initiator
12273deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12289a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12299a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12303deb3ec6SMatthias Ringwald     }
12313deb3ec6SMatthias Ringwald 
12323deb3ec6SMatthias Ringwald     // check key size
12332c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12342c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12352c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12362c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12372c041b42SMatthias Ringwald     }
12382c041b42SMatthias Ringwald #endif
12391ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12404ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12413deb3ec6SMatthias Ringwald 
1242eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12433deb3ec6SMatthias Ringwald     sm_setup_tk();
12443deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12453deb3ec6SMatthias Ringwald 
12463deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12473deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12483deb3ec6SMatthias Ringwald 
1249eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12502c041b42SMatthias Ringwald     // Check LE SC Only mode
12513cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12523cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12533cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12543cdbe9dbSMatthias Ringwald     }
12553cdbe9dbSMatthias Ringwald 
12569a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1257eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12589a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12599a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1260eddc894fSMatthias Ringwald     }
1261eddc894fSMatthias Ringwald #endif
1262eddc894fSMatthias Ringwald 
126352f9cf63SMatthias Ringwald     // identical to responder
12649a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
126552f9cf63SMatthias Ringwald 
12663deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1267c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12683deb3ec6SMatthias Ringwald 
12693deb3ec6SMatthias Ringwald     return 0;
12703deb3ec6SMatthias Ringwald }
12713deb3ec6SMatthias Ringwald 
12723deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12733deb3ec6SMatthias Ringwald 
12743deb3ec6SMatthias Ringwald     // cache and reset context
12753deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12763deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12773deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12783deb3ec6SMatthias Ringwald 
12793deb3ec6SMatthias Ringwald     // reset context
12803deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12813deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12823deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1283711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12843deb3ec6SMatthias Ringwald 
12853deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1286d2e90122SMatthias Ringwald     sm_key_t ltk;
12871979f09cSMatthias Ringwald     bool have_ltk;
12886c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12891979f09cSMatthias Ringwald     bool trigger_pairing;
129042134bc6SMatthias Ringwald #endif
12913deb3ec6SMatthias Ringwald     switch (mode){
12923deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12933deb3ec6SMatthias Ringwald             break;
12943deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12953deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1296711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12976c44b759SMatthias Ringwald 
12986c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12996c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
13006c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
13016c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
13026c44b759SMatthias Ringwald 
13033deb3ec6SMatthias Ringwald             switch (event){
1304a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
13053deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
13063deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1307a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
13086c44b759SMatthias Ringwald 
13096c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13106c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13116c44b759SMatthias Ringwald 
13126c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13136c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1314212d735eSMatthias Ringwald                         // IRK required before, continue
13156c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13166c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13176c39055aSMatthias Ringwald                             break;
13186c39055aSMatthias Ringwald                         }
1319212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1320212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1321212d735eSMatthias Ringwald                             break;
1322212d735eSMatthias Ringwald                         }
13237af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13247af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13256c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13267af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13277af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13286c44b759SMatthias Ringwald #endif
13297af5dcd5SMatthias Ringwald 
13307af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13311979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13327af5dcd5SMatthias Ringwald 
13337af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13347af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13357af5dcd5SMatthias Ringwald                             if (have_ltk){
13367af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13377af5dcd5SMatthias Ringwald                             } else {
13387af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13397af5dcd5SMatthias Ringwald                             }
13407af5dcd5SMatthias Ringwald                             sm_trigger_run();
13416c44b759SMatthias Ringwald                         }
13426c44b759SMatthias Ringwald #endif
13436c44b759SMatthias Ringwald                     } else {
13446c44b759SMatthias Ringwald 
134542134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13466c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13476c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13486c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13491979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13503deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
135109ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
135232bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1353c245ca32SMatthias Ringwald 
1354d4af1595SMatthias Ringwald                         if (have_ltk){
13556a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1356b187cc61SMatthias Ringwald                             trigger_reencryption = true;
135732bc5d65SMatthias Ringwald #else
135832bc5d65SMatthias Ringwald                             if (trigger_pairing){
135932bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
136032bc5d65SMatthias Ringwald                             } else {
136132bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
136232bc5d65SMatthias Ringwald                             }
136332bc5d65SMatthias Ringwald #endif
136432bc5d65SMatthias Ringwald                         }
136532bc5d65SMatthias Ringwald 
136632bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13676c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13685567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1369d4af1595SMatthias Ringwald                             break;
1370d4af1595SMatthias Ringwald                         }
13716c44b759SMatthias Ringwald 
13726c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13736c44b759SMatthias Ringwald                         if (trigger_pairing){
13743deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1375d4af1595SMatthias Ringwald                             break;
13763deb3ec6SMatthias Ringwald                         }
137742134bc6SMatthias Ringwald #endif
1378298ab52bSMatthias Ringwald                     }
13793deb3ec6SMatthias Ringwald                     break;
13803deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13813deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13826c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13837af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13846c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13856c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13866c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13876c39055aSMatthias Ringwald                         }
13887af5dcd5SMatthias Ringwald                         // send security request if requested
13897af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13907af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13917af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13927af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13937af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13947af5dcd5SMatthias Ringwald                         }
13956c39055aSMatthias Ringwald                         break;
13967af5dcd5SMatthias Ringwald #endif
13976c39055aSMatthias Ringwald                     }
139842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139909ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
14003deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
140109ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
14023deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
140342134bc6SMatthias Ringwald #endif
14043deb3ec6SMatthias Ringwald                     break;
14057bbeb3adSMilanka Ringwald 
14067bbeb3adSMilanka Ringwald                 default:
14077bbeb3adSMilanka Ringwald                     btstack_assert(false);
14087bbeb3adSMilanka Ringwald                     break;
14093deb3ec6SMatthias Ringwald             }
14103deb3ec6SMatthias Ringwald             break;
14113deb3ec6SMatthias Ringwald         default:
14123deb3ec6SMatthias Ringwald             break;
14133deb3ec6SMatthias Ringwald     }
14143deb3ec6SMatthias Ringwald 
14153deb3ec6SMatthias Ringwald     switch (event){
1416a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1417711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14183deb3ec6SMatthias Ringwald             break;
14193deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1420711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14213deb3ec6SMatthias Ringwald             break;
14227bbeb3adSMilanka Ringwald         default:
14237bbeb3adSMilanka Ringwald             btstack_assert(false);
14247bbeb3adSMilanka Ringwald             break;
14253deb3ec6SMatthias Ringwald     }
14263deb3ec6SMatthias Ringwald }
14273deb3ec6SMatthias Ringwald 
142855f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14293deb3ec6SMatthias Ringwald     int le_db_index = -1;
14303deb3ec6SMatthias Ringwald 
14313deb3ec6SMatthias Ringwald     // lookup device based on IRK
14323deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14333deb3ec6SMatthias Ringwald         int i;
1434092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14353deb3ec6SMatthias Ringwald             sm_key_t irk;
14363deb3ec6SMatthias Ringwald             bd_addr_t address;
1437c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14383deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1439adf5eaa9SMatthias Ringwald             // skip unused entries
1440c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
144111d10bdaSMatthias Ringwald             // compare Identity Address
144211d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
144311d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1444c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1445c7e2c1a5SMatthias Ringwald 
14463deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14473deb3ec6SMatthias Ringwald             le_db_index = i;
14483deb3ec6SMatthias Ringwald             break;
14493deb3ec6SMatthias Ringwald         }
1450c7e2c1a5SMatthias Ringwald     } else {
1451c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1452c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14533deb3ec6SMatthias Ringwald     }
14543deb3ec6SMatthias Ringwald 
14553deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14563deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1457c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14583deb3ec6SMatthias Ringwald         int i;
1459092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14603deb3ec6SMatthias Ringwald             bd_addr_t address;
1461adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14623deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1463adf5eaa9SMatthias Ringwald             // skip unused entries
1464adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14653deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14665df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14673deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14683deb3ec6SMatthias Ringwald                 le_db_index = i;
14693deb3ec6SMatthias Ringwald                 break;
14703deb3ec6SMatthias Ringwald             }
14713deb3ec6SMatthias Ringwald         }
14723deb3ec6SMatthias Ringwald     }
14733deb3ec6SMatthias Ringwald 
14743deb3ec6SMatthias Ringwald     // if not found, add to db
147502b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14763deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14773deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
147802b02cffSMatthias Ringwald         new_to_le_device_db = true;
14793deb3ec6SMatthias Ringwald     }
14803deb3ec6SMatthias Ringwald 
14813deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14823deb3ec6SMatthias Ringwald 
148302b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
148402b02cffSMatthias Ringwald         if (!new_to_le_device_db){
148502b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
148602b02cffSMatthias Ringwald         }
148702b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
148802b02cffSMatthias Ringwald #else
148902b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
149002b02cffSMatthias Ringwald #endif
149102b02cffSMatthias Ringwald 
149248163929SMatthias Ringwald         sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index);
1493e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14947710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
149548163929SMatthias Ringwald 
1496eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14973deb3ec6SMatthias Ringwald         // store local CSRK
1498715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1499715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15003deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
15013deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
15023deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
15033deb3ec6SMatthias Ringwald         }
15043deb3ec6SMatthias Ringwald 
15053deb3ec6SMatthias Ringwald         // store remote CSRK
15063deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
15073deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
15083deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15093deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15103deb3ec6SMatthias Ringwald         }
1511eda85fbfSMatthias Ringwald #endif
151278f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
151378f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1514e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
151578f44163SMatthias Ringwald             uint8_t zero_rand[8];
151678f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
151778f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15183dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151978f44163SMatthias Ringwald         }
152078f44163SMatthias Ringwald 
1521e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
152278f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
152378f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1524e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15253deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15263dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
152778f44163SMatthias Ringwald 
15283deb3ec6SMatthias Ringwald         }
15293deb3ec6SMatthias Ringwald     }
153055f09f49SMatthias Ringwald }
153155f09f49SMatthias Ringwald 
153255f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
153355f09f49SMatthias Ringwald 
153455f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
153555f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
153655f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
153755f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
153855f09f49SMatthias Ringwald 
153955f09f49SMatthias Ringwald     if (bonding_enabled){
154055f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
154127ef8bc8SMatthias Ringwald     } else {
154227ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
154327ef8bc8SMatthias Ringwald     }
15443deb3ec6SMatthias Ringwald }
15453deb3ec6SMatthias Ringwald 
1546688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1547f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1548688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1549688a08f9SMatthias Ringwald }
1550688a08f9SMatthias Ringwald 
1551688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1552688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1553688a08f9SMatthias Ringwald }
1554688a08f9SMatthias Ringwald 
15559af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1556688a08f9SMatthias Ringwald 
1557dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1558945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1559f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1560dc300847SMatthias Ringwald 
1561b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1562b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15631f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1564b90c4e75SMatthias Ringwald     } else {
1565b90c4e75SMatthias 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);
1566b35a3de2SMatthias Ringwald     }
1567b35a3de2SMatthias Ringwald }
1568b35a3de2SMatthias Ringwald 
1569688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
157042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1571688a08f9SMatthias Ringwald         // Responder
15724acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15734acf7b7bSMatthias Ringwald             // generate Nb
15744acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15756ca80073SMatthias 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);
15764acf7b7bSMatthias Ringwald         } else {
1577688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15784acf7b7bSMatthias Ringwald         }
1579688a08f9SMatthias Ringwald     } else {
1580688a08f9SMatthias Ringwald         // Initiator role
1581688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1582688a08f9SMatthias Ringwald             case JUST_WORKS:
1583dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1584688a08f9SMatthias Ringwald                 break;
1585688a08f9SMatthias Ringwald 
158647fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1587bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1588688a08f9SMatthias Ringwald                 break;
1589688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1590688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
159147fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15924ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1593b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1594688a08f9SMatthias Ringwald                 } else {
1595dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1596688a08f9SMatthias Ringwald                 }
1597688a08f9SMatthias Ringwald                 break;
1598688a08f9SMatthias Ringwald             case OOB:
159965a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1600688a08f9SMatthias Ringwald                 break;
16017bbeb3adSMilanka Ringwald             default:
16027bbeb3adSMilanka Ringwald                 btstack_assert(false);
16037bbeb3adSMilanka Ringwald                 break;
1604688a08f9SMatthias Ringwald         }
1605688a08f9SMatthias Ringwald     }
1606688a08f9SMatthias Ringwald }
1607688a08f9SMatthias Ringwald 
1608aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1609688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1610688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1611688a08f9SMatthias Ringwald 
1612c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1613c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1614a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1615c59d0c92SMatthias Ringwald         return;
1616c59d0c92SMatthias Ringwald     }
1617c59d0c92SMatthias Ringwald 
1618bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1619bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16206857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16212bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1622b4f65634SMatthias Ringwald #endif
1623bd57ffebSMatthias Ringwald 
1624bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1625aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16266535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1627bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1628aec94140SMatthias Ringwald             break;
1629688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1630688a08f9SMatthias Ringwald             // check
1631688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1632bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1633688a08f9SMatthias Ringwald                 break;
1634688a08f9SMatthias Ringwald             }
1635bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1636688a08f9SMatthias Ringwald             break;
1637901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1638901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1639901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1640901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1641901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1642019005a0SMatthias Ringwald             break;
1643019005a0SMatthias Ringwald         }
16440346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16456535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1646bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16470346c37cSMatthias Ringwald             break;
16480346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16496535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1650bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16510346c37cSMatthias Ringwald             break;
16520346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1653b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1654b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1655b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1656b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16576535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16586535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1659893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1660bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1661019005a0SMatthias Ringwald             break;
1662901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16636535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
166442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1665901c000fSMatthias Ringwald                 // responder
1666901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1667901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1668901c000fSMatthias Ringwald                 } else {
1669901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1670901c000fSMatthias Ringwald                 }
1671901c000fSMatthias Ringwald             } else {
1672901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1673901c000fSMatthias Ringwald             }
1674901c000fSMatthias Ringwald             break;
1675901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1676901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1677901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1678aec94140SMatthias Ringwald                 break;
1679aec94140SMatthias Ringwald             }
168042134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1681901c000fSMatthias Ringwald                 // responder
1682901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1683901c000fSMatthias Ringwald             } else {
1684901c000fSMatthias Ringwald                 // initiator
1685901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1686bd57ffebSMatthias Ringwald             }
1687901c000fSMatthias Ringwald             break;
16886857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
168957132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16906535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
169157132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16922bacf595SMatthias Ringwald             break;
169357132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16942bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16952bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16962bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16978974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
169855160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16998974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
17002bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
17012bacf595SMatthias Ringwald             } else {
17022bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
17032bacf595SMatthias Ringwald             }
17040ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17052bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17062bacf595SMatthias Ringwald             break;
1707e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1708e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1709e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1710e0a03c85SMatthias Ringwald             break;
1711e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1712e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1713e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1714e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1715e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1716e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1717e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1718c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1719e0a03c85SMatthias Ringwald             break;
1720bdb14b0eSMatthias Ringwald #endif
1721bd57ffebSMatthias Ringwald         default:
1722bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1723bd57ffebSMatthias Ringwald             break;
1724bd57ffebSMatthias Ringwald     }
172570b44dd4SMatthias Ringwald     sm_trigger_run();
1726aec94140SMatthias Ringwald }
1727aec94140SMatthias Ringwald 
1728688a08f9SMatthias 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){
1729dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1730aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17316535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17326535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1733aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1734aec94140SMatthias Ringwald     log_info("f4 key");
1735aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1736aec94140SMatthias Ringwald     log_info("f4 message");
1737dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1738d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1739aec94140SMatthias Ringwald }
1740aec94140SMatthias Ringwald 
17410346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17420346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17430346c37cSMatthias Ringwald 
17440346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17458334d3d8SMatthias Ringwald 
17468334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17478334d3d8SMatthias Ringwald 
174840c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17490346c37cSMatthias Ringwald     // calculate salt for f5
17500346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17510346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1753d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17540346c37cSMatthias Ringwald }
17550346c37cSMatthias Ringwald 
17560346c37cSMatthias 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){
17570346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17580346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17590346c37cSMatthias Ringwald 
17600346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17610346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17626535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17636535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17646535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17656535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17666535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17676535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17680346c37cSMatthias Ringwald     log_info("f5 key");
17690346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17700346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17710346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1772d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17730346c37cSMatthias Ringwald }
17740346c37cSMatthias Ringwald 
17750346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17760346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17770346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17780346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17796535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17806535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
178142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17820346c37cSMatthias Ringwald         // responder
17830346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17840346c37cSMatthias Ringwald     } else {
17850346c37cSMatthias Ringwald         // initiator
17860346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17870346c37cSMatthias Ringwald     }
17880346c37cSMatthias Ringwald }
17890346c37cSMatthias Ringwald 
17900346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17910346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17920346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17930346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17940346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17950346c37cSMatthias Ringwald     // 1..52 setup before
17960346c37cSMatthias Ringwald     log_info("f5 key");
17970346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17980346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17990346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1800d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18010346c37cSMatthias Ringwald }
1802f92edc8eSMatthias Ringwald 
18030346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
18040346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
18050346c37cSMatthias Ringwald }
18060346c37cSMatthias Ringwald 
180731f061fbSMatthias 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){
18086535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18096535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18106535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18116535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18126535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18136535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
181431f061fbSMatthias Ringwald }
181531f061fbSMatthias Ringwald 
181631f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
181731f061fbSMatthias Ringwald     const uint16_t message_len = 65;
181831f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1819dc300847SMatthias Ringwald     log_info("f6 key");
1820dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1821dc300847SMatthias Ringwald     log_info("f6 message");
1822dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1823d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1824dc300847SMatthias Ringwald }
1825dc300847SMatthias Ringwald 
1826f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1827f92edc8eSMatthias Ringwald // - U is 256 bits
1828f92edc8eSMatthias Ringwald // - V is 256 bits
1829f92edc8eSMatthias Ringwald // - X is 128 bits
1830f92edc8eSMatthias Ringwald // - Y is 128 bits
1831bd57ffebSMatthias 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){
1832bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1833bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18346535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18356535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18366535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1837f92edc8eSMatthias Ringwald     log_info("g2 key");
1838f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1839f92edc8eSMatthias Ringwald     log_info("g2 message");
18402bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1841d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1842f92edc8eSMatthias Ringwald }
1843f92edc8eSMatthias Ringwald 
1844b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1845f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
184642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1847f92edc8eSMatthias Ringwald         // responder
1848fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1849f92edc8eSMatthias Ringwald     } else {
1850f92edc8eSMatthias Ringwald         // initiator
1851fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1852f92edc8eSMatthias Ringwald     }
1853f92edc8eSMatthias Ringwald }
1854f92edc8eSMatthias Ringwald 
1855945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18569af0f475SMatthias Ringwald     uint8_t z = 0;
185740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18589af0f475SMatthias Ringwald         // some form of passkey
18599af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18604ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18619af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18629af0f475SMatthias Ringwald     }
1863fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18649af0f475SMatthias Ringwald }
1865688a08f9SMatthias Ringwald 
1866688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1867a680ba6bSMatthias Ringwald     // OOB
1868a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18694acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18704acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18714acf7b7bSMatthias Ringwald         } else {
18724acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18734acf7b7bSMatthias Ringwald         }
1874a680ba6bSMatthias Ringwald         return;
1875a680ba6bSMatthias Ringwald     }
1876a680ba6bSMatthias Ringwald 
1877688a08f9SMatthias Ringwald     uint8_t z = 0;
187840c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1879688a08f9SMatthias Ringwald         // some form of passkey
1880688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1881688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18824ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1883688a08f9SMatthias Ringwald     }
1884fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1885688a08f9SMatthias Ringwald }
1886688a08f9SMatthias Ringwald 
18870346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1888505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18893cf37b8cSMatthias Ringwald 
18903cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18913cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18923cf37b8cSMatthias Ringwald         return;
18933cf37b8cSMatthias Ringwald     } else {
18943cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18953cf37b8cSMatthias Ringwald     }
1896d1a1f6a4SMatthias Ringwald }
18973cf37b8cSMatthias Ringwald 
1898d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1899f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1900f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1901f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1902f3582630SMatthias Ringwald 
1903d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1904d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1905d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1906d1a1f6a4SMatthias Ringwald     // trigger next step
1907d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1908d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1909d1a1f6a4SMatthias Ringwald     }
191070b44dd4SMatthias Ringwald     sm_trigger_run();
1911dc300847SMatthias Ringwald }
1912dc300847SMatthias Ringwald 
1913dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1914dc300847SMatthias Ringwald     // calculate DHKCheck
1915dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1916dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1917dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19186535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19196535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1920dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1921dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1922dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1923dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1924dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1925dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1926dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1927dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
192842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1929dc300847SMatthias Ringwald         // responder
193031f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
193131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1932dc300847SMatthias Ringwald     } else {
1933dc300847SMatthias Ringwald         // initiator
193431f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
193531f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1936dc300847SMatthias Ringwald     }
1937dc300847SMatthias Ringwald }
1938dc300847SMatthias Ringwald 
1939019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1940019005a0SMatthias Ringwald     // validate E = f6()
1941019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1942019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1943019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19446535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19456535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1946019005a0SMatthias Ringwald 
1947019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1948019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1949019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1950019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1951019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1952019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1953019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1954019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
195542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1956019005a0SMatthias Ringwald         // responder
195731f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
195831f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1959019005a0SMatthias Ringwald     } else {
1960019005a0SMatthias Ringwald         // initiator
196131f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
196231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1963019005a0SMatthias Ringwald     }
1964019005a0SMatthias Ringwald }
19652bacf595SMatthias Ringwald 
196655c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19672bacf595SMatthias Ringwald 
19682bacf595SMatthias Ringwald //
19692bacf595SMatthias Ringwald // Link Key Conversion Function h6
19702bacf595SMatthias Ringwald //
197157132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19722bacf595SMatthias Ringwald // - W is 128 bits
19732bacf595SMatthias Ringwald // - keyID is 32 bits
19742bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19752bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19762bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19772bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19782bacf595SMatthias Ringwald     log_info("h6 key");
19792bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19802bacf595SMatthias Ringwald     log_info("h6 message");
19812bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1982d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19832bacf595SMatthias Ringwald }
198457132f12SMatthias Ringwald //
198557132f12SMatthias Ringwald // Link Key Conversion Function h7
198657132f12SMatthias Ringwald //
198757132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
198857132f12SMatthias Ringwald // - SALT is 128 bits
198957132f12SMatthias Ringwald // - W    is 128 bits
199057132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
199157132f12SMatthias Ringwald 	const uint16_t message_len = 16;
199257132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
199357132f12SMatthias Ringwald 	log_info("h7 key");
199457132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
199557132f12SMatthias Ringwald 	log_info("h7 message");
199657132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
199757132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
199857132f12SMatthias Ringwald }
19992bacf595SMatthias Ringwald 
2000b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
2001b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
2002b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
2003b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
200457132f12SMatthias Ringwald 
2005c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
2006b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
20072bacf595SMatthias Ringwald }
20082bacf595SMatthias Ringwald 
2009e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2010e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2011e0a03c85SMatthias Ringwald }
2012e0a03c85SMatthias Ringwald 
20132bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20142bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20152bacf595SMatthias Ringwald }
20162bacf595SMatthias Ringwald 
2017e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2018e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2019e0a03c85SMatthias Ringwald }
2020e0a03c85SMatthias Ringwald 
2021c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
202257132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
202357132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
202457132f12SMatthias Ringwald }
2025e0a03c85SMatthias Ringwald 
2026e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2027e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2028e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2029e0a03c85SMatthias Ringwald }
2030e0a03c85SMatthias Ringwald 
2031c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2032e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2033e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2034e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2035e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2036e0a03c85SMatthias Ringwald }
2037e0a03c85SMatthias Ringwald 
2038c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2039c18be159SMatthias 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;
2040c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2041c18be159SMatthias Ringwald }
2042c18be159SMatthias Ringwald 
20439af0f475SMatthias Ringwald #endif
20449af0f475SMatthias Ringwald 
204555c62cf5SMatthias Ringwald #endif
204655c62cf5SMatthias Ringwald 
2047613da3deSMatthias Ringwald // key management legacy connections:
2048613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2049613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2050613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2051613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2052613da3deSMatthias Ringwald 
2053613da3deSMatthias Ringwald // key management secure connections:
2054613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2055613da3deSMatthias Ringwald 
205642134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20575829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20585829ebe2SMatthias Ringwald     int encryption_key_size;
20595829ebe2SMatthias Ringwald     int authenticated;
20605829ebe2SMatthias Ringwald     int authorized;
20613dc3a67dSMatthias Ringwald     int secure_connection;
20625829ebe2SMatthias Ringwald 
20635829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20645829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20653dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20663dc3a67dSMatthias 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);
20675829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20685829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20695829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20703dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20715829ebe2SMatthias Ringwald }
207242134bc6SMatthias Ringwald #endif
2073bd57ffebSMatthias Ringwald 
207442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
207559066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20766535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
207759066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
207859066796SMatthias Ringwald     // re-establish used key encryption size
207959066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20804ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
208159066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20824ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20833dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20843dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
208559066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
208659066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
208759066796SMatthias Ringwald }
208842134bc6SMatthias Ringwald #endif
208959066796SMatthias Ringwald 
20903deb3ec6SMatthias Ringwald // distributed key generation
2091d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20923deb3ec6SMatthias Ringwald     switch (dkg_state){
20933deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20943deb3ec6SMatthias Ringwald             // already busy?
20953deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2096d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20973deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2098d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2099d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2100d1a1f6a4SMatthias 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);
2101d7f1c72eSMatthias Ringwald                 return true;
21023deb3ec6SMatthias Ringwald             }
21033deb3ec6SMatthias Ringwald             break;
21043deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
21053deb3ec6SMatthias Ringwald             // already busy?
21063deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2107d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
21083deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2109d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2110d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2111d1a1f6a4SMatthias 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);
2112d7f1c72eSMatthias Ringwald                 return true;
21133deb3ec6SMatthias Ringwald             }
21143deb3ec6SMatthias Ringwald             break;
21153deb3ec6SMatthias Ringwald         default:
21163deb3ec6SMatthias Ringwald             break;
21173deb3ec6SMatthias Ringwald     }
2118d7f1c72eSMatthias Ringwald     return false;
2119d7f1c72eSMatthias Ringwald }
21203deb3ec6SMatthias Ringwald 
21213deb3ec6SMatthias Ringwald // random address updates
2122d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21233deb3ec6SMatthias Ringwald     switch (rau_state){
2124fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2125fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21265b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2127d7f1c72eSMatthias Ringwald             return true;
21283deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21293deb3ec6SMatthias Ringwald             // already busy?
21303deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2131d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2132d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2133d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2134d7f1c72eSMatthias Ringwald                 return true;
21353deb3ec6SMatthias Ringwald             }
21363deb3ec6SMatthias Ringwald             break;
21373deb3ec6SMatthias Ringwald         default:
21383deb3ec6SMatthias Ringwald             break;
21393deb3ec6SMatthias Ringwald     }
2140d7f1c72eSMatthias Ringwald     return false;
2141d7f1c72eSMatthias Ringwald }
21423deb3ec6SMatthias Ringwald 
21433deb3ec6SMatthias Ringwald // CSRK Lookup
2144d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2145d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2146d7f1c72eSMatthias Ringwald 
21473deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21483deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21493deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2150665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2151665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21523deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21533deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21543deb3ec6SMatthias Ringwald                 // and start lookup
21553deb3ec6SMatthias 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);
21563deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21573deb3ec6SMatthias Ringwald                 break;
21583deb3ec6SMatthias Ringwald             }
21593deb3ec6SMatthias Ringwald         }
21603deb3ec6SMatthias Ringwald     }
21613deb3ec6SMatthias Ringwald 
21623deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21633deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2164665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21653deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2166665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21673deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21683deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21693deb3ec6SMatthias Ringwald         }
21703deb3ec6SMatthias Ringwald     }
21713deb3ec6SMatthias Ringwald 
21723deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21733deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2174092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2175092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2176adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21773deb3ec6SMatthias Ringwald             bd_addr_t addr;
21783deb3ec6SMatthias Ringwald             sm_key_t irk;
21793deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21803deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21813deb3ec6SMatthias Ringwald 
2182adf5eaa9SMatthias Ringwald             // skip unused entries
2183adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2184adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2185adf5eaa9SMatthias Ringwald                 continue;
2186adf5eaa9SMatthias Ringwald             }
2187adf5eaa9SMatthias Ringwald 
21885df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21893deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2190a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21913deb3ec6SMatthias Ringwald                 break;
21923deb3ec6SMatthias Ringwald             }
21933deb3ec6SMatthias Ringwald 
2194a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2195a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21963deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21973deb3ec6SMatthias Ringwald                 continue;
21983deb3ec6SMatthias Ringwald             }
21993deb3ec6SMatthias Ringwald 
22003deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
22013deb3ec6SMatthias Ringwald 
22023deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
22038314c363SMatthias Ringwald             log_info_key("IRK", irk);
22043deb3ec6SMatthias Ringwald 
22056535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2206d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
22073deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2208d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2209d1a1f6a4SMatthias 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);
2210d7f1c72eSMatthias Ringwald             return true;
22113deb3ec6SMatthias Ringwald         }
22123deb3ec6SMatthias Ringwald 
2213092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22143deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22153deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22163deb3ec6SMatthias Ringwald         }
22173deb3ec6SMatthias Ringwald     }
2218d7f1c72eSMatthias Ringwald     return false;
2219d7f1c72eSMatthias Ringwald }
22203deb3ec6SMatthias Ringwald 
2221d7f1c72eSMatthias Ringwald // SC OOB
2222d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2223c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2224c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2225c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2226c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2227c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2228c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2229d7f1c72eSMatthias Ringwald             return true;
2230c59d0c92SMatthias Ringwald         default:
2231c59d0c92SMatthias Ringwald             break;
2232c59d0c92SMatthias Ringwald     }
2233c59d0c92SMatthias Ringwald #endif
2234d7f1c72eSMatthias Ringwald     return false;
2235d7f1c72eSMatthias Ringwald }
2236275aafe8SMatthias Ringwald 
2237687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2238687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2239687a03c8SMatthias Ringwald }
2240687a03c8SMatthias Ringwald 
224141d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2242d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2243d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
224441d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2245e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
224641d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
224741d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
224841d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2249f4935286SMatthias Ringwald 
2250f4935286SMatthias Ringwald             // general
2251f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2252f4935286SMatthias Ringwald                 uint8_t buffer[2];
2253f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2254f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2255f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2256687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2257f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2258f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2259f4935286SMatthias Ringwald                 break;
2260f4935286SMatthias Ringwald             }
2261f4935286SMatthias Ringwald 
226241d32297SMatthias Ringwald             // responder side
226341d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
226441d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
226541d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2266d7f1c72eSMatthias Ringwald                 return true;
22674b8b5afeSMatthias Ringwald 
22684b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22694b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22704b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22714b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2272e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22734b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22744b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2275d7f1c72eSMatthias Ringwald                         return true;
22764b8b5afeSMatthias Ringwald                     default:
22774b8b5afeSMatthias Ringwald                         break;
22784b8b5afeSMatthias Ringwald                 }
22794b8b5afeSMatthias Ringwald                 break;
22804b8b5afeSMatthias Ringwald #endif
228141d32297SMatthias Ringwald             default:
228241d32297SMatthias Ringwald                 break;
228341d32297SMatthias Ringwald         }
228441d32297SMatthias Ringwald     }
2285d7f1c72eSMatthias Ringwald     return false;
2286d7f1c72eSMatthias Ringwald }
22873deb3ec6SMatthias Ringwald 
2288d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22893deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2290d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22913deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22927149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2293665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22943deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22953deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22961979f09cSMatthias Ringwald         bool done = true;
22973deb3ec6SMatthias Ringwald         int err;
229842134bc6SMatthias Ringwald         UNUSED(err);
229934b6528fSMatthias Ringwald 
230034b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
230134b6528fSMatthias Ringwald         // assert ec key is ready
2302505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2303178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2304178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
230534b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
230634b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
230734b6528fSMatthias Ringwald             }
230834b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
230934b6528fSMatthias Ringwald                 continue;
231034b6528fSMatthias Ringwald             }
231134b6528fSMatthias Ringwald         }
231234b6528fSMatthias Ringwald #endif
231334b6528fSMatthias Ringwald 
23143deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
231542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23163deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23173deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
231842134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2319549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
232006cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
232187014f74SMatthias Ringwald #endif
232287014f74SMatthias Ringwald #endif
232334c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23245567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
232534c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2326549ad5d2SMatthias Ringwald #endif
2327c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2328c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2329c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2330c18be159SMatthias Ringwald #endif
233187014f74SMatthias Ringwald 				// just lock context
233287014f74SMatthias Ringwald 				break;
23333deb3ec6SMatthias Ringwald             default:
23341979f09cSMatthias Ringwald                 done = false;
23353deb3ec6SMatthias Ringwald                 break;
23363deb3ec6SMatthias Ringwald         }
23373deb3ec6SMatthias Ringwald         if (done){
23387149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23397149bde5SMatthias 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);
23403deb3ec6SMatthias Ringwald         }
23413deb3ec6SMatthias Ringwald     }
2342d7f1c72eSMatthias Ringwald }
2343d7f1c72eSMatthias Ringwald 
2344403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2345403280b9SMatthias Ringwald     int i;
2346403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2347403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2348403280b9SMatthias Ringwald     uint8_t action = 0;
2349403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2350403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2351403280b9SMatthias Ringwald             bool clear_flag = true;
2352403280b9SMatthias Ringwald             switch (i){
2353403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2354403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2355403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2356403280b9SMatthias Ringwald                 default:
2357403280b9SMatthias Ringwald                     break;
2358403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2359403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2360403280b9SMatthias Ringwald                     num_actions--;
2361403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2362403280b9SMatthias Ringwald                     break;
2363403280b9SMatthias Ringwald             }
2364403280b9SMatthias Ringwald             if (clear_flag){
2365403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2366403280b9SMatthias Ringwald             }
2367403280b9SMatthias Ringwald             action = i;
2368403280b9SMatthias Ringwald             break;
2369403280b9SMatthias Ringwald         }
2370403280b9SMatthias Ringwald     }
2371403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2372403280b9SMatthias Ringwald 
2373403280b9SMatthias Ringwald     // send keypress notification
2374403280b9SMatthias Ringwald     uint8_t buffer[2];
2375403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2376403280b9SMatthias Ringwald     buffer[1] = action;
2377687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2378403280b9SMatthias Ringwald 
2379403280b9SMatthias Ringwald     // try
2380403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2381403280b9SMatthias Ringwald }
2382403280b9SMatthias Ringwald 
2383403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2384403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2385403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2386403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2387403280b9SMatthias Ringwald         uint8_t buffer[17];
2388403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2389403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2390687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2391403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2392403280b9SMatthias Ringwald         return;
2393403280b9SMatthias Ringwald     }
2394403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2395403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2396403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2397403280b9SMatthias Ringwald         uint8_t buffer[11];
2398403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2399403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2400403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2401687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2402403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2403403280b9SMatthias Ringwald         return;
2404403280b9SMatthias Ringwald     }
2405403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2406403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2407403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2408403280b9SMatthias Ringwald         uint8_t buffer[17];
2409403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2410403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2411687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2412403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2413403280b9SMatthias Ringwald         return;
2414403280b9SMatthias Ringwald     }
2415403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2416403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2417403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2418403280b9SMatthias Ringwald         bd_addr_t local_address;
2419403280b9SMatthias Ringwald         uint8_t buffer[8];
2420403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2421403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2422403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2423403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2424403280b9SMatthias Ringwald                 // public or static random
2425403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2426403280b9SMatthias Ringwald                 break;
2427403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2428403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2429403280b9SMatthias Ringwald                 // fallback to public
2430403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2431403280b9SMatthias Ringwald                 buffer[1] = 0;
2432403280b9SMatthias Ringwald                 break;
2433403280b9SMatthias Ringwald             default:
2434403280b9SMatthias Ringwald                 btstack_assert(false);
2435403280b9SMatthias Ringwald                 break;
2436403280b9SMatthias Ringwald         }
2437403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2438687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2439403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2440403280b9SMatthias Ringwald         return;
2441403280b9SMatthias Ringwald     }
2442403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2443403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2444403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2445403280b9SMatthias Ringwald 
2446403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2447403280b9SMatthias Ringwald         // hack to reproduce test runs
2448403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2449403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2450403280b9SMatthias Ringwald                     }
2451403280b9SMatthias Ringwald 
2452403280b9SMatthias Ringwald                     // store local CSRK
2453403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2454403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2455403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2456403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2457403280b9SMatthias Ringwald                     }
2458403280b9SMatthias Ringwald #endif
2459403280b9SMatthias Ringwald 
2460403280b9SMatthias Ringwald         uint8_t buffer[17];
2461403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2462403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2463687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2464403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2465403280b9SMatthias Ringwald         return;
2466403280b9SMatthias Ringwald     }
2467403280b9SMatthias Ringwald     btstack_assert(false);
2468403280b9SMatthias Ringwald }
2469403280b9SMatthias Ringwald 
2470bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2471bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2472bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2473bbd73538SMatthias Ringwald     // - use secure connections
2474bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2475bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2476bbd73538SMatthias 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;
2477bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2478bbd73538SMatthias Ringwald     // - need identity address / public addr
2479bbd73538SMatthias 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);
2480bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2481bbd73538SMatthias 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)
2482bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2483bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2484bbd73538SMatthias 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.
2485bbd73538SMatthias Ringwald     uint8_t link_key[16];
2486bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2487bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
24887040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2489bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2490bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2491bbd73538SMatthias Ringwald         return false;
2492bbd73538SMatthias Ringwald     }
2493bbd73538SMatthias Ringwald     // get started (all of the above are true)
2494bbd73538SMatthias Ringwald     return true;
2495bbd73538SMatthias Ringwald #else
2496bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2497bbd73538SMatthias Ringwald 	return false;
2498bbd73538SMatthias Ringwald #endif
2499bbd73538SMatthias Ringwald }
2500bbd73538SMatthias Ringwald 
25016f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
25026f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
25036f7422f1SMatthias 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;
25046f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
25056f7422f1SMatthias Ringwald     } else {
25066f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25076f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25086f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25096f7422f1SMatthias Ringwald     }
25106f7422f1SMatthias Ringwald }
25116f7422f1SMatthias Ringwald 
2512af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2513af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2514af7ef9d1SMatthias 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;
2515af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2516af7ef9d1SMatthias Ringwald     } else {
2517af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2518af7ef9d1SMatthias Ringwald     }
2519af7ef9d1SMatthias Ringwald }
2520af7ef9d1SMatthias Ringwald 
2521d7f1c72eSMatthias Ringwald static void sm_run(void){
2522d7f1c72eSMatthias Ringwald 
2523d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2524d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2525d7f1c72eSMatthias Ringwald 
2526d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2527d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2528d7f1c72eSMatthias Ringwald 
2529d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2530d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2531d7f1c72eSMatthias Ringwald 
2532d7f1c72eSMatthias Ringwald     bool done;
2533d7f1c72eSMatthias Ringwald 
2534d7f1c72eSMatthias Ringwald     //
2535d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2536d7f1c72eSMatthias Ringwald     //
2537d7f1c72eSMatthias Ringwald 
2538d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2539d7f1c72eSMatthias Ringwald     if (done) return;
2540d7f1c72eSMatthias Ringwald 
2541d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2542d7f1c72eSMatthias Ringwald     if (done) return;
2543d7f1c72eSMatthias Ringwald 
2544d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2545d7f1c72eSMatthias Ringwald     if (done) return;
2546d7f1c72eSMatthias Ringwald 
2547d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2548d7f1c72eSMatthias Ringwald     if (done) return;
2549d7f1c72eSMatthias Ringwald 
2550d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2551d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2552d7f1c72eSMatthias Ringwald 
2553d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2554d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2555d7f1c72eSMatthias Ringwald     if (done) return;
2556d7f1c72eSMatthias Ringwald 
2557d7f1c72eSMatthias Ringwald     //
2558d7f1c72eSMatthias Ringwald     // active connection handling
2559d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2560d7f1c72eSMatthias Ringwald 
2561d7f1c72eSMatthias Ringwald     while (true) {
2562d7f1c72eSMatthias Ringwald 
2563d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2564d7f1c72eSMatthias Ringwald 
2565d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25663deb3ec6SMatthias Ringwald 
25673deb3ec6SMatthias Ringwald         //
25683deb3ec6SMatthias Ringwald         // active connection handling
25693deb3ec6SMatthias Ringwald         //
25703deb3ec6SMatthias Ringwald 
25713cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25723cf37b8cSMatthias Ringwald         if (!connection) {
25733cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25743cf37b8cSMatthias Ringwald             return;
25753cf37b8cSMatthias Ringwald         }
25763cf37b8cSMatthias Ringwald 
25773deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25787149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25797149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25807149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2581b170b20fSMatthias Ringwald             return;
2582b170b20fSMatthias Ringwald         }
25833deb3ec6SMatthias Ringwald 
25843d7fe1e9SMatthias Ringwald         // send keypress notifications
2585dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2586403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2587d7471931SMatthias Ringwald             return;
25883d7fe1e9SMatthias Ringwald         }
25893d7fe1e9SMatthias Ringwald 
25903deb3ec6SMatthias Ringwald         int key_distribution_flags;
259142134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2592b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2593b6afa23eSMatthias Ringwald         int err;
25949b75de03SMatthias Ringwald         bool have_ltk;
25959b75de03SMatthias Ringwald         uint8_t ltk[16];
2596b6f39a74SMatthias Ringwald #endif
25973deb3ec6SMatthias Ringwald 
25983deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2599dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2600dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2601dd4a08fbSMatthias Ringwald         }
26023deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
26033deb3ec6SMatthias Ringwald 
2604f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2605aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2606aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2607aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2608aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2609aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2610aec94140SMatthias Ringwald                 break;
2611688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2612688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2613688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2614688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2615688a08f9SMatthias Ringwald                 break;
2616dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2617dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2618dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2619dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2620dc300847SMatthias Ringwald                 break;
2621019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2622b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2623019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26240346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26250346c37cSMatthias Ringwald                 break;
26260346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2627b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26280346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26290346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26300346c37cSMatthias Ringwald                 break;
26310346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2632b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26330346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26340346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26350346c37cSMatthias Ringwald                 break;
26360346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2637b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26380346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26390346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2640019005a0SMatthias Ringwald                 break;
2641bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2642b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2643bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2644b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2645bd57ffebSMatthias Ringwald                 break;
2646e0a03c85SMatthias Ringwald #endif
2647e0a03c85SMatthias Ringwald 
264842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26493deb3ec6SMatthias Ringwald             // initiator side
2650f32b7a88SMatthias Ringwald 
26515567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2652f32b7a88SMatthias Ringwald 				sm_reset_setup();
2653f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2654daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2655f32b7a88SMatthias Ringwald 
26563deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26579c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26585567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26593deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2660c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2661c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26623deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26633deb3ec6SMatthias Ringwald                 return;
26643deb3ec6SMatthias Ringwald             }
26653deb3ec6SMatthias Ringwald 
2666b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2667b26f445fSMatthias Ringwald 				sm_reset_setup();
2668b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2669b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2670d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2671b26f445fSMatthias Ringwald 
26721ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26733deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2674687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26753deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26763deb3ec6SMatthias Ringwald                 break;
267742134bc6SMatthias Ringwald #endif
26783deb3ec6SMatthias Ringwald 
267927c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
268041d32297SMatthias Ringwald 
2681c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26821979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26831979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
268427c32905SMatthias Ringwald                 uint8_t buffer[65];
268527c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
268627c32905SMatthias Ringwald                 //
2687fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2688fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2689e53be891SMatthias Ringwald 
2690349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2691349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2692349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2693349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2694349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2695349d0adbSMatthias Ringwald                 }
2696349d0adbSMatthias Ringwald #endif
2697349d0adbSMatthias Ringwald 
269845a61d50SMatthias Ringwald                 // stk generation method
269945a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
270045a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
270145a61d50SMatthias Ringwald                     case JUST_WORKS:
270247fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
270342134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
270407036a04SMatthias Ringwald                             // responder
27051979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2706b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
270727c32905SMatthias Ringwald                         } else {
270807036a04SMatthias Ringwald                             // initiator
2709c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271027c32905SMatthias Ringwald                         }
271145a61d50SMatthias Ringwald                         break;
271245a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
271345a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
271447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
271507036a04SMatthias Ringwald                         // use random TK for display
27166535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27176535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
271845a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
271907036a04SMatthias Ringwald 
272042134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272145a61d50SMatthias Ringwald                             // responder
2722c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
272345a61d50SMatthias Ringwald                         } else {
272445a61d50SMatthias Ringwald                             // initiator
2725c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272645a61d50SMatthias Ringwald                         }
27271979f09cSMatthias Ringwald                         trigger_user_response = true;
272845a61d50SMatthias Ringwald                         break;
272945a61d50SMatthias Ringwald                     case OOB:
273065a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
273165a9a04eSMatthias Ringwald                             // responder
273265a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
273365a9a04eSMatthias Ringwald                         } else {
273465a9a04eSMatthias Ringwald                             // initiator
273565a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
273665a9a04eSMatthias Ringwald                         }
273745a61d50SMatthias Ringwald                         break;
27387bbeb3adSMilanka Ringwald                     default:
27397bbeb3adSMilanka Ringwald                         btstack_assert(false);
27407bbeb3adSMilanka Ringwald                         break;
274145a61d50SMatthias Ringwald                 }
274245a61d50SMatthias Ringwald 
2743687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
274427c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2745644c6a1dSMatthias Ringwald 
2746b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2747644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2748644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2749644c6a1dSMatthias Ringwald                 }
2750b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2751b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2752b90c4e75SMatthias Ringwald                 }
275327c32905SMatthias Ringwald                 break;
275427c32905SMatthias Ringwald             }
2755c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2756e53be891SMatthias Ringwald                 uint8_t buffer[17];
2757e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27589af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
275942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2760c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2761e53be891SMatthias Ringwald                 } else {
2762c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2763e53be891SMatthias Ringwald                 }
2764687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2765e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2766e53be891SMatthias Ringwald                 break;
2767e53be891SMatthias Ringwald             }
2768c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2769e53be891SMatthias Ringwald                 uint8_t buffer[17];
2770e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2771e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27729d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27734ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
277440c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
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_PAIRING_RANDOM;
278145a61d50SMatthias Ringwald                     }
278245a61d50SMatthias Ringwald                 } else {
278340c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
278442134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2785e53be891SMatthias Ringwald                         // responder
278647fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
278740c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2788901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27892886623dSMatthias Ringwald                         } else {
279040c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27912886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2792446a8c36SMatthias Ringwald                         }
2793e53be891SMatthias Ringwald                     } else {
2794136d331aSMatthias Ringwald                         // initiator
2795c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2796e53be891SMatthias Ringwald                     }
279745a61d50SMatthias Ringwald                 }
2798687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2799e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2800e53be891SMatthias Ringwald                 break;
2801e53be891SMatthias Ringwald             }
2802c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2803e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2804e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2805e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2806dc300847SMatthias Ringwald 
280742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2808c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2809e53be891SMatthias Ringwald                 } else {
2810c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2811e53be891SMatthias Ringwald                 }
2812e083ca23SMatthias Ringwald 
2813687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2814e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2815e53be891SMatthias Ringwald                 break;
2816e53be891SMatthias Ringwald             }
2817e53be891SMatthias Ringwald 
2818e53be891SMatthias Ringwald #endif
281942134bc6SMatthias Ringwald 
282042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2821dd12a62bSMatthias Ringwald 
282287014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
282387014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
282487014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2825687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2826c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
282787014f74SMatthias Ringwald 				break;
282887014f74SMatthias Ringwald 			}
282987014f74SMatthias Ringwald 
283038196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
283138196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
283238196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
283338196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
283438196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
283538196718SMatthias Ringwald 						// start using context by loading security info
283638196718SMatthias Ringwald 						sm_reset_setup();
283738196718SMatthias Ringwald 						sm_load_security_info(connection);
283838196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
283938196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
284038196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
284142646f38SMatthias Ringwald                             sm_reencryption_started(connection);
284238196718SMatthias Ringwald                             sm_trigger_run();
284338196718SMatthias Ringwald 							break;
284438196718SMatthias Ringwald 						}
284538196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
284638196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
284738196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
284838196718SMatthias Ringwald 						return;
284938196718SMatthias Ringwald 					default:
285038196718SMatthias Ringwald 						// just wait until IRK lookup is completed
285138196718SMatthias Ringwald 						break;
285238196718SMatthias Ringwald 				}
285338196718SMatthias Ringwald 				break;
285438196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
285538196718SMatthias Ringwald 
2856b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2857b6afa23eSMatthias Ringwald                 sm_reset_setup();
28589b75de03SMatthias Ringwald 
28599b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28609b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28619b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28629b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28639b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28649b75de03SMatthias Ringwald                         if (have_ltk){
28659b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
286619a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28679b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28689b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28699b75de03SMatthias Ringwald                         }
28709b75de03SMatthias Ringwald                         break;
28719b75de03SMatthias Ringwald                     default:
28729b75de03SMatthias Ringwald                         break;
28739b75de03SMatthias Ringwald                 }
28749b75de03SMatthias Ringwald 
2875b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2876d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
287739543d07SMatthias Ringwald 
2878b6afa23eSMatthias Ringwald 				// recover pairing request
2879b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2880b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2881b6afa23eSMatthias Ringwald 
2882b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2883b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2884b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2885b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2886b6afa23eSMatthias Ringwald                     }
2887b6afa23eSMatthias Ringwald #endif
28889305033eSMatthias Ringwald 				if (err != 0){
2889f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2890b6afa23eSMatthias Ringwald 					sm_trigger_run();
2891b6afa23eSMatthias Ringwald 					break;
2892b6afa23eSMatthias Ringwald 				}
2893b6afa23eSMatthias Ringwald 
2894b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2895b6afa23eSMatthias Ringwald 
2896b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2897b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2898b6afa23eSMatthias 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);
2899b6afa23eSMatthias Ringwald 					break;
2900b6afa23eSMatthias Ringwald 				}
2901b6afa23eSMatthias Ringwald 
2902b6afa23eSMatthias Ringwald 				/* fall through */
2903b6afa23eSMatthias Ringwald 
29043deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29051ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2906f55bd529SMatthias Ringwald 
2907f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29083deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29091ad129beSMatthias Ringwald 
2910f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2911f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2912f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2913f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2914f55bd529SMatthias Ringwald                 }
2915f55bd529SMatthias Ringwald #endif
2916f55bd529SMatthias Ringwald                 // setup in response
2917f55bd529SMatthias 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);
2918f55bd529SMatthias 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);
2919f55bd529SMatthias Ringwald 
2920f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29219a90d41aSMatthias 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));
2922f55bd529SMatthias Ringwald 
292327c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2924c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29250b8af2a5SMatthias Ringwald                 } else {
29260b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
292727c32905SMatthias Ringwald                 }
29280b8af2a5SMatthias Ringwald 
2929687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29303deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2931446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2932c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29333deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2934446a8c36SMatthias Ringwald                 }
29353deb3ec6SMatthias Ringwald                 return;
293642134bc6SMatthias Ringwald #endif
29373deb3ec6SMatthias Ringwald 
29383deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29393deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29403deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29419c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
294242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29433deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29443deb3ec6SMatthias Ringwald                 } else {
29453deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29463deb3ec6SMatthias Ringwald                 }
2947687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29483deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29493deb3ec6SMatthias Ringwald                 break;
29503deb3ec6SMatthias Ringwald             }
29513deb3ec6SMatthias Ringwald 
2952d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29533deb3ec6SMatthias Ringwald                 // already busy?
29543deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2955d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2956d1a1f6a4SMatthias 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);
2957d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2958d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2959f3582630SMatthias 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);
29603deb3ec6SMatthias Ringwald                 break;
29613deb3ec6SMatthias Ringwald 
29623deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29633deb3ec6SMatthias Ringwald                 // already busy?
29643deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29653deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2966d1a1f6a4SMatthias 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);
2967d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2968d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2969f3582630SMatthias 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);
29703deb3ec6SMatthias Ringwald                 break;
2971d1a1f6a4SMatthias Ringwald 
29723deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29733deb3ec6SMatthias Ringwald                 // already busy?
29743deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29753deb3ec6SMatthias Ringwald                 // calculate STK
297642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2977d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29783deb3ec6SMatthias Ringwald                 } else {
2979d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29803deb3ec6SMatthias Ringwald                 }
2981d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2982d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2983f3582630SMatthias 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);
29843deb3ec6SMatthias Ringwald                 break;
2985d1a1f6a4SMatthias Ringwald 
29863deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29873deb3ec6SMatthias Ringwald                 // already busy?
29883deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29893deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29909ad0dd7cSMatthias Ringwald 
29919ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29929ad0dd7cSMatthias Ringwald                 // r' = padding || r
29939ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29949ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29956535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29969ad0dd7cSMatthias Ringwald 
29973deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2998d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2999d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3000f3582630SMatthias 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);
3001d1a1f6a4SMatthias Ringwald                 break;
3002d1a1f6a4SMatthias Ringwald 
30033deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30043deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30053deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30069c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
300742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30083deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30093deb3ec6SMatthias Ringwald                 } else {
30103deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30113deb3ec6SMatthias Ringwald                 }
3012687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30133deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30143deb3ec6SMatthias Ringwald                 return;
30153deb3ec6SMatthias Ringwald             }
301642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30173deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30183deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30199c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30203deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30213deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30223deb3ec6SMatthias Ringwald                 return;
30233deb3ec6SMatthias Ringwald             }
3024d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3025b96d60a6SMatthias Ringwald                 // allow to override LTK
3026b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3027b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3028b96d60a6SMatthias Ringwald                 }
30293deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30309c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30315567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30323deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30333deb3ec6SMatthias Ringwald                 return;
30343deb3ec6SMatthias Ringwald             }
3035dd12a62bSMatthias Ringwald 
3036dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30373deb3ec6SMatthias Ringwald                 // already busy?
30383deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30393deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3040c61cfe5aSMatthias Ringwald 
3041dd12a62bSMatthias Ringwald 				sm_reset_setup();
3042dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3043dd12a62bSMatthias Ringwald 
304442646f38SMatthias Ringwald 				sm_reencryption_started(connection);
304542646f38SMatthias Ringwald 
3046c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3047c61cfe5aSMatthias Ringwald                 // r' = padding || r
3048c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3049c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30506535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3051c61cfe5aSMatthias Ringwald 
30523deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3053d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_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_ph4_y, (void *)(uintptr_t) connection->sm_handle);
30563deb3ec6SMatthias Ringwald                 return;
305742134bc6SMatthias Ringwald #endif
305842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
305942134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
306042134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
306142134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
306242134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
306342134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
306442134bc6SMatthias Ringwald                 return;
306542134bc6SMatthias Ringwald             }
306642134bc6SMatthias Ringwald #endif
30673deb3ec6SMatthias Ringwald 
30683deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3069e94757aeSMatthias Ringwald                 // send next key
3070403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3071403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
3072e94757aeSMatthias Ringwald                 }
3073e94757aeSMatthias Ringwald 
3074e94757aeSMatthias Ringwald                 // more to send?
3075e94757aeSMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
30763deb3ec6SMatthias Ringwald                     return;
30773deb3ec6SMatthias Ringwald                 }
30783deb3ec6SMatthias Ringwald 
30793deb3ec6SMatthias Ringwald                 // keys are sent
308042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30813deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
308261d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30833deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3084f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3085f5020412SMatthias Ringwald                         // start CTKD right away
3086f5020412SMatthias Ringwald                         continue;
30873deb3ec6SMatthias Ringwald                     } else {
30883deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30893deb3ec6SMatthias Ringwald                     }
30903deb3ec6SMatthias Ringwald                 } else {
30911dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30923deb3ec6SMatthias Ringwald                 }
30933deb3ec6SMatthias Ringwald                 break;
30943deb3ec6SMatthias Ringwald 
3095c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3096c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3097c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3098c18be159SMatthias Ringwald                 sm_reset_setup();
3099c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3100c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3101c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3102c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3103c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3104c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3105c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3106c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3107c18be159SMatthias Ringwald 
3108c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3109c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3110c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3111c18be159SMatthias Ringwald                 // Plus signing key if supported
3112c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3113c18be159SMatthias Ringwald #endif
3114c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3115c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3116c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3117c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3118c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3119c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3120c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3121c18be159SMatthias Ringwald 
3122c18be159SMatthias Ringwald                 // set state and send pairing response
3123c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3124c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3125c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3126c18be159SMatthias Ringwald                 break;
3127c18be159SMatthias Ringwald 
3128c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3129c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3130c18be159SMatthias Ringwald                 sm_reset_setup();
3131c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3132c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3133c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3134c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3135c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3136c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3137c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3138c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3139c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3140c18be159SMatthias Ringwald 
3141c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3142c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3143c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3144c18be159SMatthias Ringwald                 // Plus signing key if supported
3145c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3146c18be159SMatthias Ringwald #endif
3147c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3148c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3149c18be159SMatthias Ringwald 
3150c18be159SMatthias 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:
3151c18be159SMatthias Ringwald                 // - the IO Capability field,
3152c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3153c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3154c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3155c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3156c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3157c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3158c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3159c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3160c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3161c18be159SMatthias Ringwald 
3162c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3163c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3164c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3165c18be159SMatthias Ringwald 
3166c18be159SMatthias Ringwald                 // set state and send pairing response
3167c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3168c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3169c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3170c18be159SMatthias Ringwald                 break;
3171c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3172c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3173c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3174c18be159SMatthias Ringwald                     return;
3175c18be159SMatthias Ringwald                 }
3176c18be159SMatthias Ringwald                 // keys are sent
3177c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3178c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
317961d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3180c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3181c18be159SMatthias Ringwald                         break;
3182c18be159SMatthias Ringwald                     }
3183c18be159SMatthias Ringwald                 }
3184c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3185c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3186c18be159SMatthias Ringwald                 continue;
3187c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3188c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3189c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3190c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3191c18be159SMatthias Ringwald                 break;
3192c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3193c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3194c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3195c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3196c18be159SMatthias Ringwald                 break;
3197c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3198c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3199c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3200c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3201c18be159SMatthias Ringwald                 break;
3202c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3203c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3204c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3205c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3206c18be159SMatthias Ringwald                 break;
3207c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3208c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3209c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3210c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3211c18be159SMatthias Ringwald                 break;
3212c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3213c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3214c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3215c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3216c18be159SMatthias Ringwald                 break;
3217c18be159SMatthias Ringwald #endif
3218c18be159SMatthias Ringwald 
32193deb3ec6SMatthias Ringwald             default:
32203deb3ec6SMatthias Ringwald                 break;
32213deb3ec6SMatthias Ringwald         }
32223deb3ec6SMatthias Ringwald 
32233deb3ec6SMatthias Ringwald         // check again if active connection was released
32247149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32253deb3ec6SMatthias Ringwald     }
32263deb3ec6SMatthias Ringwald }
32273deb3ec6SMatthias Ringwald 
3228d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3229d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3230f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323204678764SMatthias Ringwald 
3233f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3234f3582630SMatthias Ringwald     if (connection == NULL) return;
3235f3582630SMatthias Ringwald 
3236d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
323704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3238f3582630SMatthias 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);
3239d1a1f6a4SMatthias Ringwald }
32403deb3ec6SMatthias Ringwald 
3241d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3242f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324404678764SMatthias Ringwald 
3245f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3246f3582630SMatthias Ringwald     if (connection == NULL) return;
3247f3582630SMatthias Ringwald 
32488314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32493deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
325070b44dd4SMatthias Ringwald     sm_trigger_run();
3251d1a1f6a4SMatthias Ringwald }
3252d1a1f6a4SMatthias Ringwald 
3253d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3254d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3255f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
325604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325704678764SMatthias Ringwald 
3258f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3259f3582630SMatthias Ringwald     if (connection == NULL) return;
3260f3582630SMatthias Ringwald 
3261d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
326204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3263f3582630SMatthias 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);
3264d1a1f6a4SMatthias Ringwald }
3265d1a1f6a4SMatthias Ringwald 
3266d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3267f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
326804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
326904678764SMatthias Ringwald 
3270f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3271f3582630SMatthias Ringwald     if (connection == NULL) return;
3272f3582630SMatthias Ringwald 
3273d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3274d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3275f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
327670b44dd4SMatthias Ringwald         sm_trigger_run();
32773deb3ec6SMatthias Ringwald         return;
32783deb3ec6SMatthias Ringwald     }
327942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32803deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
328170b44dd4SMatthias Ringwald         sm_trigger_run();
32823deb3ec6SMatthias Ringwald     } else {
3283d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3284d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3285f3582630SMatthias 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);
32863deb3ec6SMatthias Ringwald     }
32873deb3ec6SMatthias Ringwald }
3288d1a1f6a4SMatthias Ringwald 
3289d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
329004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3291f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
329204678764SMatthias Ringwald 
3293f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3294f3582630SMatthias Ringwald     if (connection == NULL) return;
3295f3582630SMatthias Ringwald 
32963deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32978314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
329842134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32993deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
33003deb3ec6SMatthias Ringwald     } else {
33013deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
33023deb3ec6SMatthias Ringwald     }
330370b44dd4SMatthias Ringwald     sm_trigger_run();
3304d1a1f6a4SMatthias Ringwald }
3305d1a1f6a4SMatthias Ringwald 
3306d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3307d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3308f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
330904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
331004678764SMatthias Ringwald 
3311f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3312f3582630SMatthias Ringwald     if (connection == NULL) return;
3313f3582630SMatthias Ringwald 
3314d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33153deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33163deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33173deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33183deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33193deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33203deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3321d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
332204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3323f3582630SMatthias 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);
33243deb3ec6SMatthias Ringwald }
3325d1a1f6a4SMatthias Ringwald 
33262a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3327d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3328d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
332904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3330f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333104678764SMatthias Ringwald 
3332f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3333f3582630SMatthias Ringwald     if (connection == NULL) return;
3334f3582630SMatthias Ringwald 
3335d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33363deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33373deb3ec6SMatthias Ringwald 
33383deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33393deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33403deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33413deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33423deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3343d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
334404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3345f3582630SMatthias 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);
33463deb3ec6SMatthias Ringwald }
33472a526f21SMatthias Ringwald #endif
3348d1a1f6a4SMatthias Ringwald 
3349d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3350d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3351f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
335204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
335304678764SMatthias Ringwald 
3354f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3355f3582630SMatthias Ringwald     if (connection == NULL) return;
3356f3582630SMatthias Ringwald 
33578314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33583deb3ec6SMatthias Ringwald     // calc CSRK next
3359d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
336004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3361f3582630SMatthias 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);
3362d1a1f6a4SMatthias Ringwald }
3363d1a1f6a4SMatthias Ringwald 
3364d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3365f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
336604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
336704678764SMatthias Ringwald 
3368f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3369f3582630SMatthias Ringwald     if (connection == NULL) return;
3370f3582630SMatthias Ringwald 
3371d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33728314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33733deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33743deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33753deb3ec6SMatthias Ringwald     } else {
33763deb3ec6SMatthias Ringwald         // no keys to send, just continue
337742134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
337861d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3379c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3380c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3381c5a72e35SMatthias Ringwald             } else {
33823deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33833deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3384c5a72e35SMatthias Ringwald             }
33853deb3ec6SMatthias Ringwald         } else {
3386af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33873deb3ec6SMatthias Ringwald         }
33882bacf595SMatthias Ringwald     }
338970b44dd4SMatthias Ringwald     sm_trigger_run();
3390d1a1f6a4SMatthias Ringwald }
3391d1a1f6a4SMatthias Ringwald 
339242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3393d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3394f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
339504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339604678764SMatthias Ringwald 
3397f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3398f3582630SMatthias Ringwald     if (connection == NULL) return;
3399f3582630SMatthias Ringwald 
34003deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
34018314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3402d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
340370b44dd4SMatthias Ringwald     sm_trigger_run();
3404d1a1f6a4SMatthias Ringwald }
3405d1a1f6a4SMatthias Ringwald #endif
3406d1a1f6a4SMatthias Ringwald 
3407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3408d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3409d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341004678764SMatthias Ringwald 
3411d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3412d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3413d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3414d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3415d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3416a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
341770b44dd4SMatthias Ringwald         sm_trigger_run();
34183deb3ec6SMatthias Ringwald         return;
34193deb3ec6SMatthias Ringwald     }
3420d1a1f6a4SMatthias Ringwald     // no match, try next
3421d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
342270b44dd4SMatthias Ringwald     sm_trigger_run();
34233deb3ec6SMatthias Ringwald }
34243deb3ec6SMatthias Ringwald 
3425d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3426d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3427d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342804678764SMatthias Ringwald 
3429d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3430d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
343170b44dd4SMatthias Ringwald     sm_trigger_run();
34327df18c15SMatthias Ringwald }
3433d1a1f6a4SMatthias Ringwald 
3434d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3435d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3436d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
343704678764SMatthias Ringwald 
3438d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3439d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
344070b44dd4SMatthias Ringwald     sm_trigger_run();
34417df18c15SMatthias Ringwald }
3442d1a1f6a4SMatthias Ringwald 
3443d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3444d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3445d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
344604678764SMatthias Ringwald 
34476535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3448e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3449e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3450e91ddb40SMatthias Ringwald 
345170b44dd4SMatthias Ringwald     sm_trigger_run();
345251fa0b28SMatthias Ringwald }
34537df18c15SMatthias Ringwald 
3454d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3455d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34563deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34573deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34583deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34593deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34603deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34614ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34624ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34633deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34643deb3ec6SMatthias Ringwald             break;
34653deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34663deb3ec6SMatthias Ringwald         default:
34673deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34684ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34692954e6c6SMatthias Ringwald             rau_state = RAU_IDLE;
3470e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
34713deb3ec6SMatthias Ringwald             break;
34723deb3ec6SMatthias Ringwald     }
347370b44dd4SMatthias Ringwald     sm_trigger_run();
34743deb3ec6SMatthias Ringwald }
34753deb3ec6SMatthias Ringwald 
3476c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34776ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3478f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3479f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3480f3582630SMatthias Ringwald     if (connection == NULL) return;
3481c59d0c92SMatthias Ringwald 
348265a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
348370b44dd4SMatthias Ringwald     sm_trigger_run();
348465a9a04eSMatthias Ringwald }
3485d1a1f6a4SMatthias Ringwald 
34866ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34876ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34886ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34896ca80073SMatthias Ringwald     if (connection == NULL) return;
34906ca80073SMatthias Ringwald 
3491b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
349270b44dd4SMatthias Ringwald     sm_trigger_run();
3493d1a1f6a4SMatthias Ringwald }
3494f1c1783eSMatthias Ringwald #endif
3495f1c1783eSMatthias Ringwald 
3496d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3497f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3498f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3499f3582630SMatthias Ringwald     if (connection == NULL) return;
3500f3582630SMatthias Ringwald 
3501d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
350270b44dd4SMatthias Ringwald     sm_trigger_run();
3503d1a1f6a4SMatthias Ringwald }
3504d1a1f6a4SMatthias Ringwald 
3505d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3506f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3507f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3508f3582630SMatthias Ringwald     if (connection == NULL) return;
3509f3582630SMatthias Ringwald 
3510caf15bf3SMatthias Ringwald     sm_reset_tk();
3511caf15bf3SMatthias Ringwald     uint32_t tk;
35125ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
35133deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3514d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
35153deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35164ea43905SMatthias Ringwald         if (tk >= 999999u){
35174ea43905SMatthias Ringwald             tk = tk - 999999u;
35183deb3ec6SMatthias Ringwald         }
3519caf15bf3SMatthias Ringwald     } else {
3520caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35214b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3522caf15bf3SMatthias Ringwald     }
3523f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
352442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35253deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35263deb3ec6SMatthias Ringwald     } else {
3527b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3528b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3529b41539d5SMatthias Ringwald         } else {
35303deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35313deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35323deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35333deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3534f3582630SMatthias 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);
35353deb3ec6SMatthias Ringwald             }
35363deb3ec6SMatthias Ringwald         }
3537b41539d5SMatthias Ringwald     }
353870b44dd4SMatthias Ringwald     sm_trigger_run();
35393deb3ec6SMatthias Ringwald }
3540d1a1f6a4SMatthias Ringwald 
3541d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3542f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3543f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3544f3582630SMatthias Ringwald     if (connection == NULL) return;
3545f3582630SMatthias Ringwald 
3546d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3547d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3548d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3549d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
355070b44dd4SMatthias Ringwald     sm_trigger_run();
3551d1a1f6a4SMatthias Ringwald }
3552d1a1f6a4SMatthias Ringwald 
3553d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3554f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3555f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3556f3582630SMatthias Ringwald     if (connection == NULL) return;
3557f3582630SMatthias Ringwald 
3558d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35593deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35604ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35613deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35624ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35638b3ffec5SMatthias 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);
35643deb3ec6SMatthias Ringwald }
3565899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3566899e6e02SMatthias Ringwald     // warn about default ER/IR
35671979f09cSMatthias Ringwald     bool warning = false;
3568899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35691979f09cSMatthias Ringwald         warning = true;
3570899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3571899e6e02SMatthias Ringwald     }
3572899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35731979f09cSMatthias Ringwald         warning = true;
3574899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3575899e6e02SMatthias Ringwald     }
357621045273SMatthias Ringwald     if (warning) {
3577899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3578899e6e02SMatthias Ringwald     }
357921045273SMatthias Ringwald }
3580899e6e02SMatthias Ringwald 
3581899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35821979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35839305033eSMatthias Ringwald     if (arg != NULL){
3584899e6e02SMatthias Ringwald         // key generated, store in tlv
35854ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3586899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3587e0d13a19SMilanka Ringwald         UNUSED(status);
3588899e6e02SMatthias Ringwald     }
3589899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35908d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3591841468bbSMatthias Ringwald 
3592841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3593841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3594841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3595841468bbSMatthias Ringwald     }
3596841468bbSMatthias Ringwald 
359770b44dd4SMatthias Ringwald     sm_trigger_run();
3598899e6e02SMatthias Ringwald }
3599899e6e02SMatthias Ringwald 
3600899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
36011979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36029305033eSMatthias Ringwald     if (arg != 0){
3603899e6e02SMatthias Ringwald         // key generated, store in tlv
36044ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3605899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3606e0d13a19SMilanka Ringwald         UNUSED(status);
3607899e6e02SMatthias Ringwald     }
3608899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3609899e6e02SMatthias Ringwald 
3610899e6e02SMatthias Ringwald     // try load ir
36114ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3612899e6e02SMatthias Ringwald     if (key_size == 16){
3613899e6e02SMatthias Ringwald         // ok, let's continue
3614899e6e02SMatthias Ringwald         log_info("IR from TLV");
3615899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3616899e6e02SMatthias Ringwald     } else {
3617899e6e02SMatthias Ringwald         // invalid, generate new random one
36181979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3619899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3620899e6e02SMatthias Ringwald     }
3621899e6e02SMatthias Ringwald }
36223deb3ec6SMatthias Ringwald 
3623f664b5e8SMatthias 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){
3624f664b5e8SMatthias Ringwald 
3625f664b5e8SMatthias Ringwald     // connection info
3626f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3627f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3628f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3629f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3630f664b5e8SMatthias Ringwald 
3631f664b5e8SMatthias Ringwald     // security properties
3632f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3633f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3634f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3635f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3636f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3637f664b5e8SMatthias Ringwald 
3638f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3639f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3640f664b5e8SMatthias Ringwald 
3641f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3642f664b5e8SMatthias Ringwald }
3643f664b5e8SMatthias Ringwald 
3644d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36453deb3ec6SMatthias Ringwald 
3646cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3647cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36489ec2630cSMatthias Ringwald 
36493deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3650711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3651fbe050beSMatthias Ringwald     uint8_t           status;
3652f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3653f664b5e8SMatthias Ringwald 
36543deb3ec6SMatthias Ringwald     switch (packet_type) {
36553deb3ec6SMatthias Ringwald 
36563deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36570e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36583deb3ec6SMatthias Ringwald 
36593deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
3660745015f6SMatthias Ringwald                     switch (btstack_event_state_get_state(packet)){
3661745015f6SMatthias Ringwald                         case HCI_STATE_WORKING:
36623deb3ec6SMatthias Ringwald                             log_info("HCI Working!");
3663899e6e02SMatthias Ringwald                             // setup IR/ER with TLV
3664899e6e02SMatthias Ringwald                             btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36659305033eSMatthias Ringwald                             if (sm_tlv_impl != NULL){
36664ea43905SMatthias Ringwald                                 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3667899e6e02SMatthias Ringwald                                 if (key_size == 16){
3668899e6e02SMatthias Ringwald                                     // ok, let's continue
3669899e6e02SMatthias Ringwald                                     log_info("ER from TLV");
3670899e6e02SMatthias Ringwald                                     sm_handle_random_result_er( NULL );
3671899e6e02SMatthias Ringwald                                 } else {
3672899e6e02SMatthias Ringwald                                     // invalid, generate random one
36731979f09cSMatthias Ringwald                                     sm_persistent_keys_random_active = true;
3674899e6e02SMatthias Ringwald                                     btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3675899e6e02SMatthias Ringwald                                 }
3676899e6e02SMatthias Ringwald                             } else {
3677899e6e02SMatthias Ringwald                                 sm_validate_er_ir();
36788d9b6072SMatthias Ringwald                                 dkg_state = DKG_CALC_IRK;
3679841468bbSMatthias Ringwald 
3680841468bbSMatthias Ringwald                                 if (test_use_fixed_local_irk){
3681841468bbSMatthias Ringwald                                     log_info_key("IRK", sm_persistent_irk);
3682841468bbSMatthias Ringwald                                     dkg_state = DKG_CALC_DHK;
3683841468bbSMatthias Ringwald                                 }
3684899e6e02SMatthias Ringwald                             }
36851bf086daSMatthias Ringwald 
36861bf086daSMatthias Ringwald                             // restart random address updates after power cycle
36871bf086daSMatthias Ringwald                             gap_random_address_set_mode(gap_random_adress_type);
3688745015f6SMatthias Ringwald                             break;
3689745015f6SMatthias Ringwald 
3690745015f6SMatthias Ringwald                         case HCI_STATE_OFF:
3691745015f6SMatthias Ringwald                             // stop random address update
3692745015f6SMatthias Ringwald                             gap_random_address_update_stop();
3693745015f6SMatthias Ringwald                             break;
3694745015f6SMatthias Ringwald 
3695745015f6SMatthias Ringwald                         default:
3696745015f6SMatthias Ringwald                             break;
36973deb3ec6SMatthias Ringwald                     }
36983deb3ec6SMatthias Ringwald 					break;
3699c18be159SMatthias Ringwald 
37002d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
37012d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
37022d095694SMatthias Ringwald 			        // ignore if connection failed
37032d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
37043deb3ec6SMatthias Ringwald 
37052d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
37062d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
37072d095694SMatthias Ringwald 			        if (!sm_conn) break;
37082d095694SMatthias Ringwald 
37092d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
37102d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
37112d095694SMatthias Ringwald                                        con_handle,
37122d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3713f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
37142d095694SMatthias Ringwald                                        addr);
37152d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
37162d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
37172d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
37182d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3719c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
37202d095694SMatthias Ringwald 			        break;
37212d095694SMatthias Ringwald #endif
3722c18be159SMatthias Ringwald 
3723c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3724c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3725c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3726c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3727c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3728c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3729c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3730c18be159SMatthias Ringwald 			        break;
3731c18be159SMatthias Ringwald #endif
3732c18be159SMatthias Ringwald 
37333deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37343deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37353deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3736f664b5e8SMatthias Ringwald                             // ignore if connection failed
3737f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37383deb3ec6SMatthias Ringwald 
3739711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3740711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37413deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37423deb3ec6SMatthias Ringwald 
3743f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3744f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3745f664b5e8SMatthias Ringwald                                                con_handle,
3746f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3747f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3748f664b5e8SMatthias Ringwald                                                addr);
3749687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3750f664b5e8SMatthias Ringwald 
3751f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3752b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3753b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3754ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3755ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3756f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3757b892db1cSMatthias Ringwald                             }
3758b892db1cSMatthias Ringwald #endif
3759b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3760b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3761ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3762ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37633deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37643deb3ec6SMatthias Ringwald                             }
3765b892db1cSMatthias Ringwald #endif
37663deb3ec6SMatthias Ringwald                             break;
37673deb3ec6SMatthias Ringwald 
37683deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3769711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3770711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37713deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37723deb3ec6SMatthias Ringwald 
37733deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37743deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37753deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37763deb3ec6SMatthias Ringwald                                 break;
37773deb3ec6SMatthias Ringwald                             }
3778c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3779778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3780778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3781e53be891SMatthias Ringwald                                 break;
3782e53be891SMatthias Ringwald                             }
37833deb3ec6SMatthias Ringwald 
37843deb3ec6SMatthias Ringwald                             // store rand and ediv
37859c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3786f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3787549ad5d2SMatthias Ringwald 
3788549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3789549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37904ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37916c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
379206cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3793549ad5d2SMatthias Ringwald                                     break;
3794549ad5d2SMatthias Ringwald                                 }
37956c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37966c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37976c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37986c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37996c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
38006c39055aSMatthias Ringwald                                         break;
38016c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
38026c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
38036c39055aSMatthias Ringwald                                         break;
38046c39055aSMatthias Ringwald                                     default:
38056c39055aSMatthias Ringwald                                         // wait for irk look doen
38066c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
38076c39055aSMatthias Ringwald                                         break;
38086c39055aSMatthias Ringwald                                 }
38096c39055aSMatthias Ringwald                                 break;
38106c39055aSMatthias Ringwald                             }
3811549ad5d2SMatthias Ringwald 
3812549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
381306cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3814549ad5d2SMatthias Ringwald #else
3815549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3816549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3817549ad5d2SMatthias Ringwald #endif
38183deb3ec6SMatthias Ringwald                             break;
3819804d3e67SMatthias Ringwald 
38203deb3ec6SMatthias Ringwald                         default:
38213deb3ec6SMatthias Ringwald                             break;
38223deb3ec6SMatthias Ringwald                     }
38233deb3ec6SMatthias Ringwald                     break;
38243deb3ec6SMatthias Ringwald 
38253deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
38263b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3827711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38283deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38293deb3ec6SMatthias Ringwald 
38303b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38313deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38323deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38333deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
383403a9359aSMatthias Ringwald 
3835fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3836fbe050beSMatthias Ringwald 
38375567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
383803a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3839fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3840fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38418d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38428d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38438d4eef95SMatthias Ringwald                                 } else {
384403a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38458d4eef95SMatthias Ringwald                                 }
3846fbe050beSMatthias Ringwald                             } else {
3847e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3848cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38493b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3850cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38513b7fd749SMatthias Ringwald                             }
3852fbe050beSMatthias Ringwald 
3853fbe050beSMatthias Ringwald                             // emit re-encryption complete
385473102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3855fbe050beSMatthias Ringwald 
3856c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3857c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3858c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38590ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
386003a9359aSMatthias Ringwald                             }
386103a9359aSMatthias Ringwald 
38623deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38633deb3ec6SMatthias Ringwald                             break;
3864fbe050beSMatthias Ringwald 
38653deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3866fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3867dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
386842134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38693deb3ec6SMatthias Ringwald                                 // slave
3870bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3871bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3872bbf8db22SMatthias Ringwald                                 } else {
3873f3582630SMatthias 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);
3874bbf8db22SMatthias Ringwald                                 }
38753deb3ec6SMatthias Ringwald                             } else {
38763deb3ec6SMatthias Ringwald                                 // master
387761d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38783deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38793deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3880f3582630SMatthias 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);
38813deb3ec6SMatthias Ringwald                                 } else {
38823deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38833deb3ec6SMatthias Ringwald                                 }
38843deb3ec6SMatthias Ringwald                             }
38853deb3ec6SMatthias Ringwald                             break;
3886c18be159SMatthias Ringwald 
3887c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3888c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3889c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3890c18be159SMatthias Ringwald                             // prepare for pairing request
3891c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3892c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3893c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3894c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3895c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3896c18be159SMatthias Ringwald                             }
3897c18be159SMatthias Ringwald                             break;
3898c18be159SMatthias Ringwald #endif
38993deb3ec6SMatthias Ringwald                         default:
39003deb3ec6SMatthias Ringwald                             break;
39013deb3ec6SMatthias Ringwald                     }
39023deb3ec6SMatthias Ringwald                     break;
39033deb3ec6SMatthias Ringwald 
39043deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3905711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3906711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39073deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39083deb3ec6SMatthias Ringwald 
39093deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
39103deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
39113deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
39123deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39135567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
39145567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
39155567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39165567aa60SMatthias Ringwald                             } else {
39173deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39185567aa60SMatthias Ringwald                             }
39193deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39203deb3ec6SMatthias Ringwald                             break;
39213deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
392242134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39233deb3ec6SMatthias Ringwald                                 // slave
3924f3582630SMatthias 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);
39253deb3ec6SMatthias Ringwald                             } else {
39263deb3ec6SMatthias Ringwald                                 // master
39273deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39283deb3ec6SMatthias Ringwald                             }
39293deb3ec6SMatthias Ringwald                             break;
39303deb3ec6SMatthias Ringwald                         default:
39313deb3ec6SMatthias Ringwald                             break;
39323deb3ec6SMatthias Ringwald                     }
39333deb3ec6SMatthias Ringwald                     break;
39343deb3ec6SMatthias Ringwald 
39353deb3ec6SMatthias Ringwald 
39363deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3937711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3938711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3939711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39403deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39413deb3ec6SMatthias Ringwald 
394203f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39437f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39447f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39457f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39467f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39477f3f442dSMatthias Ringwald                             break;
39487f3f442dSMatthias Ringwald                         default:
394968a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39500ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39517f3f442dSMatthias Ringwald                             break;
395203f736b1SMatthias Ringwald                     }
3953accbde80SMatthias Ringwald 
39543deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39553deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39563deb3ec6SMatthias Ringwald                     break;
39573deb3ec6SMatthias Ringwald 
39583deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
3959f7811256SMatthias Ringwald                     if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) {
39609091c5f5SMatthias Ringwald                         // set local addr for le device db
396133373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39620c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
396333373e40SMatthias Ringwald                     }
396465b44ffdSMatthias Ringwald                     break;
396565b44ffdSMatthias Ringwald                 default:
396665b44ffdSMatthias Ringwald                     break;
39673deb3ec6SMatthias Ringwald 			}
396865b44ffdSMatthias Ringwald             break;
396965b44ffdSMatthias Ringwald         default:
397065b44ffdSMatthias Ringwald             break;
39713deb3ec6SMatthias Ringwald 	}
39723deb3ec6SMatthias Ringwald 
39733deb3ec6SMatthias Ringwald     sm_run();
39743deb3ec6SMatthias Ringwald }
39753deb3ec6SMatthias Ringwald 
39763deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39773deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39783deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39793deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39803deb3ec6SMatthias Ringwald }
39813deb3ec6SMatthias Ringwald 
3982945888f5SMatthias Ringwald 
398331c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3984945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3985945888f5SMatthias Ringwald     switch (method){
3986945888f5SMatthias Ringwald         case JUST_WORKS:
398747fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3988945888f5SMatthias Ringwald             return 1;
3989945888f5SMatthias Ringwald         default:
3990945888f5SMatthias Ringwald             return 0;
3991945888f5SMatthias Ringwald     }
3992945888f5SMatthias Ringwald }
399307036a04SMatthias Ringwald // responder
3994945888f5SMatthias Ringwald 
3995688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3996688a08f9SMatthias Ringwald     switch (method){
3997688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3998688a08f9SMatthias Ringwald             return 1;
3999688a08f9SMatthias Ringwald         default:
4000688a08f9SMatthias Ringwald             return 0;
4001688a08f9SMatthias Ringwald     }
4002688a08f9SMatthias Ringwald }
400340c5d850SMatthias Ringwald 
400440c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
400540c5d850SMatthias Ringwald     switch (method){
400640c5d850SMatthias Ringwald         case PK_RESP_INPUT:
400740c5d850SMatthias Ringwald         case PK_INIT_INPUT:
400847fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
400940c5d850SMatthias Ringwald             return 1;
401040c5d850SMatthias Ringwald         default:
401140c5d850SMatthias Ringwald             return 0;
401240c5d850SMatthias Ringwald     }
401340c5d850SMatthias Ringwald }
401440c5d850SMatthias Ringwald 
401531c09488SMatthias Ringwald #endif
4016688a08f9SMatthias Ringwald 
40173deb3ec6SMatthias Ringwald /**
40183deb3ec6SMatthias Ringwald  * @return ok
40193deb3ec6SMatthias Ringwald  */
40203deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
40213deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
40223deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
40233deb3ec6SMatthias Ringwald         case JUST_WORKS:
40244ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
40253deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
40263deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
402747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
40284ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
40293deb3ec6SMatthias Ringwald         case OOB:
40304ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
403147fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40324ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40333deb3ec6SMatthias Ringwald         default:
40343deb3ec6SMatthias Ringwald             return 0;
40353deb3ec6SMatthias Ringwald     }
40363deb3ec6SMatthias Ringwald }
40373deb3ec6SMatthias Ringwald 
403836f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
403936f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
404036f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
404136f0defaSMatthias Ringwald     if (sm_sc_only_mode){
404236f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
404336f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
404436f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
404536f0defaSMatthias Ringwald             return;
404636f0defaSMatthias Ringwald         }
404736f0defaSMatthias Ringwald     }
404836f0defaSMatthias Ringwald #else
404936f0defaSMatthias Ringwald     UNUSED(packet);
405036f0defaSMatthias Ringwald #endif
405136f0defaSMatthias Ringwald 
405236f0defaSMatthias Ringwald     int have_ltk;
405336f0defaSMatthias Ringwald     uint8_t ltk[16];
405436f0defaSMatthias Ringwald 
405536f0defaSMatthias Ringwald     // IRK complete?
405636f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
405736f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
405836f0defaSMatthias Ringwald             // start pairing
405936f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
406036f0defaSMatthias Ringwald             break;
406136f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
406236f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
406336f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
406436f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
406536f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
406636f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
406736f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
406836f0defaSMatthias Ringwald             } else {
406936f0defaSMatthias Ringwald                 // start pairing
407036f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
407136f0defaSMatthias Ringwald             }
407236f0defaSMatthias Ringwald             break;
407336f0defaSMatthias Ringwald         default:
407436f0defaSMatthias Ringwald             // otherwise, store security request
407536f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
407636f0defaSMatthias Ringwald             break;
407736f0defaSMatthias Ringwald     }
407836f0defaSMatthias Ringwald }
407936f0defaSMatthias Ringwald #endif
408036f0defaSMatthias Ringwald 
40818334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40828334d3d8SMatthias Ringwald 
40834c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40844c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40854c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40864c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40874c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40884c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40894c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40904c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40914c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40927a2e6387SMatthias Ringwald             11, // 0x07 master identification
40934c1d1092SMatthias Ringwald             17, // 0x08 identification information
40944c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40954c1d1092SMatthias Ringwald             17, // 0x0a signing information
40964c1d1092SMatthias Ringwald             2,  // 0x0b security request
40974c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40984c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40994c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
41004c1d1092SMatthias Ringwald     };
41013deb3ec6SMatthias Ringwald 
4102c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4103b170b20fSMatthias Ringwald         sm_run();
4104b170b20fSMatthias Ringwald     }
4105b170b20fSMatthias Ringwald 
41063deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
41074ea43905SMatthias Ringwald     if (size == 0u) return;
41084c1d1092SMatthias Ringwald 
41094c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
41104c1d1092SMatthias Ringwald 
41114c1d1092SMatthias Ringwald     // validate pdu size
41124c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
41137a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
41143deb3ec6SMatthias Ringwald 
4115711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
41163deb3ec6SMatthias Ringwald     if (!sm_conn) return;
41173deb3ec6SMatthias Ringwald 
41184c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
411968a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
41200ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4121accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
41223deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
41233deb3ec6SMatthias Ringwald         return;
41243deb3ec6SMatthias Ringwald     }
41253deb3ec6SMatthias Ringwald 
41264c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
41273deb3ec6SMatthias Ringwald 
41283deb3ec6SMatthias Ringwald     int err;
412942134bc6SMatthias Ringwald     UNUSED(err);
41303deb3ec6SMatthias Ringwald 
41314c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
41323d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
41333d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
41343d7fe1e9SMatthias Ringwald         buffer[1] = 3;
41353d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
41363d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
41373d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
41383d7fe1e9SMatthias Ringwald         return;
41393d7fe1e9SMatthias Ringwald     }
41403d7fe1e9SMatthias Ringwald 
41413deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
41423deb3ec6SMatthias Ringwald 
4143c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
41443deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
41453deb3ec6SMatthias Ringwald             return;
41463deb3ec6SMatthias Ringwald 
414742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
414842134bc6SMatthias Ringwald 
41493deb3ec6SMatthias Ringwald         // Initiator
41503deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
41514c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
41523deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41533deb3ec6SMatthias Ringwald                 break;
41543deb3ec6SMatthias Ringwald             }
415536f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4156dc8ca372SMatthias Ringwald             break;
41573deb3ec6SMatthias Ringwald 
41583deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4159aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4160aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4161aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4162aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4163aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4164aacfafc3SMatthias Ringwald                 break;
4165aacfafc3SMatthias Ringwald             }
4166aacfafc3SMatthias Ringwald 
4167aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41684c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41693deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41703deb3ec6SMatthias Ringwald                 break;
41713deb3ec6SMatthias Ringwald             }
41720af429c6SMatthias Ringwald 
41733deb3ec6SMatthias Ringwald             // store pairing request
41746535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41756535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41763deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41770af429c6SMatthias Ringwald 
41780af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41790af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41800af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41810af429c6SMatthias Ringwald                 err = test_pairing_failure;
41820af429c6SMatthias Ringwald             }
41830af429c6SMatthias Ringwald #endif
41840af429c6SMatthias Ringwald 
41859305033eSMatthias Ringwald             if (err != 0){
4186f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41873deb3ec6SMatthias Ringwald                 break;
41883deb3ec6SMatthias Ringwald             }
4189b41539d5SMatthias Ringwald 
4190b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4191b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4192f3582630SMatthias 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);
4193b41539d5SMatthias Ringwald                 break;
4194b41539d5SMatthias Ringwald             }
4195b41539d5SMatthias Ringwald 
4196136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4197136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41988cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41998cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4200136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4201136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4202136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4203c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4204136d331aSMatthias Ringwald                     }
42058cba5ca3SMatthias Ringwald                 } else {
4206c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
42078cba5ca3SMatthias Ringwald                 }
4208136d331aSMatthias Ringwald                 break;
4209136d331aSMatthias Ringwald             }
4210136d331aSMatthias Ringwald #endif
42113deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
42123deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
42133deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
42143deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4215f3582630SMatthias 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);
42163deb3ec6SMatthias Ringwald             }
42173deb3ec6SMatthias Ringwald             break;
42183deb3ec6SMatthias Ringwald 
42193deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
42204c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
42213deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42223deb3ec6SMatthias Ringwald                 break;
42233deb3ec6SMatthias Ringwald             }
42243deb3ec6SMatthias Ringwald 
42253deb3ec6SMatthias Ringwald             // store s_confirm
42269c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4227192365feSMatthias Ringwald 
4228aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4229aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4230aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4231aa9b34e5SMatthias Ringwald                 break;
4232aa9b34e5SMatthias Ringwald             }
4233aa9b34e5SMatthias Ringwald 
4234192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4235192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4236192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4237192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4238192365feSMatthias Ringwald             }
4239192365feSMatthias Ringwald #endif
42403deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42413deb3ec6SMatthias Ringwald             break;
42423deb3ec6SMatthias Ringwald 
42433deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42444c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42453deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42463deb3ec6SMatthias Ringwald                 break;;
42473deb3ec6SMatthias Ringwald             }
42483deb3ec6SMatthias Ringwald 
42493deb3ec6SMatthias Ringwald             // received random value
42509c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42513deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42523deb3ec6SMatthias Ringwald             break;
425342134bc6SMatthias Ringwald #endif
42543deb3ec6SMatthias Ringwald 
425542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42563deb3ec6SMatthias Ringwald         // Responder
42573deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42583deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42593deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42604c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42613deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42623deb3ec6SMatthias Ringwald                 break;;
42633deb3ec6SMatthias Ringwald             }
42643deb3ec6SMatthias Ringwald 
42653deb3ec6SMatthias Ringwald             // store pairing request
4266212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4267212d735eSMatthias Ringwald 
4268212d735eSMatthias Ringwald             // check if IRK completed
4269212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4270212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4271212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42723deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42733deb3ec6SMatthias Ringwald                     break;
4274212d735eSMatthias Ringwald                 default:
4275212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4276212d735eSMatthias Ringwald                     break;
4277212d735eSMatthias Ringwald             }
4278212d735eSMatthias Ringwald             break;
427942134bc6SMatthias Ringwald #endif
42803deb3ec6SMatthias Ringwald 
428127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4282c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42834c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
428427c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
428527c32905SMatthias Ringwald                 break;
428627c32905SMatthias Ringwald             }
4287bccf5e67SMatthias Ringwald 
4288e53be891SMatthias Ringwald             // store public key for DH Key calculation
4289fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4290fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4291bccf5e67SMatthias Ringwald 
429202658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
429302658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
429402658749SMatthias Ringwald                 log_info("Remote PK matches ours");
429502658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
429602658749SMatthias Ringwald                 break;
429702658749SMatthias Ringwald             }
429802658749SMatthias Ringwald 
4299d1a1f6a4SMatthias Ringwald             // validate public key
4300d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
43019305033eSMatthias Ringwald             if (err != 0){
430202658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4303349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4304bccf5e67SMatthias Ringwald                 break;
4305bccf5e67SMatthias Ringwald             }
4306891bb64aSMatthias Ringwald 
4307d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4308f3582630SMatthias 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);
43093cf37b8cSMatthias Ringwald 
431065a9a04eSMatthias Ringwald 
431165a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
431242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4313136d331aSMatthias Ringwald                 // responder
4314c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4315136d331aSMatthias Ringwald             } else {
4316136d331aSMatthias Ringwald                 // initiator
4317a1e31e9cSMatthias Ringwald                 // stk generation method
4318a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4319a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4320a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
432147fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4322c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4323a1e31e9cSMatthias Ringwald                         break;
4324a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
432507036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
432607036a04SMatthias Ringwald                         break;
432707036a04SMatthias Ringwald                     case PK_INIT_INPUT:
432847fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
432907036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
433007036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
433107036a04SMatthias Ringwald                             break;
433207036a04SMatthias Ringwald                         }
4333b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4334a1e31e9cSMatthias Ringwald                         break;
4335a1e31e9cSMatthias Ringwald                     case OOB:
4336d1a1f6a4SMatthias Ringwald                         // generate Nx
43374acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43386ca80073SMatthias 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);
4339a1e31e9cSMatthias Ringwald                         break;
43407bbeb3adSMilanka Ringwald                     default:
43417bbeb3adSMilanka Ringwald                         btstack_assert(false);
43427bbeb3adSMilanka Ringwald                         break;
4343a1e31e9cSMatthias Ringwald                 }
4344136d331aSMatthias Ringwald             }
434527c32905SMatthias Ringwald             break;
4346e53be891SMatthias Ringwald 
4347c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43484c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
434945a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
435045a61d50SMatthias Ringwald                 break;
435145a61d50SMatthias Ringwald             }
435245a61d50SMatthias Ringwald             // received confirm value
435345a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
435445a61d50SMatthias Ringwald 
4355192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4356192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4357192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4358192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4359192365feSMatthias Ringwald             }
4360192365feSMatthias Ringwald #endif
436142134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
436245a61d50SMatthias Ringwald                 // responder
436307036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
436407036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
436507036a04SMatthias Ringwald                         // still waiting for passkey
436607036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
436707036a04SMatthias Ringwald                         break;
436807036a04SMatthias Ringwald                     }
436907036a04SMatthias Ringwald                 }
4370b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
437145a61d50SMatthias Ringwald             } else {
437245a61d50SMatthias Ringwald                 // initiator
4373945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43746ca80073SMatthias 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);
4375f1c1783eSMatthias Ringwald                 } else {
4376c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
437745a61d50SMatthias Ringwald                 }
4378f1c1783eSMatthias Ringwald             }
437945a61d50SMatthias Ringwald             break;
438045a61d50SMatthias Ringwald 
4381c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43824c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4383e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4384136d331aSMatthias Ringwald                 break;
4385e53be891SMatthias Ringwald             }
4386e53be891SMatthias Ringwald 
4387e53be891SMatthias Ringwald             // received random value
4388e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4389e53be891SMatthias Ringwald 
43905a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4391ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4392d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4393d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4394d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
439565a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4396d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4397688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4398ae451ec5SMatthias Ringwald                  break;
43995a293e6eSMatthias Ringwald             }
44006f52a196SMatthias Ringwald 
44014acf7b7bSMatthias Ringwald             // OOB
44024acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
44034acf7b7bSMatthias Ringwald 
44044acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
44054acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
44064acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
44074ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
44084acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
44094acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
44104acf7b7bSMatthias Ringwald                     } else {
44116535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
44124acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
44134acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
44144acf7b7bSMatthias Ringwald                     }
44154acf7b7bSMatthias Ringwald                 }  else {
44164ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
44174acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
44184acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
44194acf7b7bSMatthias Ringwald                     } else {
44206535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
44214acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
44224acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
44234acf7b7bSMatthias Ringwald                     }
44244acf7b7bSMatthias Ringwald                 }
44254acf7b7bSMatthias Ringwald 
4426a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
44274acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4428a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4429a680ba6bSMatthias Ringwald                      break;
4430a680ba6bSMatthias Ringwald                 }
44314acf7b7bSMatthias Ringwald             }
4432a680ba6bSMatthias Ringwald 
4433a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4434688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4435e53be891SMatthias Ringwald             break;
4436e53be891SMatthias Ringwald 
4437901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4438901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44393cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4440901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4441901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4442901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4443901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4444901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4445901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4446901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4447c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4448901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4449d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44504c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4451e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4452e53be891SMatthias Ringwald                 break;
4453e53be891SMatthias Ringwald             }
4454e53be891SMatthias Ringwald             // store DHKey Check
4455901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4456e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4457446a8c36SMatthias Ringwald 
4458901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4459901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4460019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4461bd57ffebSMatthias Ringwald             }
4462bd57ffebSMatthias Ringwald             break;
446327c32905SMatthias Ringwald #endif
446427c32905SMatthias Ringwald 
446542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44663deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44674c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44683deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
446927c32905SMatthias Ringwald                 break;
44703deb3ec6SMatthias Ringwald             }
44713deb3ec6SMatthias Ringwald 
44723deb3ec6SMatthias Ringwald             // received confirm value
44739c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44743deb3ec6SMatthias Ringwald 
4475192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4476192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4477192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4478192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4479192365feSMatthias Ringwald             }
4480192365feSMatthias Ringwald #endif
44813deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44823deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44835611a760SMatthias 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);
44843deb3ec6SMatthias Ringwald             }
44853deb3ec6SMatthias Ringwald 
44863deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44873deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4488f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44893deb3ec6SMatthias Ringwald                 break;
44903deb3ec6SMatthias Ringwald             }
44913deb3ec6SMatthias Ringwald 
44923deb3ec6SMatthias Ringwald             // wait for user action?
44933deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44943deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44953deb3ec6SMatthias Ringwald                 break;
44963deb3ec6SMatthias Ringwald             }
44973deb3ec6SMatthias Ringwald 
44983deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4499f3582630SMatthias 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);
45003deb3ec6SMatthias Ringwald             break;
45013deb3ec6SMatthias Ringwald 
45023deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
45034c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
45043deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
45053deb3ec6SMatthias Ringwald                 break;;
45063deb3ec6SMatthias Ringwald             }
45073deb3ec6SMatthias Ringwald 
45083deb3ec6SMatthias Ringwald             // received random value
45099c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
45103deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
45113deb3ec6SMatthias Ringwald             break;
451242134bc6SMatthias Ringwald #endif
45133deb3ec6SMatthias Ringwald 
45143deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
45154c1d1092SMatthias Ringwald             switch(sm_pdu_code){
45163deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
45173deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
45189c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
45193deb3ec6SMatthias Ringwald                     break;
45203deb3ec6SMatthias Ringwald 
45213deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
45223deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4523f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
45249c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
45253deb3ec6SMatthias Ringwald                     break;
45263deb3ec6SMatthias Ringwald 
45273deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
45283deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
45299c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
45303deb3ec6SMatthias Ringwald                     break;
45313deb3ec6SMatthias Ringwald 
45323deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
45333deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
45343deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4535724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
45363deb3ec6SMatthias Ringwald                     break;
45373deb3ec6SMatthias Ringwald 
45383deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45393deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45409c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45413deb3ec6SMatthias Ringwald                     break;
45423deb3ec6SMatthias Ringwald                 default:
45433deb3ec6SMatthias Ringwald                     // Unexpected PDU
45443deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45453deb3ec6SMatthias Ringwald                     break;
45463deb3ec6SMatthias Ringwald             }
45473deb3ec6SMatthias Ringwald             // done with key distribution?
454861d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45493deb3ec6SMatthias Ringwald 
45503deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45513deb3ec6SMatthias Ringwald 
455242134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45536f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45543deb3ec6SMatthias Ringwald                 } else {
4555625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4556625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4557bbf8db22SMatthias Ringwald                     } else {
4558f3582630SMatthias 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);
4559625f00b2SMatthias Ringwald                     }
45603deb3ec6SMatthias Ringwald                 }
45613deb3ec6SMatthias Ringwald             }
45623deb3ec6SMatthias Ringwald             break;
4563c18be159SMatthias Ringwald 
4564c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4565c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4566c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4567c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4568c18be159SMatthias Ringwald                 break;
4569c18be159SMatthias Ringwald             }
4570c18be159SMatthias Ringwald             // store pairing response
4571c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4572c18be159SMatthias Ringwald 
4573c18be159SMatthias Ringwald             // validate encryption key size
4574c18be159SMatthias 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));
4575c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4576c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4577c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4578c18be159SMatthias Ringwald             }
4579c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4580c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4581c18be159SMatthias Ringwald                 break;
4582c18be159SMatthias Ringwald             }
4583c18be159SMatthias Ringwald 
4584c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4585c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4586c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4587c18be159SMatthias Ringwald 
4588c18be159SMatthias Ringwald             // skip receive if there are none
458961d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4590c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4591c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4592c18be159SMatthias Ringwald             } else {
4593c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4594c18be159SMatthias Ringwald             }
4595c18be159SMatthias Ringwald             break;
4596c18be159SMatthias Ringwald 
4597c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4598c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4599c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4600c18be159SMatthias Ringwald                 break;
4601c18be159SMatthias Ringwald             }
4602c18be159SMatthias Ringwald             // store pairing request
4603c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4604c18be159SMatthias Ringwald             // validate encryption key size
4605c18be159SMatthias 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));
4606c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4607c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4608c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4609c18be159SMatthias Ringwald             }
4610c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4611c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4612c18be159SMatthias Ringwald                 break;
4613c18be159SMatthias Ringwald             }
4614c18be159SMatthias Ringwald             // trigger response
4615c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4616c18be159SMatthias Ringwald             break;
4617c18be159SMatthias Ringwald 
4618c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4619c18be159SMatthias Ringwald             switch(sm_pdu_code){
4620c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4621c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4622c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4623c18be159SMatthias Ringwald                     break;
4624c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4625c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4626c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4627c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4628c18be159SMatthias Ringwald                     break;
4629c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4630c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4631c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4632c18be159SMatthias Ringwald                     break;
4633c18be159SMatthias Ringwald                 default:
4634c18be159SMatthias Ringwald                     // Unexpected PDU
4635c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4636c18be159SMatthias Ringwald                     break;
4637c18be159SMatthias Ringwald             }
4638c18be159SMatthias Ringwald 
4639c18be159SMatthias Ringwald             // all keys received
464061d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4641c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4642c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4643c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4644c18be159SMatthias Ringwald                 } else {
4645c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4646c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4647c18be159SMatthias Ringwald                 }
4648c18be159SMatthias Ringwald             }
4649c18be159SMatthias Ringwald             break;
4650c18be159SMatthias Ringwald #endif
4651c18be159SMatthias Ringwald 
46523deb3ec6SMatthias Ringwald         default:
46533deb3ec6SMatthias Ringwald             // Unexpected PDU
46543deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46552d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46563deb3ec6SMatthias Ringwald             break;
46573deb3ec6SMatthias Ringwald     }
46583deb3ec6SMatthias Ringwald 
465970b44dd4SMatthias Ringwald     // try to send next pdu
466070b44dd4SMatthias Ringwald     sm_trigger_run();
46613deb3ec6SMatthias Ringwald }
46623deb3ec6SMatthias Ringwald 
46633deb3ec6SMatthias Ringwald // Security Manager Client API
4664a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46653deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46663deb3ec6SMatthias Ringwald }
46673deb3ec6SMatthias Ringwald 
46684acf7b7bSMatthias 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)){
4669a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4670a680ba6bSMatthias Ringwald }
4671a680ba6bSMatthias Ringwald 
4672b96d60a6SMatthias 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)){
4673b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4674b96d60a6SMatthias Ringwald }
4675b96d60a6SMatthias Ringwald 
467689a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
467789a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
467889a78d34SMatthias Ringwald }
467989a78d34SMatthias Ringwald 
468067f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
468167f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
468267f708e0SMatthias Ringwald }
468367f708e0SMatthias Ringwald 
46843deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46853deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46863deb3ec6SMatthias Ringwald }
46873deb3ec6SMatthias Ringwald 
46883deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46893deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46903deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46913deb3ec6SMatthias Ringwald }
46923deb3ec6SMatthias Ringwald 
46933deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
469498d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
469598d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
469698d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
469798d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
469898d95509SMatthias Ringwald     }
469998d95509SMatthias Ringwald #endif
47003deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
47013deb3ec6SMatthias Ringwald }
47023deb3ec6SMatthias Ringwald 
47033deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
47043deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
47053deb3ec6SMatthias Ringwald }
47063deb3ec6SMatthias Ringwald 
470742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
47083deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
47093deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
47103deb3ec6SMatthias Ringwald }
471142134bc6SMatthias Ringwald #endif
47123deb3ec6SMatthias Ringwald 
47133deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
47146535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
47153deb3ec6SMatthias Ringwald }
47163deb3ec6SMatthias Ringwald 
47173deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
47186535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
47193deb3ec6SMatthias Ringwald }
47203deb3ec6SMatthias Ringwald 
47213deb3ec6SMatthias Ringwald // Testing support only
47223deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
47236535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4724103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4725841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
47263deb3ec6SMatthias Ringwald }
47273deb3ec6SMatthias Ringwald 
47283deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4729841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
47303deb3ec6SMatthias Ringwald }
47313deb3ec6SMatthias Ringwald 
4732d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4733d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4734d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4735d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
473634b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
473770b44dd4SMatthias Ringwald     sm_trigger_run();
4738d1a1f6a4SMatthias Ringwald }
4739674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
474034b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4741674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4742674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4743674e5b4aSMatthias Ringwald }
4744d1a1f6a4SMatthias Ringwald #endif
4745d1a1f6a4SMatthias Ringwald 
4746192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4747192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4748192365feSMatthias Ringwald     test_pairing_failure = reason;
4749192365feSMatthias Ringwald }
4750192365feSMatthias Ringwald #endif
4751192365feSMatthias Ringwald 
47523deb3ec6SMatthias Ringwald void sm_init(void){
47532d2d4d3cSMatthias Ringwald 
47542d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47552d2d4d3cSMatthias Ringwald 
4756899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4757899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4758899e6e02SMatthias Ringwald 
47593deb3ec6SMatthias Ringwald     // defaults
47603deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47613deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4762b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4763b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4764b4343428SMatthias Ringwald 
47653deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47663deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47673deb3ec6SMatthias Ringwald 
47685ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47691979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4770caf15bf3SMatthias Ringwald 
4771d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4772d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47737a766ebfSMatthias Ringwald #endif
47748d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4775fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47763deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47773deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47783deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47793deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47803deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47813deb3ec6SMatthias Ringwald 
47823deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47837149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47843deb3ec6SMatthias Ringwald 
4785841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47863deb3ec6SMatthias Ringwald 
478784c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
478884c0c5c7SMatthias Ringwald 
4789e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4790e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4791e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4792e03e489aSMatthias Ringwald 
4793d1a1f6a4SMatthias Ringwald     //
4794d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4795d1a1f6a4SMatthias Ringwald 
479651bd74d1SMatthias Ringwald     // init le_device_db
479751bd74d1SMatthias Ringwald     le_device_db_init();
479851bd74d1SMatthias Ringwald 
4799b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4800e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
480127c32905SMatthias Ringwald 
480209e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4803674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4804a3aba2f9SMatthias Ringwald #endif
48052d2d4d3cSMatthias Ringwald 
48062d2d4d3cSMatthias Ringwald     sm_initialized = true;
48073deb3ec6SMatthias Ringwald }
48083deb3ec6SMatthias Ringwald 
480915537ea4SMatthias Ringwald void sm_deinit(void){
481015537ea4SMatthias Ringwald     sm_initialized = false;
481115537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
481215537ea4SMatthias Ringwald }
481315537ea4SMatthias Ringwald 
48144b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
48154b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4816caf15bf3SMatthias Ringwald }
4817caf15bf3SMatthias Ringwald 
48186c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
48191979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
48206c39055aSMatthias Ringwald }
48216c39055aSMatthias Ringwald 
4822711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4823711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
48243deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
48253deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
48263deb3ec6SMatthias Ringwald }
48273deb3ec6SMatthias Ringwald 
482877e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
482977e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
483077e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
483177e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
483277e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
483377e2e5edSMatthias Ringwald }
483477e2e5edSMatthias Ringwald #endif
483577e2e5edSMatthias Ringwald 
48366bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4837711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4838711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48393deb3ec6SMatthias Ringwald     if (!sm_conn) return;
48406bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
48416bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
48423deb3ec6SMatthias Ringwald }
48433deb3ec6SMatthias Ringwald 
48443deb3ec6SMatthias Ringwald // request pairing
4845711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4846711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48473deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48483deb3ec6SMatthias Ringwald 
48497af5dcd5SMatthias Ringwald     bool have_ltk;
48507af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48513deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
485242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
485324c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
485424c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
485524c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48567af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48577af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48587af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48597af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48607af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48617af5dcd5SMatthias Ringwald                         if (have_ltk){
48627af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
486324c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48647af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48657af5dcd5SMatthias Ringwald                             break;
48667af5dcd5SMatthias Ringwald                         }
48677af5dcd5SMatthias Ringwald                         /* fall through */
48687af5dcd5SMatthias Ringwald 
48697af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48707af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48717af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48727af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48737af5dcd5SMatthias Ringwald                         break;
48747af5dcd5SMatthias Ringwald                     default:
48757af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48767af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48777af5dcd5SMatthias Ringwald                         break;
48787af5dcd5SMatthias Ringwald                 }
487924c20dc4SMatthias Ringwald                 break;
488024c20dc4SMatthias Ringwald             default:
488124c20dc4SMatthias Ringwald                 break;
488224c20dc4SMatthias Ringwald         }
48833deb3ec6SMatthias Ringwald     } else {
48843deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4885175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4886175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48873deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48883deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48893dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4890f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4891f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4892f53ec649SMatthias Ringwald                         if (have_ltk){
4893c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48945567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4895c245ca32SMatthias Ringwald                             break;
4896f53ec649SMatthias Ringwald                         }
4897cf373d3aSMatthias Ringwald                         /* fall through */
4898c245ca32SMatthias Ringwald 
489934c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
49003deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
49013deb3ec6SMatthias Ringwald                         break;
49023deb3ec6SMatthias Ringwald                     default:
4903d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
490409ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49053deb3ec6SMatthias Ringwald                         break;
49063deb3ec6SMatthias Ringwald                 }
4907175b7faaSMatthias Ringwald                 break;
4908cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4909cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4910cb6d7eb0SMatthias Ringwald                 break;
4911175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
491209ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4913175b7faaSMatthias Ringwald                 break;
4914175b7faaSMatthias Ringwald             default:
4915175b7faaSMatthias Ringwald                 break;
49163deb3ec6SMatthias Ringwald         }
49173deb3ec6SMatthias Ringwald     }
491870b44dd4SMatthias Ringwald     sm_trigger_run();
49193deb3ec6SMatthias Ringwald }
49203deb3ec6SMatthias Ringwald 
49213deb3ec6SMatthias Ringwald // called by client app on authorization request
4922711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4923711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49243deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49253deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4926589f5a99SMatthias 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);
49273deb3ec6SMatthias Ringwald }
49283deb3ec6SMatthias Ringwald 
4929711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4930711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49313deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49323deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4933589f5a99SMatthias 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);
49343deb3ec6SMatthias Ringwald }
49353deb3ec6SMatthias Ringwald 
49363deb3ec6SMatthias Ringwald // GAP Bonding API
49373deb3ec6SMatthias Ringwald 
4938711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4939711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49403deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49413deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
49420af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
49430af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
49440af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49450af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49460af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49470af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49480af429c6SMatthias Ringwald #endif
49490af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4950de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4951de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4952de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
495347fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49540af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4955de2fd182SMatthias Ringwald                     break;
495647fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4957de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4958de2fd182SMatthias Ringwald                     break;
4959de2fd182SMatthias Ringwald                 case JUST_WORKS:
4960de2fd182SMatthias Ringwald                 case OOB:
4961de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4962de2fd182SMatthias Ringwald                     break;
49637bbeb3adSMilanka Ringwald                 default:
49647bbeb3adSMilanka Ringwald                     btstack_assert(false);
49657bbeb3adSMilanka Ringwald                     break;
4966de2fd182SMatthias Ringwald             }
49670af429c6SMatthias Ringwald             break;
49680af429c6SMatthias Ringwald         default:
49690af429c6SMatthias Ringwald             break;
49703deb3ec6SMatthias Ringwald     }
497170b44dd4SMatthias Ringwald     sm_trigger_run();
49723deb3ec6SMatthias Ringwald }
49733deb3ec6SMatthias Ringwald 
4974711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4975711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49763deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49773deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49783deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4979136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4980c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4981bbf8db22SMatthias Ringwald         } else {
4982f3582630SMatthias 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);
4983136d331aSMatthias Ringwald         }
49843deb3ec6SMatthias Ringwald     }
49850346c37cSMatthias Ringwald 
49860346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4987c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4988dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4989446a8c36SMatthias Ringwald     }
49900346c37cSMatthias Ringwald #endif
49910346c37cSMatthias Ringwald 
499270b44dd4SMatthias Ringwald     sm_trigger_run();
49933deb3ec6SMatthias Ringwald }
49943deb3ec6SMatthias Ringwald 
4995c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4996c8c46d51SMatthias Ringwald     // for now, it's the same
4997c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4998c8c46d51SMatthias Ringwald }
4999c8c46d51SMatthias Ringwald 
5000711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
5001711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50023deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50033deb3ec6SMatthias Ringwald     sm_reset_tk();
5004f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
50053deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
50063deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5007f3582630SMatthias 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);
50083deb3ec6SMatthias Ringwald     }
50091c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
50106535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
50116535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
501207036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
501307036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
501407036a04SMatthias Ringwald     }
50151c516d8fSMatthias Ringwald #endif
501670b44dd4SMatthias Ringwald     sm_trigger_run();
50173deb3ec6SMatthias Ringwald }
50183deb3ec6SMatthias Ringwald 
50193d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
50203d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50213d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50223d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5023dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
50244ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5025dd4a08fbSMatthias Ringwald     switch (action){
5026dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5027dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
50284ea43905SMatthias Ringwald             flags |= (1u << action);
5029dd4a08fbSMatthias Ringwald             break;
5030dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5031dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
50324ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5033dd4a08fbSMatthias Ringwald             break;
5034dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
50354ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5036dd4a08fbSMatthias Ringwald                 // erase actions queued
5037dd4a08fbSMatthias Ringwald                 num_actions--;
50384ea43905SMatthias Ringwald                 if (num_actions == 0u){
5039dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50404ea43905SMatthias Ringwald                     flags &= 0x19u;
5041dd4a08fbSMatthias Ringwald                 }
5042dd4a08fbSMatthias Ringwald                 break;
5043dd4a08fbSMatthias Ringwald             }
5044dd4a08fbSMatthias Ringwald             num_actions++;
50454ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5046dd4a08fbSMatthias Ringwald             break;
5047dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50484ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5049dd4a08fbSMatthias Ringwald                 // enter actions queued
5050dd4a08fbSMatthias Ringwald                 num_actions--;
50514ea43905SMatthias Ringwald                 if (num_actions == 0u){
5052dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50534ea43905SMatthias Ringwald                     flags &= 0x19u;
5054dd4a08fbSMatthias Ringwald                 }
5055dd4a08fbSMatthias Ringwald                 break;
5056dd4a08fbSMatthias Ringwald             }
5057dd4a08fbSMatthias Ringwald             num_actions++;
50584ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5059dd4a08fbSMatthias Ringwald             break;
5060dd4a08fbSMatthias Ringwald         default:
5061dd4a08fbSMatthias Ringwald             break;
5062dd4a08fbSMatthias Ringwald     }
5063dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
506470b44dd4SMatthias Ringwald     sm_trigger_run();
50653d7fe1e9SMatthias Ringwald }
50663d7fe1e9SMatthias Ringwald 
5067c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5068d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5069d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5070d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
507170b44dd4SMatthias Ringwald     sm_trigger_run();
5072d1a1f6a4SMatthias Ringwald }
5073c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50748334d3d8SMatthias Ringwald 
50758334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50768334d3d8SMatthias Ringwald 
5077c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5078c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5079d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5080d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5081c59d0c92SMatthias Ringwald     return 0;
5082c59d0c92SMatthias Ringwald }
5083c59d0c92SMatthias Ringwald #endif
5084c59d0c92SMatthias Ringwald 
50853deb3ec6SMatthias Ringwald /**
5086ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5087ba394633SMatthias Ringwald  * @param con_handle
5088ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5089ba394633SMatthias Ringwald  */
5090ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5091ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5092ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5093ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5094ba394633SMatthias Ringwald }
5095ba394633SMatthias Ringwald 
5096ba394633SMatthias Ringwald /**
50973deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50983deb3ec6SMatthias Ringwald  * @param handle
50996b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
51003deb3ec6SMatthias Ringwald  */
5101711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5102711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51033deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
51043deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
51053deb3ec6SMatthias Ringwald }
51063deb3ec6SMatthias Ringwald 
51078f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
510847ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
510947ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
511047ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
511147ba4de1SMatthias Ringwald             return 0;
511247ba4de1SMatthias Ringwald         default:
51138f57b085SMatthias Ringwald             return 1;
51148f57b085SMatthias Ringwald     }
511547ba4de1SMatthias Ringwald }
5116d70217a2SMatthias Ringwald 
511733373e40SMatthias Ringwald static uint8_t own_address_type(void){
5118b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5119b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5120b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5121b95a5a35SMatthias Ringwald         default:
5122b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5123b95a5a35SMatthias Ringwald     }
512433373e40SMatthias Ringwald }
51258f57b085SMatthias Ringwald 
51263deb3ec6SMatthias Ringwald // GAP LE API
51273deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
51283deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51293deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5130b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
51318f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51323deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51333deb3ec6SMatthias Ringwald     gap_random_address_trigger();
51343deb3ec6SMatthias Ringwald }
51353deb3ec6SMatthias Ringwald 
51363deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
51373deb3ec6SMatthias Ringwald     return gap_random_adress_type;
51383deb3ec6SMatthias Ringwald }
51393deb3ec6SMatthias Ringwald 
51403deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
51413deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
51428f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51433deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51443deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51453deb3ec6SMatthias Ringwald }
51463deb3ec6SMatthias Ringwald 
5147667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51488f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51496535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5150e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
51517e252622SMatthias Ringwald }
51527e252622SMatthias Ringwald 
5153d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51543deb3ec6SMatthias Ringwald /*
51553deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51563deb3ec6SMatthias Ringwald  * @param adv_int_min
51573deb3ec6SMatthias Ringwald  * @param adv_int_max
51583deb3ec6SMatthias Ringwald  * @param adv_type
51593deb3ec6SMatthias Ringwald  * @param direct_address_type
51603deb3ec6SMatthias Ringwald  * @param direct_address
51613deb3ec6SMatthias Ringwald  * @param channel_map
51623deb3ec6SMatthias Ringwald  * @param filter_policy
51633deb3ec6SMatthias Ringwald  *
51643deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51653deb3ec6SMatthias Ringwald  */
51663deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51673deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5168b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51693deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51703deb3ec6SMatthias Ringwald }
5171d70217a2SMatthias Ringwald #endif
5172dcd6c9b5SMatthias Ringwald 
5173dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5174dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5175dcd6c9b5SMatthias Ringwald      // wrong connection
5176dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5177dcd6c9b5SMatthias Ringwald     // already encrypted
5178dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5179dcd6c9b5SMatthias Ringwald     // irk status?
5180dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5181dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5182dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5183dcd6c9b5SMatthias Ringwald             return 0;
5184dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5185dcd6c9b5SMatthias Ringwald             break;
5186dcd6c9b5SMatthias Ringwald         default:
5187dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5188dcd6c9b5SMatthias Ringwald             return 1;
5189dcd6c9b5SMatthias Ringwald     }
5190f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5191f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5192b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5193b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5194b15d5ceaSMatthias Ringwald     } else {
5195dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5196dcd6c9b5SMatthias Ringwald     }
5197b15d5ceaSMatthias Ringwald }
51983cdbe9dbSMatthias Ringwald 
51993cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
52003cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
52013cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
52023cdbe9dbSMatthias Ringwald #else
52033cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
52043cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
52053cdbe9dbSMatthias Ringwald #endif
52063cdbe9dbSMatthias Ringwald }
5207052bbdc5SMatthias Ringwald 
5208052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5209052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5210052bbdc5SMatthias Ringwald }
52114f384501SMatthias Ringwald 
52124f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
52134f384501SMatthias Ringwald     uint16_t i;
52144f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
52154f384501SMatthias Ringwald         bd_addr_t entry_address;
52164f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
52174f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
52184f384501SMatthias Ringwald         // skip unused entries
52194f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
52204f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
52214f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
52224f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
52234f384501SMatthias Ringwald #endif
52244f384501SMatthias Ringwald             le_device_db_remove(i);
52254f384501SMatthias Ringwald             break;
52264f384501SMatthias Ringwald         }
52274f384501SMatthias Ringwald     }
52284f384501SMatthias Ringwald }
5229