xref: /btstack/test/security_manager_sc/sm_test.c (revision a64cbea79fa5fb9daa58e135a19c6cce10f3e642)
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 void __gcov_dump(void);
68 void __gcov_reset(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 hci_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 = hci_subevent_le_connection_complete_get_connection_handle(packet);
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 					if (hci_get_state() != HCI_STATE_WORKING) break;
308 					connection_handle = hci_event_disconnection_complete_get_connection_handle(packet);
309 					printf("DISCONNECTED: Connection handle 0x%04x\n", connection_handle);
310 					break;
311 				default:
312 					break;
313 			}
314 	}
315 	fflush(stdout);
316 }
317 
318 static void sm_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
319 	UNUSED(channel);
320 	UNUSED(size);
321 	switch (packet_type) {
322 		case HCI_EVENT_PACKET:
323 			switch (packet[0]) {
324 				case SM_EVENT_JUST_WORKS_REQUEST:
325 					printf("JUST_WORKS_REQUEST\n");
326 					break;
327 				case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
328 					printf("NUMERIC_COMPARISON_REQUEST\n");
329 					break;
330 				case SM_EVENT_PASSKEY_INPUT_NUMBER:
331 					// display number
332 					printf("PASSKEY_INPUT_NUMBER\n");
333 					ui_passkey = 0;
334 					ui_digits_for_passkey = 6;
335 					sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_ENTRY_STARTED);
336 					break;
337 				case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
338 					// display number
339 					printf("PASSKEY_DISPLAY_NUMBER: %06u\n", little_endian_read_32(packet, 11));
340 					break;
341 				case SM_EVENT_PASSKEY_DISPLAY_CANCEL:
342 					break;
343 				case SM_EVENT_AUTHORIZATION_REQUEST:
344 					break;
345 				case SM_EVENT_PAIRING_COMPLETE:
346 					printf("\nPAIRING_COMPLETE: %u,%u\n", sm_event_pairing_complete_get_status(packet), sm_event_pairing_complete_get_reason(packet));
347 					if (sm_event_pairing_complete_get_status(packet)) break;
348 					if (we_are_central){
349 						printf("Search for LE Counter service.\n");
350 						state = TC_W4_SERVICE_RESULT;
351 						gatt_client_discover_primary_services_by_uuid128(handle_gatt_client_event, connection_handle, le_counter_service_uuid);
352 					}
353 					break;
354 				default:
355 					break;
356 			}
357 	}
358 	fflush(stdout);
359 }
360 
361 
362 static void att_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
363 	UNUSED(channel);
364 	UNUSED(size);
365 	switch (packet_type) {
366 		case HCI_EVENT_PACKET:
367 			switch (packet[0]) {
368 				case ATT_EVENT_CAN_SEND_NOW:
369 					att_server_notify(connection_handle, ATT_CHARACTERISTIC_0000FF11_0000_1000_8000_00805F9B34FB_01_VALUE_HANDLE, (uint8_t *) "Pairing Success!", 16);
370 					break;
371 				default:
372 					break;
373 			}
374 	}
375 	fflush(stdout);
376 }
377 
378 static void stdin_process(char c){
379 	log_info("stdin: %c (%02x)", c, c);
380     // passkey input
381     if (ui_digits_for_passkey && c >= '0' && c <= '9'){
382         printf("%c", c);
383         fflush(stdout);
384         ui_passkey = ui_passkey * 10 + c - '0';
385         ui_digits_for_passkey--;
386         sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
387         if (ui_digits_for_passkey == 0){
388             printf("\n");
389             fflush(stdout);
390             sm_keypress_notification(connection_handle, SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED);
391             sm_passkey_input(connection_handle, ui_passkey);
392          }
393         return;
394     }
395 
396     if (ui_oob_confirm){
397         if (c == ' ') return;
398         ui_oob_nibble = (ui_oob_nibble << 4) | nibble_for_char(c);
399         if ((ui_oob_pos & 1) == 1){
400             sm_oob_peer_confirm[ui_oob_pos >> 1] = ui_oob_nibble;
401             ui_oob_nibble = 0;
402         }
403         ui_oob_pos++;
404         if (ui_oob_pos == 32){
405             ui_oob_confirm = 0;
406             printf("PEER_OOB_CONFIRM: ");
407             printf_hexdump(sm_oob_peer_confirm, 16);
408             fflush(stdout);
409         }
410         return;
411     }
412 
413     if (ui_oob_random){
414         if (c == ' ') return;
415         ui_oob_nibble = (ui_oob_nibble << 4) | nibble_for_char(c);
416         if ((ui_oob_pos & 1) == 1){
417             sm_oob_peer_random[ui_oob_pos >> 1] = ui_oob_nibble;
418             ui_oob_nibble = 0;
419         }
420         ui_oob_pos++;
421         if (ui_oob_pos == 32){
422             ui_oob_random = 0;
423             printf("PEER_OOB_RANDOM: ");
424             printf_hexdump(sm_oob_peer_random, 16);
425             fflush(stdout);
426         }
427         return;
428     }
429 
430 
431     switch (c){
432         case 'a': // accept just works
433             printf("accepting just works\n");
434             sm_just_works_confirm(connection_handle);
435             break;
436         case 'c':
437             printf("CENTRAL: connect to %s\n", bd_addr_to_str(peer_address));
438             gap_connect(peer_address, BD_ADDR_TYPE_LE_PUBLIC);
439             break;
440         case 'd':
441             printf("decline bonding\n");
442             sm_bonding_decline(connection_handle);
443             break;
444         case 'o':
445             printf("receive oob confirm value\n");
446             ui_oob_confirm = 1;
447             ui_oob_pos = 0;
448             break;
449         case 'r':
450             printf("receive oob random value\n");
451             ui_oob_random = 1;
452             ui_oob_pos = 0;
453             break;
454         case 'p':
455             printf("REQUEST_PAIRING\n");
456             sm_request_pairing(connection_handle);
457             break;
458         case 'x':
459 #ifdef COVERAGE
460 			log_info("Flush gcov");
461             __gcov_dump();
462             __gcov_reset();
463 #endif
464 			printf("EXIT\n");
465             exit(0);
466             break;
467         default:
468             break;
469     }
470     fflush(stdout);
471     return;
472 }
473 
474 int btstack_main(int argc, const char * argv[]);
475 int btstack_main(int argc, const char * argv[]){
476 
477     int arg = 1;
478 
479     while (arg < argc) {
480         if(!strcmp(argv[arg], "-a") || !strcmp(argv[arg], "--address")){
481             arg++;
482             we_are_central = sscanf_bd_addr(argv[arg], peer_address);
483             arg++;
484         }
485         if(!strcmp(argv[arg], "-i") || !strcmp(argv[arg], "--iocap")){
486             arg++;
487             sm_io_capabilities = (io_capability_t) atoi(argv[arg++]);
488         }
489         if(!strcmp(argv[arg], "-r") || !strcmp(argv[arg], "--authreq")){
490             arg++;
491             sm_auth_req = atoi(argv[arg++]);
492         }
493         if(!strcmp(argv[arg], "-f") || !strcmp(argv[arg], "--failure")){
494             arg++;
495             sm_failure = atoi(argv[arg++]);
496         }
497         if(!strcmp(argv[arg], "-o") || !strcmp(argv[arg], "--oob")){
498             arg++;
499             sm_have_oob_data = atoi(argv[arg++]);
500         }
501     }
502 
503     // parse command line flags
504 
505     printf("Security Manager Tester starting up...\n");
506     log_info("IO_CAPABILITIES: %u", (int) sm_io_capabilities);
507     log_info("AUTH_REQ: %u", sm_auth_req);
508     log_info("HAVE_OOB: %u", sm_have_oob_data);
509     log_info("FAILURE: %u", sm_failure);
510     if (we_are_central){
511         log_info("ROLE: CENTRAL");
512     } else {
513         log_info("ROLE: PERIPHERAL");
514 
515         // setup advertisements
516         uint16_t adv_int_min = 0x0030;
517         uint16_t adv_int_max = 0x0030;
518         uint8_t adv_type = 0;
519         bd_addr_t null_addr;
520         memset(null_addr, 0, 6);
521         gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
522         gap_advertisements_set_data(adv_data_len, (uint8_t*) adv_data);
523         gap_advertisements_enable(1);
524     }
525 
526     // inform about BTstack state
527     hci_event_callback_registration.callback = &hci_packet_handler;
528     hci_add_event_handler(&hci_event_callback_registration);
529 
530     // set up l2cap_le
531     l2cap_init();
532 
533     // setup le device db
534     le_device_db_init();
535 
536     //
537     gatt_client_init();
538 
539     // setup SM io capabilities & auth req
540     sm_init();
541     sm_set_io_capabilities(sm_io_capabilities);
542     sm_set_authentication_requirements(sm_auth_req);
543     sm_register_oob_data_callback(get_oob_data_callback);
544     sm_register_sc_oob_data_callback(get_sc_oob_data_callback);
545 
546     if (sm_failure < SM_REASON_NUMERIC_COMPARISON_FAILED && sm_failure != SM_REASON_PASSKEY_ENTRY_FAILED){
547         sm_test_set_pairing_failure(sm_failure);
548     }
549 
550     sm_event_callback_registration.callback = &sm_packet_handler;
551     sm_add_event_handler(&sm_event_callback_registration);
552 
553     // setup ATT server
554     att_server_init(profile_data, att_read_callback, att_write_callback);
555     att_server_register_packet_handler(&att_packet_handler);
556 
557     btstack_stdin_setup(stdin_process);
558 
559     // set one-shot timer
560     heartbeat.process = &heartbeat_handler;
561     btstack_run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS);
562     btstack_run_loop_add_timer(&heartbeat);
563 
564     // turn on!
565     hci_power_control(HCI_POWER_ON);
566 
567     return 0;
568 }
569 
570 /* EXAMPLE_END */
571