xref: /btstack/example/sm_pairing_central.c (revision 98f1394d9d4c33f501ec5dcff54d145a92013c5e)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "sm_pairing_central.c"
39 
40 
41 // *****************************************************************************
42 /* EXAMPLE_START(sm_pairing_central): LE Central - Test Pairing Methods
43  *
44  * @text Depending on the Authentication requiremens and IO Capabilities,
45  * the pairing process uses different short and long term key generation method.
46  * This example helps explore the different options incl. LE Secure Connections.
47  * It scans for advertisements and connects to the first device that lists a
48  * random service.
49  */
50  // *****************************************************************************
51 
52 
53 #include <stdint.h>
54 #include <inttypes.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 
59 #include "btstack.h"
60 // sm_pairing_central.gatt contains the declaration of the provided GATT Services + Characteristics
61 // sm_pairing_central.h    contains the binary representation of sm_pairing_central.gatt
62 // it is generated by the build system by calling: $BTSTACK_ROOT/tool/compile_gatt.py sm_pairing_central.gatt sm_pairing_central.h
63 // it needs to be regenerated when the GATT Database declared in sm_pairing_central.gatt file is modified
64 #include "sm_pairing_central.h"
65 
66 
67 // We're looking for a remote device that lists this service in the advertisement
68 // LightBlue assigns 0x1111 as the UUID for a Blank service.
69 #define REMOTE_SERVICE 0x1111
70 
71 // Fixed passkey - used with sm_pairing_peripheral. Passkey is random in general
72 #define FIXED_PASSKEY 123456U
73 
74 
75 static btstack_packet_callback_registration_t hci_event_callback_registration;
76 static btstack_packet_callback_registration_t sm_event_callback_registration;
77 
78 /* @section GAP LE setup for receiving advertisements
79  *
80  * @text GAP LE advertisements are received as custom HCI events of the
81  * GAP_EVENT_ADVERTISING_REPORT type. To receive them, you'll need to register
82  * the HCI packet handler, as shown in Listing GAPLEAdvSetup.
83  */
84 
85 /* LISTING_START(GAPLEAdvSetup): Setting up GAP LE client for receiving advertisements */
86 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
87 static void sm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
88 
89 static void sm_pairing_central_setup(void){
90     l2cap_init();
91 
92     // setup SM: Display only
93     sm_init();
94 
95     // setup ATT server
96     att_server_init(profile_data, NULL, NULL);
97 
98     // setup GATT Client
99     gatt_client_init();
100 
101     // register handler
102     hci_event_callback_registration.callback = &hci_packet_handler;
103     hci_add_event_handler(&hci_event_callback_registration);
104 
105     sm_event_callback_registration.callback = &sm_packet_handler;
106     sm_add_event_handler(&sm_event_callback_registration);
107 
108 
109     // Configuration
110 
111     // Enable mandatory authentication for GATT Client
112     // - if un-encrypted connections are not supported, e.g. when connecting to own device, this enforces authentication
113     // gatt_client_set_required_security_level(LEVEL_2);
114 
115     /**
116      * Choose ONE of the following configurations
117      * Bonding is disabled to allow for repeated testing. It can be enabled by or'ing
118      * SM_AUTHREQ_BONDING to the authentication requirements like this:
119      * sm_set_authentication_requirements( X | SM_AUTHREQ_BONDING)
120      */
121 
122     // LE Legacy Pairing, Just Works
123     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_YES_NO);
124     // sm_set_authentication_requirements(0);
125 
126     // LE Legacy Pairing, Passkey entry initiator enter, responder (us) displays
127     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
128     // sm_set_authentication_requirements(SM_AUTHREQ_MITM_PROTECTION);
129     // sm_use_fixed_passkey_in_display_role(FIXED_PASSKEY);
130 
131 #ifdef ENABLE_LE_SECURE_CONNECTIONS
132 
133     // enable LE Secure Connections Only mode - disables Legacy pairing
134     // sm_set_secure_connections_only_mode(true);
135 
136     // LE Secure Connections, Just Works
137     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_YES_NO);
138     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION);
139 
140     // LE Secure Connections, Numeric Comparison
141     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_YES_NO);
142     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
143 
144     // LE Secure Pairing, Passkey entry initiator (us) enters, responder displays
145     // sm_set_io_capabilities(IO_CAPABILITY_KEYBOARD_ONLY);
146     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
147     // sm_use_fixed_passkey_in_display_role(FIXED_PASSKEY);
148 
149     // LE Secure Pairing, Passkey entry initiator (us) displays, responder enters
150     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
151     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
152 #endif
153 }
154 
155 /* LISTING_END */
156 
157 /* @section HCI packet handler
158  *
159  * @text The HCI packet handler has to start the scanning,
160  * and to handle received advertisements. Advertisements are received
161  * as HCI event packets of the GAP_EVENT_ADVERTISING_REPORT type,
162  * see Listing HCIPacketHandler.
163  */
164 
165 /* LISTING_START(HCIPacketHandler): Scanning and receiving advertisements */
166 
167 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
168     UNUSED(channel);
169     UNUSED(size);
170 
171     if (packet_type != HCI_EVENT_PACKET) return;
172     hci_con_handle_t con_handle;
173     uint8_t status;
174 
175     switch (hci_event_packet_get_type(packet)) {
176         case BTSTACK_EVENT_STATE:
177             // BTstack activated, get started
178             if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
179                 printf("Start scaning!\n");
180                 gap_set_scan_parameters(1,0x0030, 0x0030);
181                 gap_start_scan();
182             }
183             break;
184         case GAP_EVENT_ADVERTISING_REPORT:{
185             bd_addr_t address;
186             gap_event_advertising_report_get_address(packet, address);
187             uint8_t address_type = gap_event_advertising_report_get_address_type(packet);
188             uint8_t length = gap_event_advertising_report_get_data_length(packet);
189             const uint8_t * data = gap_event_advertising_report_get_data(packet);
190             // printf("Advertisement event: addr-type %u, addr %s, data[%u] ",
191             //   address_type, bd_addr_to_str(address), length);
192             // printf_hexdump(data, length);
193             if (!ad_data_contains_uuid16(length, (uint8_t *) data, REMOTE_SERVICE)) break;
194             printf("Found remote with UUID %04x, connecting...\n", REMOTE_SERVICE);
195             gap_stop_scan();
196             gap_connect(address,address_type);
197             break;
198         }
199         case HCI_EVENT_LE_META:
200             // wait for connection complete
201             if (hci_event_le_meta_get_subevent_code(packet) != HCI_SUBEVENT_LE_CONNECTION_COMPLETE) break;
202             con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet);
203             printf("Connection complete\n");
204 
205             // for testing, choose one of the following actions
206 
207             // manually start pairing
208             sm_request_pairing(con_handle);
209 
210             // gatt client request to authenticated characteristic in sm_pairing_peripheral (short cut, uses hard-coded value handle)
211             // gatt_client_read_value_of_characteristic_using_value_handle(&hci_packet_handler, con_handle, 0x0009);
212 
213             // general gatt client request to trigger mandatory authentication
214             // gatt_client_discover_primary_services(&hci_packet_handler, con_handle);
215             break;
216         case HCI_EVENT_ENCRYPTION_CHANGE:
217             con_handle = hci_event_encryption_change_get_connection_handle(packet);
218             printf("Connection encrypted: %u\n", hci_event_encryption_change_get_encryption_enabled(packet));
219             break;
220         case GATT_EVENT_QUERY_COMPLETE:
221             status = gatt_event_query_complete_get_att_status(packet);
222             switch (status){
223                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION:
224                     printf("GATT Query result: Insufficient Encryption\n");
225                     break;
226                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
227                     printf("GATT Query result: Insufficient Authentication\n");
228                     break;
229                 case ATT_ERROR_BONDING_INFORMATION_MISSING:
230                     printf("GATT Query result: Bonding Information Missing\n");
231                     break;
232                 case ATT_ERROR_SUCCESS:
233                     printf("GATT Query result: OK\n");
234                     break;
235                 default:
236                     printf("GATT Query result: 0x%02x\n", gatt_event_query_complete_get_att_status(packet));
237                     break;
238             }
239             break;
240         default:
241             break;
242     }
243 }
244 
245 /* @section HCI packet handler
246  *
247  * @text The SM packet handler receives Security Manager Events required for pairing.
248  * It also receives events generated during Identity Resolving
249  * see Listing SMPacketHandler.
250  */
251 
252 /* LISTING_START(SMPacketHandler): Scanning and receiving advertisements */
253 
254 static void sm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
255     UNUSED(channel);
256     UNUSED(size);
257 
258     if (packet_type != HCI_EVENT_PACKET) return;
259 
260     bd_addr_t addr;
261     bd_addr_type_t addr_type;
262 
263     switch (hci_event_packet_get_type(packet)) {
264         case SM_EVENT_JUST_WORKS_REQUEST:
265             printf("Just works requested\n");
266             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
267             break;
268         case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
269             printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
270             sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
271             break;
272         case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
273             printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
274             break;
275         case SM_EVENT_PASSKEY_INPUT_NUMBER:
276             printf("Passkey Input requested\n");
277             printf("Sending fixed passkey %"PRIu32"\n", (uint32_t) FIXED_PASSKEY);
278             sm_passkey_input(sm_event_passkey_input_number_get_handle(packet), FIXED_PASSKEY);
279             break;
280         case SM_EVENT_PAIRING_STARTED:
281             printf("Pairing started\n");
282             break;
283         case SM_EVENT_PAIRING_COMPLETE:
284             switch (sm_event_pairing_complete_get_status(packet)){
285                 case ERROR_CODE_SUCCESS:
286                     printf("Pairing complete, success\n");
287                     break;
288                 case ERROR_CODE_CONNECTION_TIMEOUT:
289                     printf("Pairing failed, timeout\n");
290                     break;
291                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
292                     printf("Pairing failed, disconnected\n");
293                     break;
294                 case ERROR_CODE_AUTHENTICATION_FAILURE:
295                     printf("Pairing failed, authentication failure with reason = %u\n", sm_event_pairing_complete_get_reason(packet));
296                     break;
297                 default:
298                     break;
299             }
300             break;
301         case SM_EVENT_REENCRYPTION_STARTED:
302             sm_event_reencryption_complete_get_address(packet, addr);
303             printf("Bonding information exists for addr type %u, identity addr %s -> start re-encryption\n",
304                    sm_event_reencryption_started_get_addr_type(packet), bd_addr_to_str(addr));
305             break;
306         case SM_EVENT_REENCRYPTION_COMPLETE:
307             switch (sm_event_reencryption_complete_get_status(packet)){
308                 case ERROR_CODE_SUCCESS:
309                     printf("Re-encryption complete, success\n");
310                     break;
311                 case ERROR_CODE_CONNECTION_TIMEOUT:
312                     printf("Re-encryption failed, timeout\n");
313                     break;
314                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
315                     printf("Re-encryption failed, disconnected\n");
316                     break;
317                 case ERROR_CODE_PIN_OR_KEY_MISSING:
318                     printf("Re-encryption failed, bonding information missing\n\n");
319                     printf("Assuming remote lost bonding information\n");
320                     printf("Deleting local bonding information and start new pairing...\n");
321                     sm_event_reencryption_complete_get_address(packet, addr);
322                     addr_type = sm_event_reencryption_started_get_addr_type(packet);
323                     gap_delete_bonding(addr_type, addr);
324                     sm_request_pairing(sm_event_reencryption_complete_get_handle(packet));
325                     break;
326                 default:
327                     break;
328             }
329             break;
330         default:
331             break;
332     }
333 }
334 /* LISTING_END */
335 
336 int btstack_main(void);
337 int btstack_main(void)
338 {
339     sm_pairing_central_setup();
340 
341     // turn on!
342     hci_power_control(HCI_POWER_ON);
343 
344     return 0;
345 }
346 
347 /* EXAMPLE_END */
348