xref: /btstack/test/security_manager_sc/sm_test.c (revision f5228c62dfa305f00bfdabbb48dafdc0b8919667)
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 MATTHIAS
24  * RINGWALD 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 // *****************************************************************************
39 /* EXAMPLE_START(sm_test): Security Manager Test
40  *
41  */
42 // *****************************************************************************
43 
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #include "btstack_config.h"
51 
52 #include "ble/att_db.h"
53 #include "ble/att_server.h"
54 #include "ble/le_device_db.h"
55 #include "ble/sm.h"
56 #include "btstack_debug.h"
57 #include "btstack_event.h"
58 #include "btstack_memory.h"
59 #include "btstack_run_loop.h"
60 #include "gap.h"
61 #include "hci.h"
62 #include "hci_dump.h"
63 #include "l2cap.h"
64 #include "btstack_stdin.h"
65 
66 #ifdef COVERAGE
67 // guesswork:
68 void __gcov_flush(void);
69 #endif
70 
71 #define HEARTBEAT_PERIOD_MS 1000
72 
73 const uint8_t adv_data[] = {
74     // Flags general discoverable, BR/EDR not supported
75     0x02, 0x01, 0x06,
76     // Name
77     0x0d, 0x09, 'S', 'M', ' ', 'P', 'e', 'r', 'i', 'p', 'h', 'e', 'a', 'l'
78 };
79 const uint8_t adv_data_len = sizeof(adv_data);
80 
81 // test profile
82 #include "sm_test.h"
83 
84 static uint8_t sm_have_oob_data = 0;
85 static io_capability_t sm_io_capabilities = IO_CAPABILITY_DISPLAY_ONLY;
86 static uint8_t sm_auth_req = 0;
87 static uint8_t sm_failure = 0;
88 
89 // legacy pairing oob
90 static uint8_t sm_oob_tk_data[] = { 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00,  };
91 
92 // sc pairing oob
93 static uint8_t sm_oob_local_random[16];
94 static uint8_t sm_oob_peer_random[16];
95 static uint8_t sm_oob_peer_confirm[16];
96 
97 static int       we_are_central = 0;
98 static bd_addr_t peer_address;
99 
100 static int ui_passkey = 0;
101 static int ui_digits_for_passkey = 0;
102 static int ui_oob_confirm;
103 static int ui_oob_random;
104 static int ui_oob_pos;
105 static int ui_oob_nibble;
106 
107 static btstack_timer_source_t heartbeat;
108 static uint8_t counter = 0;
109 
110 static uint16_t connection_handle = 0;
111 
112 static btstack_packet_callback_registration_t hci_event_callback_registration;
113 static btstack_packet_callback_registration_t sm_event_callback_registration;
114 
115 typedef enum {
116     TC_IDLE,
117     TC_W4_SCAN_RESULT,
118     TC_W4_CONNECT,
119     TC_W4_SERVICE_RESULT,
120     TC_W4_CHARACTERISTIC_RESULT,
121     TC_W4_SUBSCRIBED,
122     TC_SUBSCRIBED
123 } gc_state_t;
124 
125 static gc_state_t state = TC_IDLE;
126 
127 static uint8_t le_counter_service_uuid[16]        = { 0x00, 0x00, 0xFF, 0x10, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
128 static uint8_t le_counter_characteristic_uuid[16] = { 0x00, 0x00, 0xFF, 0x11, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
129 
130 static gatt_client_service_t le_counter_service;
131 static gatt_client_characteristic_t le_counter_characteristic;
132 
133 static gatt_client_notification_t notification_listener;
134 static void  heartbeat_handler(struct btstack_timer_source *ts){
135     // restart timer
136     btstack_run_loop_set_timer(ts, HEARTBEAT_PERIOD_MS);
137     btstack_run_loop_add_timer(ts);
138     counter++;
139 }
140 
141 static int get_oob_data_callback(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data){
142     UNUSED(address_type);
143     (void)addr;
144     log_info("get_oob_data_callback for %s", bd_addr_to_str(addr));
145     if(!sm_have_oob_data) return 0;
146     memcpy(oob_data, sm_oob_tk_data, 16);
147     return 1;
148 }
149 
150 static 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){
151     UNUSED(address_type);
152     (void)addr;
153     log_info("get_sc_oob_data_callback for %s", bd_addr_to_str(addr));
154     if(!sm_have_oob_data) return 0;
155     memcpy(oob_sc_peer_confirm, sm_oob_peer_confirm, 16);
156     memcpy(oob_sc_peer_random,  sm_oob_peer_random, 16);
157     return 1;
158 }
159 
160 static void sc_local_oob_generated_callback(const uint8_t * confirm_value, const uint8_t * random_value){
161     printf("LOCAL_OOB_CONFIRM: ");
162     printf_hexdump(confirm_value, 16);
163     printf("LOCAL_OOB_RANDOM: ");
164     printf_hexdump(random_value, 16);
165     fflush(stdout);
166     memcpy(sm_oob_local_random, random_value, 16);
167 }
168 
169 // ATT Client Read Callback for Dynamic Data
170 // - if buffer == NULL, don't copy data, just return size of value
171 // - if buffer != NULL, copy data and return number bytes copied
172 // @param offset defines start of attribute value
173 static uint16_t att_read_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t offset, uint8_t * buffer, uint16_t buffer_size){
174     UNUSED(con_handle);
175     UNUSED(buffer);
176     printf("READ Callback, handle %04x, offset %u, buffer size %u\n", attribute_handle, offset, buffer_size);
177     switch (attribute_handle){
178         default:
179             break;
180     }
181     return 0;
182 }
183 
184 // write requests
185 static int att_write_callback(hci_con_handle_t con_handle, uint16_t attribute_handle, uint16_t transaction_mode, uint16_t offset, uint8_t *buffer, uint16_t buffer_size){
186     UNUSED(con_handle);
187     printf("WRITE Callback, handle %04x, mode %u, offset %u, data: ", attribute_handle, transaction_mode, offset);
188     printf_hexdump(buffer, buffer_size);
189 
190     switch (attribute_handle){
191         case ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_CLIENT_CONFIGURATION_HANDLE:
192             // short cut, send right away
193             att_server_request_can_send_now_event(con_handle);
194             break;
195         default:
196             break;
197     }
198     return 0;
199 }
200 
201 static void handle_gatt_client_event(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
202     UNUSED(packet_type);
203     UNUSED(channel);
204     UNUSED(size);
205 
206     int status;
207     char message[30];
208 
209     switch(state){
210         case TC_W4_SERVICE_RESULT:
211             switch(hci_event_packet_get_type(packet)){
212                 case GATT_EVENT_SERVICE_QUERY_RESULT:
213                     gatt_event_service_query_result_get_service(packet, &le_counter_service);
214                     break;
215                 case GATT_EVENT_QUERY_COMPLETE:
216                     if (packet[4] != 0){
217                         printf("SERVICE_QUERY_RESULT - Error status %x.\n", packet[4]);
218                         gap_disconnect(connection_handle);
219                         break;
220                     }
221                     state = TC_W4_CHARACTERISTIC_RESULT;
222                     printf("Search for counter characteristic.\n");
223                     gatt_client_discover_characteristics_for_service_by_uuid128(handle_gatt_client_event, connection_handle, &le_counter_service, le_counter_characteristic_uuid);
224                     break;
225                 default:
226                     break;
227             }
228             break;
229 
230         case TC_W4_CHARACTERISTIC_RESULT:
231             switch(hci_event_packet_get_type(packet)){
232                 case GATT_EVENT_CHARACTERISTIC_QUERY_RESULT:
233                     gatt_event_characteristic_query_result_get_characteristic(packet, &le_counter_characteristic);
234                     break;
235                 case GATT_EVENT_QUERY_COMPLETE:
236                     if (packet[4] != 0){
237                         printf("CHARACTERISTIC_QUERY_RESULT - Error status %x.\n", packet[4]);
238                         gap_disconnect(connection_handle);
239                         break;
240                     }
241                     state = TC_W4_SUBSCRIBED;
242                     printf("Configure counter for notify.\n");
243                     status = gatt_client_write_client_characteristic_configuration(handle_gatt_client_event, connection_handle, &le_counter_characteristic, GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION);
244                     break;
245                 default:
246                     break;
247             }
248             break;
249         case TC_W4_SUBSCRIBED:
250             switch(hci_event_packet_get_type(packet)){
251                 case GATT_EVENT_QUERY_COMPLETE:
252                     // register handler for notifications
253                     state = TC_SUBSCRIBED;
254                     printf("Subscribed, start listening\n");
255                     gatt_client_listen_for_characteristic_value_updates(&notification_listener, handle_gatt_client_event, connection_handle, &le_counter_characteristic);
256                     break;
257                 default:
258                     break;
259             }
260             break;
261 
262         case TC_SUBSCRIBED:
263             switch(hci_event_packet_get_type(packet)){
264                 case GATT_EVENT_NOTIFICATION:
265                     memset(message, 0, sizeof(message));
266                     memcpy(message, gatt_event_notification_get_value(packet), gatt_event_notification_get_value_length(packet));
267                     printf("COUNTER: %s\n", message);
268                     log_info("COUNTER: %s", message);
269                     break;
270                 default:
271                     break;
272             }
273 
274         default:
275             break;
276     }
277     fflush(stdout);
278 }
279 
280 static void app_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
281     UNUSED(channel);
282     UNUSED(size);
283     bd_addr_t local_addr;
284     switch (packet_type) {
285         case HCI_EVENT_PACKET:
286             switch (packet[0]) {
287                 case BTSTACK_EVENT_STATE:
288                     // bt stack activated, get started
289                     if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
290                         gap_local_bd_addr(local_addr);
291                         printf("BD_ADDR: %s\n", bd_addr_to_str(local_addr));
292                         // generate OOB data
293                         sm_generate_sc_oob_data(sc_local_oob_generated_callback);
294                     }
295                     break;
296                 case HCI_EVENT_LE_META:
297                     switch (hci_event_le_meta_get_subevent_code(packet)) {
298                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
299                             connection_handle = little_endian_read_16(packet, 4);
300                             printf("CONNECTED: Connection handle 0x%04x\n", connection_handle);
301                             break;
302                         default:
303                             break;
304                     }
305                     break;
306                 case HCI_EVENT_DISCONNECTION_COMPLETE:
307                     break;
308                 case SM_EVENT_JUST_WORKS_REQUEST:
309                     printf("JUST_WORKS_REQUEST\n");
310                     break;
311                 case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
312                     printf("NUMERIC_COMPARISON_REQUEST\n");
313                     break;
314                 case SM_EVENT_PASSKEY_INPUT_NUMBER:
315                     // display number
316                     printf("PASSKEY_INPUT_NUMBER\n");
317                     ui_passkey = 0;
318                     ui_digits_for_passkey = 6;
319                     sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_ENTRY_STARTED);
320                     break;
321                 case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
322                     // display number
323                     printf("PASSKEY_DISPLAY_NUMBER: %06u\n", little_endian_read_32(packet, 11));
324                     break;
325                 case SM_EVENT_PASSKEY_DISPLAY_CANCEL:
326                     break;
327                 case SM_EVENT_AUTHORIZATION_REQUEST:
328                     break;
329                 case SM_EVENT_PAIRING_COMPLETE:
330                     printf("\nPAIRING_COMPLETE: %u,%u\n", sm_event_pairing_complete_get_status(packet), sm_event_pairing_complete_get_reason(packet));
331                     if (sm_event_pairing_complete_get_status(packet)) break;
332                     if (we_are_central){
333                         printf("Search for LE Counter service.\n");
334                         state = TC_W4_SERVICE_RESULT;
335                         gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_counter_service_uuid);
336                     }
337                     break;
338                 case ATT_EVENT_HANDLE_VALUE_INDICATION_COMPLETE:
339                     break;
340                 case ATT_EVENT_CAN_SEND_NOW:
341                     att_server_notify(connection_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t *) "Pairing Success!", 16);
342                     break;
343                 default:
344                     break;
345             }
346     }
347     fflush(stdout);
348 }
349 
350 static void stdin_process(char c){
351 	log_info("stdin: %c (%02x)", c, c);
352     // passkey input
353     if (ui_digits_for_passkey && c >= '0' && c <= '9'){
354         printf("%c", c);
355         fflush(stdout);
356         ui_passkey = ui_passkey * 10 + c - '0';
357         ui_digits_for_passkey--;
358         sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
359         if (ui_digits_for_passkey == 0){
360             printf("\n");
361             fflush(stdout);
362             sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED);
363             sm_passkey_input(connection_handle, ui_passkey);
364          }
365         return;
366     }
367 
368     if (ui_oob_confirm){
369         if (c == ' ') return;
370         ui_oob_nibble = (ui_oob_nibble << 4) | nibble_for_char(c);
371         if ((ui_oob_pos & 1) == 1){
372             sm_oob_peer_confirm[ui_oob_pos >> 1] = ui_oob_nibble;
373             ui_oob_nibble = 0;
374         }
375         ui_oob_pos++;
376         if (ui_oob_pos == 32){
377             ui_oob_confirm = 0;
378             printf("PEER_OOB_CONFIRM: ");
379             printf_hexdump(sm_oob_peer_confirm, 16);
380             fflush(stdout);
381         }
382         return;
383     }
384 
385     if (ui_oob_random){
386         if (c == ' ') return;
387         ui_oob_nibble = (ui_oob_nibble << 4) | nibble_for_char(c);
388         if ((ui_oob_pos & 1) == 1){
389             sm_oob_peer_random[ui_oob_pos >> 1] = ui_oob_nibble;
390             ui_oob_nibble = 0;
391         }
392         ui_oob_pos++;
393         if (ui_oob_pos == 32){
394             ui_oob_random = 0;
395             printf("PEER_OOB_RANDOM: ");
396             printf_hexdump(sm_oob_peer_random, 16);
397             fflush(stdout);
398         }
399         return;
400     }
401 
402 
403     switch (c){
404         case 'a': // accept just works
405             printf("accepting just works\n");
406             sm_just_works_confirm(connection_handle);
407             break;
408         case 'c':
409             printf("CENTRAL: connect to %s\n", bd_addr_to_str(peer_address));
410             gap_connect(peer_address, BD_ADDR_TYPE_LE_PUBLIC);
411             break;
412         case 'd':
413             printf("decline bonding\n");
414             sm_bonding_decline(connection_handle);
415             break;
416         case 'o':
417             printf("receive oob confirm value\n");
418             ui_oob_confirm = 1;
419             ui_oob_pos = 0;
420             break;
421         case 'r':
422             printf("receive oob random value\n");
423             ui_oob_random = 1;
424             ui_oob_pos = 0;
425             break;
426         case 'p':
427             printf("REQUEST_PAIRING\n");
428             sm_request_pairing(connection_handle);
429             break;
430         case 'x':
431 #ifdef COVERAGE
432 			log_info("Flush gcov");
433 			__gcov_flush();
434 #endif
435 			printf("EXIT\n");
436             exit(0);
437             break;
438         default:
439             break;
440     }
441     fflush(stdout);
442     return;
443 }
444 
445 int btstack_main(int argc, const char * argv[]);
446 int btstack_main(int argc, const char * argv[]){
447 
448     int arg = 1;
449 
450     while (arg < argc) {
451         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
452             arg++;
453             we_are_central = sscanf_bd_addr(argv[arg], peer_address);
454             arg++;
455         }
456         if(!strcmp(argv[arg], "-i") || !strcmp(argv[arg], "--iocap")){
457             arg++;
458             sm_io_capabilities = (io_capability_t) atoi(argv[arg++]);
459         }
460         if(!strcmp(argv[arg], "-r") || !strcmp(argv[arg], "--authreq")){
461             arg++;
462             sm_auth_req = atoi(argv[arg++]);
463         }
464         if(!strcmp(argv[arg], "-f") || !strcmp(argv[arg], "--failure")){
465             arg++;
466             sm_failure = atoi(argv[arg++]);
467         }
468         if(!strcmp(argv[arg], "-o") || !strcmp(argv[arg], "--oob")){
469             arg++;
470             sm_have_oob_data = atoi(argv[arg++]);
471         }
472     }
473 
474     // parse command line flags
475 
476     printf("Security Manager Tester starting up...\n");
477     log_info("IO_CAPABILITIES: %u", (int) sm_io_capabilities);
478     log_info("AUTH_REQ: %u", sm_auth_req);
479     log_info("HAVE_OOB: %u", sm_have_oob_data);
480     log_info("FAILURE: %u", sm_failure);
481     if (we_are_central){
482         log_info("ROLE: CENTRAL");
483     } else {
484         log_info("ROLE: PERIPHERAL");
485 
486         // setup advertisements
487         uint16_t adv_int_min = 0x0030;
488         uint16_t adv_int_max = 0x0030;
489         uint8_t adv_type = 0;
490         bd_addr_t null_addr;
491         memset(null_addr, 0, 6);
492         gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
493         gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
494         gap_advertisements_enable(1);
495     }
496 
497     // inform about BTstack state
498     hci_event_callback_registration.callback = &app_packet_handler;
499     hci_add_event_handler(&hci_event_callback_registration);
500 
501     // set up l2cap_le
502     l2cap_init();
503 
504     // setup le device db
505     le_device_db_init();
506 
507     //
508     gatt_client_init();
509 
510     // setup SM io capabilities & auth req
511     sm_init();
512     sm_set_io_capabilities(sm_io_capabilities);
513     sm_set_authentication_requirements(sm_auth_req);
514     sm_register_oob_data_callback(get_oob_data_callback);
515     sm_register_sc_oob_data_callback(get_sc_oob_data_callback);
516 
517     if (sm_failure < SM_REASON_NUMERIC_COMPARISON_FAILED && sm_failure != SM_REASON_PASSKEY_ENTRY_FAILED){
518         sm_test_set_pairing_failure(sm_failure);
519     }
520 
521     sm_event_callback_registration.callback = &app_packet_handler;
522     sm_add_event_handler(&sm_event_callback_registration);
523 
524     // setup ATT server
525     att_server_init(profile_data, att_read_callback, att_write_callback);
526     att_server_register_packet_handler(app_packet_handler);
527 
528     btstack_stdin_setup(stdin_process);
529 
530     // set one-shot timer
531     heartbeat.process = &heartbeat_handler;
532     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
533     btstack_run_loop_add_timer(&heartbeat);
534 
535     // turn on!
536     hci_power_control(HCI_POWER_ON);
537 
538     return 0;
539 }
540 
541 /* EXAMPLE_END */
542