xref: /btstack/example/sm_pairing_peripheral.c (revision ced70f9bfeafe291ec597a3a9cc862e39e0da3ce)
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 
72 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
73 
74 const uint8_t adv_data[] = {
75     // Flags general discoverable, BR/EDR not supported
76     0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
77     // Name
78     0x0b, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME, 'S', 'M', ' ', 'P', 'a', 'i', 'r', 'i', 'n', 'g',
79     // Incomplete List of 16-bit Service Class UUIDs -- 1111 - only valid for testing!
80     0x03, BLUETOOTH_DATA_TYPE_INCOMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, 0x11, 0x11,
81 };
82 const uint8_t adv_data_len = sizeof(adv_data);
83 
84 static void sm_peripheral_setup(void){
85 
86     l2cap_init();
87 
88     // setup SM: Display only
89     sm_init();
90 
91     // setup ATT server
92     att_server_init(profile_data, NULL, NULL);
93 
94     // setup GATT Client
95     gatt_client_init();
96 
97     // setup advertisements
98     uint16_t adv_int_min = 0x0030;
99     uint16_t adv_int_max = 0x0030;
100     uint8_t adv_type = 0;
101     bd_addr_t null_addr;
102     memset(null_addr, 0, 6);
103     gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
104     gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
105     gap_advertisements_enable(1);
106 
107     // register for SM events
108     sm_event_callback_registration.callback = &packet_handler;
109     sm_add_event_handler(&sm_event_callback_registration);
110 
111     // register for ATT
112     att_server_register_packet_handler(packet_handler);
113 
114 
115     // Configuration
116 
117     // Enable mandatory authentication for GATT Client
118     // - if un-encrypted connections are not supported, e.g. when connecting to own device, this enforces authentication
119     // gatt_client_set_required_security_level(LEVEL_2);
120 
121     /**
122      * Choose ONE of the following configurations
123      * Bonding is disabled to allow for repeated testing. It can be enabled by or'ing
124      * SM_AUTHREQ_BONDING to the authentication requirements like this:
125      * sm_set_authentication_requirements( X | SM_AUTHREQ_BONDING)
126      */
127 
128     // LE Legacy Pairing, Just Works
129     // sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
130     // sm_set_authentication_requirements(0);
131 
132     // LE Legacy Pairing, Passkey entry initiator enter, responder (us) displays
133     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
134     // sm_set_authentication_requirements(SM_AUTHREQ_MITM_PROTECTION);
135     // sm_use_fixed_passkey_in_display_role(123456);
136 
137 #ifdef ENABLE_LE_SECURE_CONNECTIONS
138 
139     // enable LE Secure Connections Only mode - disables Legacy pairing
140     // sm_set_secure_connections_only_mode(true);
141 
142     // LE Secure Connections, Just Works
143     // sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
144     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION);
145 
146     // LE Secure Connections, Numeric Comparison
147     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_YES_NO);
148     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
149 
150     // LE Secure Pairing, Passkey entry initiator enter, responder (us) displays
151     // sm_set_io_capabilities(IO_CAPABILITY_DISPLAY_ONLY);
152     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
153     // sm_use_fixed_passkey_in_display_role(123456);
154 
155     // LE Secure Pairing, Passkey entry initiator displays, responder (us) enter
156     // sm_set_io_capabilities(IO_CAPABILITY_KEYBOARD_ONLY);
157     // sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION|SM_AUTHREQ_MITM_PROTECTION);
158 #endif
159 }
160 
161 /* LISTING_END */
162 
163 /*
164  * @section Packet Handler
165  *
166  * @text The packet handler is used to:
167  *        - report connect/disconnect
168  *        - handle Security Manager events
169  */
170 
171 /* LISTING_START(packetHandler): Packet Handler */
172 static void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
173     UNUSED(channel);
174     UNUSED(size);
175 
176     if (packet_type != HCI_EVENT_PACKET) return;
177 
178     hci_con_handle_t con_handle;
179     bd_addr_t addr;
180     bd_addr_type_t addr_type;
181     uint8_t status;
182 
183     switch (hci_event_packet_get_type(packet)) {
184         case HCI_EVENT_META_GAP:
185             switch (hci_event_gap_meta_get_subevent_code(packet)) {
186                 case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
187                     printf("Connection complete\n");
188                     con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
189                     UNUSED(con_handle);
190 
191                     // for testing, choose one of the following actions
192 
193                     // manually start pairing
194                     // sm_request_pairing(con_handle);
195 
196                     // gatt client request to authenticated characteristic in sm_pairing_central (short cut, uses hard-coded value handle)
197                     // gatt_client_read_value_of_characteristic_using_value_handle(&packet_handler, con_handle, 0x0009);
198 
199                     // general gatt client request to trigger mandatory authentication
200                     // gatt_client_discover_primary_services(&packet_handler, con_handle);
201                     break;
202                 default:
203                     break;
204             }
205             break;
206         case SM_EVENT_JUST_WORKS_REQUEST:
207             printf("Just Works requested\n");
208             sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
209             break;
210         case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
211             printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
212             sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
213             break;
214         case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
215             printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
216             break;
217         case SM_EVENT_IDENTITY_CREATED:
218             sm_event_identity_created_get_identity_address(packet, addr);
219             printf("Identity created: type %u address %s\n", sm_event_identity_created_get_identity_addr_type(packet), bd_addr_to_str(addr));
220             break;
221         case SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED:
222             sm_event_identity_resolving_succeeded_get_identity_address(packet, addr);
223             printf("Identity resolved: type %u address %s\n", sm_event_identity_resolving_succeeded_get_identity_addr_type(packet), bd_addr_to_str(addr));
224             break;
225         case SM_EVENT_IDENTITY_RESOLVING_FAILED:
226             sm_event_identity_created_get_address(packet, addr);
227             printf("Identity resolving failed\n");
228             break;
229         case SM_EVENT_PAIRING_STARTED:
230             printf("Pairing started\n");
231             break;
232         case SM_EVENT_PAIRING_COMPLETE:
233             switch (sm_event_pairing_complete_get_status(packet)){
234                 case ERROR_CODE_SUCCESS:
235                     printf("Pairing complete, success\n");
236                     break;
237                 case ERROR_CODE_CONNECTION_TIMEOUT:
238                     printf("Pairing failed, timeout\n");
239                     break;
240                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
241                     printf("Pairing failed, disconnected\n");
242                     break;
243                 case ERROR_CODE_AUTHENTICATION_FAILURE:
244                     printf("Pairing failed, authentication failure with reason = %u\n", sm_event_pairing_complete_get_reason(packet));
245                     break;
246                 default:
247                     break;
248             }
249             break;
250         case SM_EVENT_REENCRYPTION_STARTED:
251             sm_event_reencryption_complete_get_address(packet, addr);
252             printf("Bonding information exists for addr type %u, identity addr %s -> re-encryption started\n",
253                    sm_event_reencryption_started_get_addr_type(packet), bd_addr_to_str(addr));
254             break;
255         case SM_EVENT_REENCRYPTION_COMPLETE:
256             switch (sm_event_reencryption_complete_get_status(packet)){
257                 case ERROR_CODE_SUCCESS:
258                     printf("Re-encryption complete, success\n");
259                     break;
260                 case ERROR_CODE_CONNECTION_TIMEOUT:
261                     printf("Re-encryption failed, timeout\n");
262                     break;
263                 case ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION:
264                     printf("Re-encryption failed, disconnected\n");
265                     break;
266                 case ERROR_CODE_PIN_OR_KEY_MISSING:
267                     printf("Re-encryption failed, bonding information missing\n\n");
268                     printf("Assuming remote lost bonding information\n");
269                     printf("Deleting local bonding information to allow for new pairing...\n");
270                     sm_event_reencryption_complete_get_address(packet, addr);
271                     addr_type = sm_event_reencryption_started_get_addr_type(packet);
272                     gap_delete_bonding(addr_type, addr);
273                     break;
274                 default:
275                     break;
276             }
277             break;
278         case GATT_EVENT_QUERY_COMPLETE:
279             status = gatt_event_query_complete_get_att_status(packet);
280             switch (status){
281                 case ATT_ERROR_INSUFFICIENT_ENCRYPTION:
282                     printf("GATT Query failed, Insufficient Encryption\n");
283                     break;
284                 case ATT_ERROR_INSUFFICIENT_AUTHENTICATION:
285                     printf("GATT Query failed, Insufficient Authentication\n");
286                     break;
287                 case ATT_ERROR_BONDING_INFORMATION_MISSING:
288                     printf("GATT Query failed, Bonding Information Missing\n");
289                     break;
290                 case ATT_ERROR_SUCCESS:
291                     printf("GATT Query successful\n");
292                     break;
293                 default:
294                     printf("GATT Query failed, status 0x%02x\n", gatt_event_query_complete_get_att_status(packet));
295                     break;
296             }
297             break;
298         default:
299             break;
300     }
301 }
302 /* LISTING_END */
303 
304 int btstack_main(void);
305 int btstack_main(void)
306 {
307     sm_peripheral_setup();
308 
309     // turn on!
310 	hci_power_control(HCI_POWER_ON);
311 
312     return 0;
313 }
314 /* EXAMPLE_END */
315