xref: /btstack/example/sm_pairing_peripheral.c (revision 8f19f013a14580c1f0d0c6803bf97784b9493d28)
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_peripheral.c"
39 
40 // *****************************************************************************
41 /* EXAMPLE_START(sm_pairing_peripheral): LE Peripheral - Test Pairing Methods
42  *
43  * @text Depending on the Authentication requiremens and IO Capabilities,
44  * the pairing process uses different short and long term key generation method.
45  * This example helps explore the different options incl. LE Secure Connections.
46  */
47  // *****************************************************************************
48 
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <inttypes.h>
54 
55 #include "sm_pairing_peripheral.h"
56 #include "btstack.h"
57 
58 /* @section Main Application Setup
59  *
60  * @text Listing MainConfiguration shows main application code.
61  * It initializes L2CAP, the Security Manager and configures the ATT Server with the pre-compiled
62  * ATT Database generated from $sm_pairing_peripheral.gatt$. Finally, it configures the advertisements
63  * and boots the Bluetooth stack.
64  * In this example, the Advertisement contains the Flags attribute, the device name, and a 16-bit (test) service 0x1111
65  * The flag 0x06 indicates: LE General Discoverable Mode and BR/EDR not supported.
66  * Various examples for IO Capabilites and Authentication Requirements are given below.
67  */
68 
69 /* LISTING_START(MainConfiguration): Setup stack to advertise */
70 static btstack_packet_callback_registration_t sm_event_callback_registration;
71 static btstack_packet_callback_registration_t hci_event_callback_registration;
72 
73 static void sm_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
74 static void hci_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
75 
76 const uint8_t adv_data[] = {
77     // Flags general discoverable, BR/EDR not supported
78     0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
79     // Name
80     0x0b, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'S', 'M', ' ', 'P', 'a', 'i', 'r', 'i', 'n', 'g',
81     // Incomplete List of 16-bit Service Class UUIDs -- 1111 - only valid for testing!
82     0x03, BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x11, 0x11,
83 };
84 const uint8_t adv_data_len = sizeof(adv_data);
85 
sm_peripheral_setup(void)86 static void sm_peripheral_setup(void){
87 
88     l2cap_init();
89 
90     // setup SM: Display only
91     sm_init();
92 
93     // setup ATT server
94     att_server_init(profile_data, NULL, NULL);
95 
96     // setup GATT Client
97     gatt_client_init();
98 
99     // setup advertisements
100     uint16_t adv_int_min = 0x0030;
101     uint16_t adv_int_max = 0x0030;
102     uint8_t adv_type = 0;
103     bd_addr_t null_addr;
104     memset(null_addr, 0, 6);
105     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
106     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
107     gap_advertisements_enable(1);
108 
109     // register handler
110     hci_event_callback_registration.callback = &hci_packet_handler;
111     hci_add_event_handler(&hci_event_callback_registration);
112 
113     sm_event_callback_registration.callback = &sm_packet_handler;
114     sm_add_event_handler(&sm_event_callback_registration);
115 
116     // Configuration
117 
118     // Enable mandatory authentication for GATT Client
119     // - if un-encrypted connections are not supported, e.g. when connecting to own device, this enforces authentication
120     // gatt_client_set_required_security_level(LEVEL_2);
121 
122     /**
123      * Choose ONE of the following configurations
124      * Bonding is disabled to allow for repeated testing. It can be enabled by or'ing
125      * SM_AUTHREQ_BONDING to the authentication requirements like this:
126      * sm_set_authentication_requirements( X | SM_AUTHREQ_BONDING)
127      */
128 
129     // LE Legacy Pairing, Just Works
130     // sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
131     // sm_set_authentication_requirements(0);
132 
133     // LE Legacy Pairing, Passkey entry initiator enter, responder (us) displays
134     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
135     // sm_set_authentication_requirements(SM_AUTHREQ_MITM_PROTECTION);
136     // sm_use_fixed_passkey_in_display_role(123456);
137 
138 #ifdef ENABLE_LE_SECURE_CONNECTIONS
139 
140     // enable LE Secure Connections Only mode - disables Legacy pairing
141     // sm_set_secure_connections_only_mode(true);
142 
143     // LE Secure Connections, Just Works
144     // sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
145     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION);
146 
147     // LE Secure Connections, Numeric Comparison
148     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_YES_NO);
149     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
150 
151     // LE Secure Pairing, Passkey entry initiator enter, responder (us) displays
152     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
153     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
154     // sm_use_fixed_passkey_in_display_role(123456);
155 
156     // LE Secure Pairing, Passkey entry initiator displays, responder (us) enter
157     // sm_set_io_capabilities(IO_CAPABILITY_KEYBOARD_ONLY);
158     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
159 #endif
160 }
161 
162 /* LISTING_END */
163 
164 /*
165  * @section Security Manager Packet Handler
166  *
167  * @text The packet handler is used to handle Security Manager events
168  */
169 
170 /* LISTING_START(packetHandler): Security Manager Packet Handler */
sm_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)171 static void sm_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
172     UNUSED(channel);
173     UNUSED(size);
174 
175     if (packet_type != HCI_EVENT_PACKET) return;
176 
177     hci_con_handle_t con_handle;
178     bd_addr_t addr;
179     bd_addr_type_t addr_type;
180     uint8_t status;
181 
182     switch (hci_event_packet_get_type(packet)) {
183         case HCI_EVENT_META_GAP:
184             switch (hci_event_gap_meta_get_subevent_code(packet)) {
185                 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
186                     printf("Connection complete\n");
187                     con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
188                     UNUSED(con_handle);
189 
190                     // for testing, choose one of the following actions
191 
192                     // manually start pairing
193                     // sm_request_pairing(con_handle);
194 
195                     // gatt client request to authenticated characteristic in sm_pairing_central (short cut, uses hard-coded value handle)
196                     // gatt_client_read_value_of_characteristic_using_value_handle(&packet_handler, con_handle, 0x0009);
197 
198                     // general gatt client request to trigger mandatory authentication
199                     // gatt_client_discover_primary_services(&packet_handler, con_handle);
200                     break;
201                 default:
202                     break;
203             }
204             break;
205         case SM_EVENT_JUST_WORKS_REQUEST:
206             printf("Just Works requested\n");
207             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
208             break;
209         case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
210             printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
211             sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
212             break;
213         case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
214             printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
215             break;
216         case SM_EVENT_IDENTITY_CREATED:
217             sm_event_identity_created_get_identity_address(packet, addr);
218             printf("Identity created: type %u address %s\n", sm_event_identity_created_get_identity_addr_type(packet), bd_addr_to_str(addr));
219             break;
220         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
221             sm_event_identity_resolving_succeeded_get_identity_address(packet, addr);
222             printf("Identity resolved: type %u address %s\n", sm_event_identity_resolving_succeeded_get_identity_addr_type(packet), bd_addr_to_str(addr));
223             break;
224         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
225             sm_event_identity_created_get_address(packet, addr);
226             printf("Identity resolving failed\n");
227             break;
228         case SM_EVENT_PAIRING_STARTED:
229             printf("Pairing started\n");
230             break;
231         case SM_EVENT_PAIRING_COMPLETE:
232             switch (sm_event_pairing_complete_get_status(packet)){
233                 case ERROR_CODE_SUCCESS:
234                     printf("Pairing complete, success\n");
235                     break;
236                 case ERROR_CODE_CONNECTION_TIMEOUT:
237                     printf("Pairing failed, timeout\n");
238                     break;
239                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
240                     printf("Pairing failed, disconnected\n");
241                     break;
242                 case ERROR_CODE_AUTHENTICATION_FAILURE:
243                     printf("Pairing failed, authentication failure with reason = %u\n", sm_event_pairing_complete_get_reason(packet));
244                     break;
245                 default:
246                     break;
247             }
248             break;
249         case SM_EVENT_REENCRYPTION_STARTED:
250             sm_event_reencryption_complete_get_address(packet, addr);
251             printf("Bonding information exists for addr type %u, identity addr %s -> re-encryption started\n",
252                    sm_event_reencryption_started_get_addr_type(packet), bd_addr_to_str(addr));
253             break;
254         case SM_EVENT_REENCRYPTION_COMPLETE:
255             switch (sm_event_reencryption_complete_get_status(packet)){
256                 case ERROR_CODE_SUCCESS:
257                     printf("Re-encryption complete, success\n");
258                     break;
259                 case ERROR_CODE_CONNECTION_TIMEOUT:
260                     printf("Re-encryption failed, timeout\n");
261                     break;
262                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
263                     printf("Re-encryption failed, disconnected\n");
264                     break;
265                 case ERROR_CODE_PIN_OR_KEY_MISSING:
266                     printf("Re-encryption failed, bonding information missing\n\n");
267                     printf("Assuming remote lost bonding information\n");
268                     printf("Deleting local bonding information to allow for new pairing...\n");
269                     sm_event_reencryption_complete_get_address(packet, addr);
270                     addr_type = sm_event_reencryption_started_get_addr_type(packet);
271                     gap_delete_bonding(addr_type, addr);
272                     break;
273                 default:
274                     break;
275             }
276             break;
277         case GATT_EVENT_QUERY_COMPLETE:
278             status = gatt_event_query_complete_get_att_status(packet);
279             switch (status){
280                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION:
281                     printf("GATT Query failed, Insufficient Encryption\n");
282                     break;
283                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
284                     printf("GATT Query failed, Insufficient Authentication\n");
285                     break;
286                 case ATT_ERROR_BONDING_INFORMATION_MISSING:
287                     printf("GATT Query failed, Bonding Information Missing\n");
288                     break;
289                 case ATT_ERROR_SUCCESS:
290                     printf("GATT Query successful\n");
291                     break;
292                 default:
293                     printf("GATT Query failed, status 0x%02x\n", gatt_event_query_complete_get_att_status(packet));
294                     break;
295             }
296             break;
297         default:
298             break;
299     }
300 }
301 
302 /*
303  * @section HCI Packet Handler
304  *
305  * @text The packet handler is used to handle new connections, can trigger Security Request
306  */
hci_packet_handler(uint8_t packet_type,uint16_t channel,uint8_t * packet,uint16_t size)307 static void hci_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
308     UNUSED(channel);
309     UNUSED(size);
310 
311     if (packet_type != HCI_EVENT_PACKET) return;
312 
313     hci_con_handle_t con_handle;
314 
315     switch (hci_event_packet_get_type(packet)) {
316         case HCI_EVENT_META_GAP:
317             switch (hci_event_gap_meta_get_subevent_code(packet)) {
318                 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
319                     printf("Connection complete\n");
320                     con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
321                     UNUSED(con_handle);
322 
323                     // for testing, choose one of the following actions
324 
325                     // manually start pairing
326                     // sm_request_pairing(con_handle);
327 
328                     // gatt client request to authenticated characteristic in sm_pairing_central (short cut, uses hard-coded value handle)
329                     // gatt_client_read_value_of_characteristic_using_value_handle(&packet_handler, con_handle, 0x0009);
330 
331                     // general gatt client request to trigger mandatory authentication
332                     // gatt_client_discover_primary_services(&packet_handler, con_handle);
333                     break;
334                 default:
335                     break;
336             }
337             break;
338         default:
339             break;
340     }
341 }
342 
343 /* LISTING_END */
344 
345 int btstack_main(void);
btstack_main(void)346 int btstack_main(void)
347 {
348     sm_peripheral_setup();
349 
350     // turn on!
351 	hci_power_control(HCI_POWER_ON);
352 
353     return 0;
354 }
355 /* EXAMPLE_END */
356