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