xref: /btstack/src/mesh/beacon.c (revision 7cdc89a533ca236b2c2564b759993b788bae89d3)
1 /*
2  * Copyright (C) 2017 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 #define BTSTACK_FILE__ "beacon.c"
39 
40 #include "mesh/beacon.h"
41 
42 #include <string.h>
43 
44 #include "ble/core.h"
45 #include "bluetooth.h"
46 #include "bluetooth_data_types.h"
47 #include "btstack_debug.h"
48 #include "btstack_event.h"
49 #include "btstack_run_loop.h"
50 #include "btstack_util.h"
51 #include "gap.h"
52 
53 #include "mesh/adv_bearer.h"
54 #include "mesh/gatt_bearer.h"
55 #include "mesh/mesh_foundation.h"
56 #include "mesh/mesh_iv_index_seq_number.h"
57 #include "mesh/mesh_keys.h"
58 
59 #define BEACON_TYPE_UNPROVISIONED_DEVICE 0
60 #define BEACON_TYPE_SECURE_NETWORK 1
61 
62 #define UNPROVISIONED_BEACON_INTERVAL_MS 5000
63 #define UNPROVISIONED_BEACON_LEN      23
64 
65 #define SECURE_NETWORK_BEACON_INTERVAL_MIN_MS  10000
66 #define SECURE_NETWORK_BEACON_INTERVAL_MAX_MS 600000
67 #define SECURE_NETWORK_BEACON_LEN                 22
68 
69 // prototypes
70 static void mesh_secure_network_beacon_run(btstack_timer_source_t * ts);
71 
72 // bearers
73 #ifdef ENABLE_MESH_GATT_BEARER
74 static hci_con_handle_t gatt_bearer_con_handle;
75 #endif
76 
77 // beacon
78 static uint8_t mesh_beacon_data[29];
79 static uint8_t mesh_beacon_len;
80 static btstack_timer_source_t   beacon_timer;
81 static int                      beacon_timer_active;
82 
83 // unprovisioned device beacon
84 #ifdef ENABLE_MESH_ADV_BEARER
85 static const uint8_t * beacon_device_uuid;
86 static       uint16_t  beacon_oob_information;
87 static       uint32_t  beacon_uri_hash;
88 static int             beacon_send_device_beacon;
89 #endif
90 
91 static btstack_packet_handler_t unprovisioned_device_beacon_handler;
92 
93 // secure network beacon
94 static btstack_crypto_aes128_cmac_t        mesh_secure_network_beacon_cmac_request;
95 static uint8_t                             mesh_secure_network_beacon_auth_value[16];
96 static btstack_packet_handler_t            mesh_secure_network_beacon_handler;
97 static int                                 mesh_secure_network_beacon_active;
98 #ifdef ENABLE_MESH_ADV_BEARER
99 static uint8_t                             mesh_secure_network_beacon_validate_buffer[SECURE_NETWORK_BEACON_LEN];
100 #endif
101 
102 #ifdef ENABLE_MESH_ADV_BEARER
103 static void beacon_timer_handler(btstack_timer_source_t * ts){
104     // restart timer
105     btstack_run_loop_set_timer(ts, UNPROVISIONED_BEACON_INTERVAL_MS);
106     btstack_run_loop_add_timer(ts);
107     beacon_timer_active = 1;
108 
109     // setup beacon
110     mesh_beacon_len = UNPROVISIONED_BEACON_LEN;
111     mesh_beacon_data[0] = BEACON_TYPE_UNPROVISIONED_DEVICE;
112     (void)memcpy(&mesh_beacon_data[1], beacon_device_uuid, 16);
113     big_endian_store_16(mesh_beacon_data, 17, beacon_oob_information);
114     big_endian_store_32(mesh_beacon_data, 19, beacon_uri_hash);
115 
116     // request to send
117     beacon_send_device_beacon = 1;
118     adv_bearer_request_can_send_now_for_beacon();
119 }
120 #endif
121 
122 static void mesh_secure_network_beacon_auth_value_calculated(void * arg){
123     mesh_subnet_t * mesh_subnet = (mesh_subnet_t *) arg;
124 
125     (void)memcpy(&mesh_beacon_data[14],
126                  mesh_secure_network_beacon_auth_value, 8);
127     mesh_beacon_len = SECURE_NETWORK_BEACON_LEN;
128 
129     printf("Secure Network Beacon\n");
130     printf("- ");
131     printf_hexdump(mesh_beacon_data, mesh_beacon_len);
132 
133     mesh_secure_network_beacon_active = 0;
134     mesh_subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_AUTH_VALUE;
135 
136     mesh_secure_network_beacon_run(NULL);
137 }
138 
139 static uint8_t mesh_secure_network_beacon_get_flags(mesh_subnet_t * mesh_subnet){
140     uint8_t mesh_flags = 0;
141     if (mesh_subnet->key_refresh != MESH_KEY_REFRESH_NOT_ACTIVE){
142         mesh_flags |= 1;
143     }
144     if (mesh_iv_update_active()){
145         mesh_flags |= 2;
146     }
147 
148     return mesh_flags;
149 }
150 
151 static void mesh_secure_network_beacon_setup(mesh_subnet_t * mesh_subnet){
152     mesh_beacon_data[0] = BEACON_TYPE_SECURE_NETWORK;
153     mesh_beacon_data[1] = mesh_secure_network_beacon_get_flags(mesh_subnet);
154     // TODO: pick correct key based on key refresh phase
155 
156     (void)memcpy(&mesh_beacon_data[2], mesh_subnet->old_key->network_id, 8);
157     big_endian_store_32(mesh_beacon_data, 10, mesh_get_iv_index());
158     mesh_network_key_t * network_key = mesh_subnet_get_outgoing_network_key(mesh_subnet);
159     btstack_crypto_aes128_cmac_message(&mesh_secure_network_beacon_cmac_request, network_key->beacon_key, 13,
160         &mesh_beacon_data[1], mesh_secure_network_beacon_auth_value, &mesh_secure_network_beacon_auth_value_calculated, mesh_subnet);
161 }
162 
163 static void mesh_secure_network_beacon_update_interval(mesh_subnet_t * subnet){
164     uint32_t min_observation_period_ms = 2 * subnet->beacon_interval_ms;
165     uint32_t actual_observation_period = btstack_time_delta(btstack_run_loop_get_time_ms(), subnet->beacon_observation_start_ms);
166 
167     // The Observation Period in seconds should typically be double the typical Beacon Interval.
168     if (actual_observation_period < min_observation_period_ms) return;
169 
170     // Expected Number of Beacons (1 beacon per 10 seconds)
171     uint16_t expected_number_of_beacons = actual_observation_period / SECURE_NETWORK_BEACON_INTERVAL_MIN_MS;
172 
173     // Beacon Interval = Observation Period * (Observed Number of Beacons + 1) / Expected Number of Beacons
174     uint32_t new_beacon_interval  =  actual_observation_period * (subnet->beacon_observation_counter + 1) / expected_number_of_beacons;
175 
176     if (new_beacon_interval > SECURE_NETWORK_BEACON_INTERVAL_MAX_MS){
177         new_beacon_interval = SECURE_NETWORK_BEACON_INTERVAL_MAX_MS;
178     }
179     else if (new_beacon_interval < SECURE_NETWORK_BEACON_INTERVAL_MIN_MS){
180         new_beacon_interval = SECURE_NETWORK_BEACON_INTERVAL_MAX_MS;
181     }
182     subnet->beacon_interval_ms = new_beacon_interval;
183     log_info("New beacon interval %u seconds", (int) (subnet->beacon_interval_ms / 1000));
184 }
185 
186 static void mesh_secure_network_beacon_run(btstack_timer_source_t * ts){
187     UNUSED(ts);
188 
189     uint32_t next_timeout_ms = 0;
190 
191     // iterate over all networks
192     mesh_subnet_iterator_t it;
193     mesh_subnet_iterator_init(&it);
194     while (mesh_subnet_iterator_has_more(&it)){
195         mesh_subnet_t * subnet = mesh_subnet_iterator_get_next(&it);
196         switch (subnet->beacon_state){
197             case MESH_SECURE_NETWORK_BEACON_W4_INTERVAL:
198                 // update beacon interval
199                 mesh_secure_network_beacon_update_interval(subnet);
200 
201                 if (mesh_foundation_beacon_get() == 0){
202                     // beacon off, continue observing
203                     if (next_timeout_ms == 0 || next_timeout_ms > subnet->beacon_interval_ms){
204                         next_timeout_ms = subnet->beacon_interval_ms;
205                     }
206                     break;
207                 }
208 
209                 // send new beacon
210                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_W2_AUTH_VALUE;
211 
212                 /* fall through */
213 
214             case MESH_SECURE_NETWORK_BEACON_W2_AUTH_VALUE:
215                 if (mesh_secure_network_beacon_active){
216                     // just try again in 10 ms
217                     next_timeout_ms = 10;
218                     break;
219                 }
220                 subnet->beacon_state  = MESH_SECURE_NETWORK_BEACON_W4_AUTH_VALUE;
221                 mesh_secure_network_beacon_active = 1;
222                 mesh_secure_network_beacon_setup(subnet);
223                 break;
224 
225             case MESH_SECURE_NETWORK_BEACON_AUTH_VALUE:
226 
227 #ifdef ENABLE_MESH_ADV_BEARER
228                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_W2_SEND_ADV;
229                 adv_bearer_request_can_send_now_for_beacon();
230                 break;
231 #endif
232                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_ADV_SENT;
233 
234                 /* fall through */
235 
236             case MESH_SECURE_NETWORK_BEACON_ADV_SENT:
237 
238 #ifdef ENABLE_MESH_GATT_BEARER
239                 if (gatt_bearer_con_handle != HCI_CON_HANDLE_INVALID && mesh_foundation_gatt_proxy_get() != 0){
240                     subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_W2_SEND_GATT;
241                     gatt_bearer_request_can_send_now_for_beacon();
242                     break;
243                 }
244 #endif
245                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_GATT_SENT;
246 
247                 /* fall through */
248 
249             case MESH_SECURE_NETWORK_BEACON_GATT_SENT:
250                 // now, start listening for beacons
251                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_W4_INTERVAL;
252                 // and request timeout
253                 if (next_timeout_ms == 0 || next_timeout_ms > subnet->beacon_interval_ms){
254                     next_timeout_ms = subnet->beacon_interval_ms;
255                 }
256                 break;
257 
258             default:
259                 break;
260         }
261     }
262 
263     if (beacon_timer_active){
264         btstack_run_loop_remove_timer(&beacon_timer);
265         beacon_timer_active = 0;
266     }
267 
268     // setup next run
269     if (next_timeout_ms == 0) return;
270 
271     btstack_run_loop_set_timer(&beacon_timer, next_timeout_ms);
272     btstack_run_loop_set_timer_handler(&beacon_timer, mesh_secure_network_beacon_run);
273     btstack_run_loop_add_timer(&beacon_timer);
274     beacon_timer_active = 1;
275 }
276 
277 #ifdef ENABLE_MESH_ADV_BEARER
278 static void beacon_handle_secure_beacon_auth_value_calculated(void * arg){
279     UNUSED(arg);
280 
281     // pass on, if auth value checks out
282     if (memcmp(&mesh_secure_network_beacon_validate_buffer[14], mesh_secure_network_beacon_auth_value, 8) == 0) {
283         if (mesh_secure_network_beacon_handler){
284             (*mesh_secure_network_beacon_handler)(MESH_BEACON_PACKET, 0, mesh_secure_network_beacon_validate_buffer, SECURE_NETWORK_BEACON_LEN);
285         }
286     }
287 
288     // done
289     mesh_secure_network_beacon_active = 0;
290     mesh_secure_network_beacon_run(NULL);
291 }
292 
293 static void beacon_handle_secure_beacon(uint8_t * packet, uint16_t size){
294     if (size != SECURE_NETWORK_BEACON_LEN) return;
295 
296     // lookup subnet and netkey by network id
297     uint8_t * beacon_network_id = &packet[2];
298     mesh_subnet_iterator_t it;
299     mesh_subnet_iterator_init(&it);
300     mesh_subnet_t * subnet = NULL;
301     mesh_network_key_t * network_key = NULL;
302     while (mesh_subnet_iterator_has_more(&it)){
303         mesh_subnet_t * item = mesh_subnet_iterator_get_next(&it);
304         if (memcmp(item->old_key->network_id, beacon_network_id, 8) == 0 ) {
305             subnet = item;
306             network_key = item->old_key;
307         }
308         if (item->new_key != NULL && memcmp(item->new_key->network_id, beacon_network_id, 8) == 0 ) {
309             subnet = item;
310             network_key = item->new_key;
311         }
312         break;
313     }
314     if (subnet == NULL) return;
315 
316     // count beacon
317     subnet->beacon_observation_counter++;
318 
319     // check if new flags are set
320     uint8_t current_flags = mesh_secure_network_beacon_get_flags(subnet);
321     uint8_t new_flags = packet[1] & (~current_flags);
322 
323     if (new_flags == 0) return;
324 
325     // validate beacon - if crytpo ready
326     if (mesh_secure_network_beacon_active) return;
327 
328     mesh_secure_network_beacon_active = 1;
329     (void)memcpy(mesh_secure_network_beacon_validate_buffer, &packet[0],
330                  SECURE_NETWORK_BEACON_LEN);
331 
332     btstack_crypto_aes128_cmac_message(&mesh_secure_network_beacon_cmac_request, network_key->beacon_key, 13,
333         &mesh_secure_network_beacon_validate_buffer[1], mesh_secure_network_beacon_auth_value, &beacon_handle_secure_beacon_auth_value_calculated, subnet);
334 }
335 
336 static void beacon_handle_beacon_packet(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
337     log_info("beacon type %u", packet[0]);
338     switch (packet[0]){
339         case BEACON_TYPE_UNPROVISIONED_DEVICE:
340             if (unprovisioned_device_beacon_handler){
341                 (*unprovisioned_device_beacon_handler)(packet_type, channel, packet, size);
342             }
343             break;
344         case BEACON_TYPE_SECURE_NETWORK:
345             beacon_handle_secure_beacon(packet, size);
346             break;
347         default:
348             break;
349     }
350 }
351 
352 static void beacon_adv_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
353     mesh_subnet_iterator_t it;
354     switch (packet_type){
355         case HCI_EVENT_PACKET:
356             switch(packet[0]){
357                 case HCI_EVENT_MESH_META:
358                     switch(packet[2]){
359                         case MESH_SUBEVENT_CAN_SEND_NOW:
360                             if (beacon_send_device_beacon){
361                                 beacon_send_device_beacon = 0;
362                                 adv_bearer_send_beacon(mesh_beacon_data, mesh_beacon_len);
363                                 break;
364                             }
365                             // secure beacon state machine
366                             mesh_subnet_iterator_init(&it);
367                             while (mesh_subnet_iterator_has_more(&it)){
368                                 mesh_subnet_t * subnet = mesh_subnet_iterator_get_next(&it);
369                                 switch (subnet->beacon_state){
370                                     case MESH_SECURE_NETWORK_BEACON_W2_SEND_ADV:
371                                         adv_bearer_send_beacon(mesh_beacon_data, mesh_beacon_len);
372                                         subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_ADV_SENT;
373                                         mesh_secure_network_beacon_run(NULL);
374                                         break;
375                                     default:
376                                         break;
377                                 }
378                             }
379                             break;
380                         default:
381                             break;
382                     }
383                     break;
384                 default:
385                     break;
386             }
387             break;
388         case MESH_BEACON_PACKET:
389             beacon_handle_beacon_packet(packet_type, channel, packet, size);
390             break;
391         default:
392             break;
393     }
394 }
395 #endif
396 
397 #ifdef ENABLE_MESH_GATT_BEARER
398 // handle MESH_SUBEVENT_PROXY_DISCONNECTED and MESH_SUBEVENT_CAN_SEND_NOW
399 static void beacon_gatt_handle_mesh_event(uint8_t mesh_subevent){
400     mesh_subnet_iterator_t it;
401     mesh_subnet_iterator_init(&it);
402     while (mesh_subnet_iterator_has_more(&it)){
403         mesh_subnet_t * subnet = mesh_subnet_iterator_get_next(&it);
404         switch (subnet->beacon_state){
405             case MESH_SECURE_NETWORK_BEACON_W2_SEND_GATT:
406                 // skip send on MESH_SUBEVENT_PROXY_DISCONNECTED
407                 if (mesh_subevent == MESH_SUBEVENT_CAN_SEND_NOW){
408                     gatt_bearer_send_beacon(mesh_beacon_data, mesh_beacon_len);
409                 }
410                 subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_GATT_SENT;
411                 mesh_secure_network_beacon_run(NULL);
412                 break;
413             default:
414                 break;
415         }
416     }
417 
418 }
419 
420 static void beacon_gatt_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
421     uint8_t mesh_subevent;
422     switch (packet_type){
423         case HCI_EVENT_PACKET:
424             switch(packet[0]){
425                 case HCI_EVENT_MESH_META:
426                     mesh_subevent = packet[2];
427                     switch(mesh_subevent){
428                         case MESH_SUBEVENT_PROXY_CONNECTED:
429                             gatt_bearer_con_handle = mesh_subevent_proxy_connected_get_con_handle(packet);
430                             break;
431                         case MESH_SUBEVENT_PROXY_DISCONNECTED:
432                             gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
433                             beacon_gatt_handle_mesh_event(mesh_subevent);
434                             break;
435                         case MESH_SUBEVENT_CAN_SEND_NOW:
436                             beacon_gatt_handle_mesh_event(mesh_subevent);
437                             break;
438                         default:
439                             break;
440                     }
441                     break;
442                 default:
443                     break;
444             }
445             break;
446         case MESH_BEACON_PACKET:
447             beacon_handle_beacon_packet(packet_type, channel, packet, size);
448             break;
449         default:
450             break;
451     }
452 }
453 #endif
454 
455 void beacon_init(void){
456 #ifdef ENABLE_MESH_ADV_BEARER
457     adv_bearer_register_for_beacon(&beacon_adv_packet_handler);
458 #endif
459 #ifdef ENABLE_MESH_GATT_BEARER
460     gatt_bearer_con_handle = HCI_CON_HANDLE_INVALID;
461     gatt_bearer_register_for_beacon(&beacon_gatt_packet_handler);
462 #endif
463 }
464 
465 /**
466  * Start Unprovisioned Device Beacon
467  */
468 void beacon_unprovisioned_device_start(const uint8_t * device_uuid, uint16_t oob_information){
469 #ifdef ENABLE_MESH_ADV_BEARER
470     beacon_oob_information = oob_information;
471     if (device_uuid){
472         beacon_device_uuid = device_uuid;
473         beacon_timer.process = &beacon_timer_handler;
474         beacon_timer_handler(&beacon_timer);
475     }
476 #endif
477 }
478 
479 /**
480  * Stop Unprovisioned Device Beacon
481  */
482 void beacon_unprovisioned_device_stop(void){
483 #ifdef ENABLE_MESH_ADV_BEARER
484     btstack_run_loop_remove_timer(&beacon_timer);
485     beacon_timer_active = 0;
486 #endif
487 }
488 
489 // secure network beacons
490 
491 void beacon_secure_network_start(mesh_subnet_t * mesh_subnet){
492     // default interval
493     mesh_subnet->beacon_interval_ms = SECURE_NETWORK_BEACON_INTERVAL_MIN_MS;
494     mesh_subnet->beacon_observation_start_ms = btstack_run_loop_get_time_ms();
495     mesh_subnet->beacon_observation_counter = 0;
496     if (mesh_foundation_beacon_get()){
497         mesh_subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_W2_AUTH_VALUE;
498     } else {
499         mesh_subnet->beacon_state = MESH_SECURE_NETWORK_BEACON_GATT_SENT;
500     }
501 
502     // start sending
503     mesh_secure_network_beacon_run(NULL);
504 }
505 
506 // register handler
507 void beacon_register_for_unprovisioned_device_beacons(btstack_packet_handler_t packet_handler){
508     unprovisioned_device_beacon_handler = packet_handler;
509 }
510 
511 void beacon_register_for_secure_network_beacons(btstack_packet_handler_t packet_handler){
512     mesh_secure_network_beacon_handler = packet_handler;
513 }
514