1 /*
2  * Copyright (c) 2017 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <errno.h>
9 #include <zephyr/sys/util.h>
10 #include <zephyr/sys/byteorder.h>
11 #include <zephyr/sys/iterable_sections.h>
12 #include <zephyr/net/buf.h>
13 #include <zephyr/bluetooth/bluetooth.h>
14 #include <zephyr/bluetooth/conn.h>
15 #include <zephyr/bluetooth/mesh.h>
16 
17 #include "common/bt_str.h"
18 
19 #include "mesh.h"
20 #include "net.h"
21 #include "prov.h"
22 #include "crypto.h"
23 #include "beacon.h"
24 #include "cfg.h"
25 
26 #define LOG_LEVEL CONFIG_BT_MESH_BEACON_LOG_LEVEL
27 #include <zephyr/logging/log.h>
28 LOG_MODULE_REGISTER(bt_mesh_beacon);
29 
30 #define PROVISIONED_INTERVAL       K_SECONDS(10)
31 
32 #define BEACON_TYPE_UNPROVISIONED  0x00
33 #define BEACON_TYPE_SECURE         0x01
34 #define BEACON_TYPE_PRIVATE        0x02
35 
36 /* 3 transmissions, 20ms interval */
37 #define UNPROV_XMIT                BT_MESH_TRANSMIT(2, 20)
38 
39 /* 1 transmission, 20ms interval */
40 #define PROV_XMIT                  BT_MESH_TRANSMIT(0, 20)
41 
42 static struct k_work_delayable beacon_timer;
43 static struct bt_mesh_subnet *beacon_send_sub_curr;
44 
45 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
46 static struct {
47 	/**
48 	 * Identifier for the current Private beacon random-value.
49 	 * Each time we regenerate the random-value, we'll update this idx.
50 	 * Whenever it's time for a subnet to create a beacon, it'll compare
51 	 * the subnet's beacon idx to determine whether the random value has
52 	 * changed since the last beacon was sent. If this is the case, we'll
53 	 * regenerate the beacon based on the new random value.
54 	 */
55 	uint16_t idx;
56 	uint8_t val[13];
57 	uint64_t timestamp;
58 } priv_random;
59 #endif
60 
61 struct beacon_params {
62 	bool private;
63 	union {
64 		const uint8_t *net_id;
65 		struct {
66 			const uint8_t *data;
67 			const uint8_t *random;
68 		};
69 	};
70 	const uint8_t *auth;
71 	uint32_t iv_index;
72 	uint8_t flags;
73 
74 	bool new_key;
75 };
76 
77 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
78 static int private_beacon_create(struct bt_mesh_subnet *sub,
79 				 struct net_buf_simple *buf);
80 static int private_beacon_update(struct bt_mesh_subnet *sub);
81 #endif
82 
subnet_beacon_get_by_type(struct bt_mesh_subnet * sub,bool priv)83 static struct bt_mesh_beacon *subnet_beacon_get_by_type(struct bt_mesh_subnet *sub, bool priv)
84 {
85 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
86 	return priv ? &sub->priv_beacon : &sub->secure_beacon;
87 #else
88 	return &sub->secure_beacon;
89 #endif
90 }
91 
beacon_cache_match(struct bt_mesh_subnet * sub,void * data)92 static bool beacon_cache_match(struct bt_mesh_subnet *sub, void *data)
93 {
94 	struct beacon_params *params;
95 	struct bt_mesh_beacon *beacon;
96 
97 	params = data;
98 	beacon = subnet_beacon_get_by_type(sub, params->private);
99 
100 	return !memcmp(beacon->cache, params->auth, sizeof(beacon->cache));
101 }
102 
cache_add(const uint8_t auth[8],struct bt_mesh_beacon * beacon)103 static void cache_add(const uint8_t auth[8], struct bt_mesh_beacon *beacon)
104 {
105 	memcpy(beacon->cache, auth, sizeof(beacon->cache));
106 }
107 
bt_mesh_beacon_cache_clear(struct bt_mesh_subnet * sub)108 void bt_mesh_beacon_cache_clear(struct bt_mesh_subnet *sub)
109 {
110 	(void)memset(sub->secure_beacon.cache, 0, sizeof(sub->secure_beacon.cache));
111 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
112 	(void)memset(sub->priv_beacon.cache, 0, sizeof(sub->priv_beacon.cache));
113 #endif
114 }
115 
beacon_start(uint16_t duration,int err,void * user_data)116 static void beacon_start(uint16_t duration, int err, void *user_data)
117 {
118 	if (err) {
119 		LOG_ERR("Failed to send beacon: err %d", err);
120 		if (beacon_send_sub_curr) {
121 			k_work_reschedule(&beacon_timer, K_NO_WAIT);
122 		}
123 	}
124 }
125 
beacon_complete(int err,void * user_data)126 static void beacon_complete(int err, void *user_data)
127 {
128 	struct bt_mesh_beacon *beacon = user_data;
129 
130 	LOG_DBG("err %d", err);
131 	beacon->sent = k_uptime_get_32();
132 
133 	if (beacon_send_sub_curr) {
134 		k_work_reschedule(&beacon_timer, K_MSEC(20));
135 	}
136 }
137 
secure_beacon_create(struct bt_mesh_subnet * sub,struct net_buf_simple * buf)138 static int secure_beacon_create(struct bt_mesh_subnet *sub,
139 				struct net_buf_simple *buf)
140 {
141 	uint8_t flags = bt_mesh_net_flags(sub);
142 	struct bt_mesh_subnet_keys *keys;
143 
144 	net_buf_simple_add_u8(buf, BEACON_TYPE_SECURE);
145 
146 	keys = &sub->keys[SUBNET_KEY_TX_IDX(sub)];
147 
148 	net_buf_simple_add_u8(buf, flags);
149 
150 	/* Network ID */
151 	net_buf_simple_add_mem(buf, keys->net_id, 8);
152 
153 	/* IV Index */
154 	net_buf_simple_add_be32(buf, bt_mesh.iv_index);
155 
156 	net_buf_simple_add_mem(buf, sub->secure_beacon.auth, 8);
157 
158 	LOG_DBG("net_idx 0x%04x flags 0x%02x NetID %s", sub->net_idx, flags,
159 		bt_hex(keys->net_id, 8));
160 	LOG_DBG("IV Index 0x%08x Auth %s", bt_mesh.iv_index, bt_hex(sub->secure_beacon.auth, 8));
161 
162 	return 0;
163 }
164 
165 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
private_random_update(void)166 static int private_random_update(void)
167 {
168 	uint8_t interval = bt_mesh_priv_beacon_update_interval_get();
169 	uint64_t uptime = k_uptime_get();
170 	int err;
171 
172 	/* The Private beacon random value should change every N seconds to maintain privacy.
173 	 * N = (10 * interval) seconds, or on every beacon creation, if the interval is 0.
174 	 */
175 	if (bt_mesh_priv_beacon_get() == BT_MESH_FEATURE_ENABLED &&
176 	    interval &&
177 	    uptime - priv_random.timestamp < (10 * interval * MSEC_PER_SEC) &&
178 	    priv_random.timestamp != 0) {
179 		/* Not time yet */
180 		return 0;
181 	}
182 
183 	err = bt_rand(priv_random.val, sizeof(priv_random.val));
184 	if (err) {
185 		return err;
186 	}
187 
188 	/* Update the index to indicate to all subnets that the private beacon must be regenerated.
189 	 * Each subnet maintains the random index their private beacon data was generated with.
190 	 */
191 	priv_random.idx++;
192 	priv_random.timestamp = uptime;
193 
194 	return 0;
195 }
196 
private_beacon_update(struct bt_mesh_subnet * sub)197 static int private_beacon_update(struct bt_mesh_subnet *sub)
198 {
199 	struct bt_mesh_subnet_keys *keys = &sub->keys[SUBNET_KEY_TX_IDX(sub)];
200 	uint8_t flags = bt_mesh_net_flags(sub);
201 	int err;
202 
203 	err = bt_mesh_beacon_encrypt(&keys->priv_beacon, flags, bt_mesh.iv_index,
204 				     priv_random.val, sub->priv_beacon_ctx.data,
205 				     sub->priv_beacon.auth);
206 	if (err) {
207 		LOG_ERR("Can't encrypt private beacon");
208 		return err;
209 	}
210 
211 	sub->priv_beacon_ctx.idx = priv_random.idx;
212 	return 0;
213 }
214 
private_beacon_create(struct bt_mesh_subnet * sub,struct net_buf_simple * buf)215 static int private_beacon_create(struct bt_mesh_subnet *sub,
216 				 struct net_buf_simple *buf)
217 {
218 	int err;
219 
220 	/* Refresh beacon data */
221 	err = private_random_update();
222 	if (err) {
223 		return err;
224 	}
225 
226 	if (sub->priv_beacon_ctx.idx != priv_random.idx) {
227 		err = private_beacon_update(sub);
228 		if (err) {
229 			return err;
230 		}
231 	}
232 
233 	net_buf_simple_add_u8(buf, BEACON_TYPE_PRIVATE);
234 	net_buf_simple_add_mem(buf, priv_random.val, 13);
235 	net_buf_simple_add_mem(buf, sub->priv_beacon_ctx.data, 5);
236 	net_buf_simple_add_mem(buf, sub->priv_beacon.auth, 8);
237 
238 	LOG_DBG("0x%03x", sub->net_idx);
239 	return 0;
240 }
241 #endif
242 
bt_mesh_beacon_create(struct bt_mesh_subnet * sub,struct net_buf_simple * buf,bool priv)243 int bt_mesh_beacon_create(struct bt_mesh_subnet *sub, struct net_buf_simple *buf, bool priv)
244 {
245 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
246 	if (priv) {
247 		return private_beacon_create(sub, buf);
248 	}
249 #endif
250 
251 	secure_beacon_create(sub, buf);
252 	return 0;
253 }
254 
255 /* If the interval has passed or is within 5 seconds from now send a beacon */
256 #define BEACON_THRESHOLD(beacon) \
257 	((10 * ((beacon)->last + 1)) * MSEC_PER_SEC - (5 * MSEC_PER_SEC))
258 
secure_beacon_is_running(void)259 static bool secure_beacon_is_running(void)
260 {
261 	return bt_mesh_beacon_enabled() ||
262 	       atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR);
263 }
264 
net_beacon_send(struct bt_mesh_subnet * sub,struct bt_mesh_beacon * beacon,int (* beacon_create)(struct bt_mesh_subnet * sub,struct net_buf_simple * buf))265 static int net_beacon_send(struct bt_mesh_subnet *sub, struct bt_mesh_beacon *beacon,
266 			    int (*beacon_create)(struct bt_mesh_subnet *sub,
267 						 struct net_buf_simple *buf))
268 {
269 	static const struct bt_mesh_send_cb send_cb = {
270 		.start = beacon_start,
271 		.end = beacon_complete,
272 	};
273 	uint32_t now = k_uptime_get_32();
274 	struct bt_mesh_adv *adv;
275 	uint32_t time_diff;
276 	uint32_t time_since_last_recv;
277 	int err;
278 
279 	LOG_DBG("");
280 
281 	time_diff = now - beacon->sent;
282 	time_since_last_recv = now - beacon->recv;
283 	if (time_diff < (600 * MSEC_PER_SEC) &&
284 		(time_diff < BEACON_THRESHOLD(beacon) ||
285 		 time_since_last_recv < (10 * MSEC_PER_SEC))) {
286 		return -ENOMSG;
287 	}
288 
289 	adv = bt_mesh_adv_create(BT_MESH_ADV_BEACON, BT_MESH_ADV_TAG_LOCAL,
290 				 PROV_XMIT, K_NO_WAIT);
291 	if (!adv) {
292 		LOG_ERR("Unable to allocate beacon adv");
293 		return -ENOMEM; /* Bail out */
294 	}
295 
296 	err = beacon_create(sub, &adv->b);
297 	if (!err) {
298 		bt_mesh_adv_send(adv, &send_cb, beacon);
299 	}
300 
301 	bt_mesh_adv_unref(adv);
302 
303 	return err;
304 }
305 
net_beacon_for_subnet_send(struct bt_mesh_subnet * sub)306 static int net_beacon_for_subnet_send(struct bt_mesh_subnet *sub)
307 {
308 	int err = -ENOMSG;
309 
310 	struct {
311 		struct bt_mesh_beacon *beacon;
312 		bool enabled;
313 		int (*create_fn)(struct bt_mesh_subnet *sub, struct net_buf_simple *buf);
314 	} beacons[] = {
315 		[0] = {
316 			.beacon = &sub->secure_beacon,
317 			.enabled = secure_beacon_is_running(),
318 			.create_fn = secure_beacon_create,
319 		},
320 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
321 		[1] = {
322 			.beacon = &sub->priv_beacon,
323 			.enabled = bt_mesh_priv_beacon_get() == BT_MESH_FEATURE_ENABLED,
324 			.create_fn = private_beacon_create,
325 		},
326 #endif
327 	};
328 
329 	for (int i = 0; i < ARRAY_SIZE(beacons); i++) {
330 		if (!beacons[i].enabled) {
331 			continue;
332 		}
333 
334 		err = net_beacon_send(sub, beacons[i].beacon, beacons[i].create_fn);
335 		if (err < 0) {
336 			/* Bail out */
337 			break;
338 		}
339 	}
340 
341 	return err;
342 }
343 
unprovisioned_beacon_send(void)344 static int unprovisioned_beacon_send(void)
345 {
346 	const struct bt_mesh_prov *prov;
347 	uint8_t uri_hash[16] = { 0 };
348 	struct bt_mesh_adv *adv;
349 	uint16_t oob_info;
350 
351 	LOG_DBG("");
352 
353 	adv = bt_mesh_adv_create(BT_MESH_ADV_BEACON, BT_MESH_ADV_TAG_LOCAL,
354 				 UNPROV_XMIT, K_NO_WAIT);
355 	if (!adv) {
356 		LOG_ERR("Unable to allocate beacon adv");
357 		return -ENOBUFS;
358 	}
359 
360 	prov = bt_mesh_prov_get();
361 
362 	net_buf_simple_add_u8(&adv->b, BEACON_TYPE_UNPROVISIONED);
363 	net_buf_simple_add_mem(&adv->b, prov->uuid, 16);
364 
365 	if (prov->uri && bt_mesh_s1_str(prov->uri, uri_hash) == 0) {
366 		oob_info = prov->oob_info | BT_MESH_PROV_OOB_URI;
367 	} else {
368 		oob_info = prov->oob_info;
369 	}
370 
371 	net_buf_simple_add_be16(&adv->b, oob_info);
372 	net_buf_simple_add_mem(&adv->b, uri_hash, 4);
373 
374 	bt_mesh_adv_send(adv, NULL, NULL);
375 	bt_mesh_adv_unref(adv);
376 
377 	if (prov->uri) {
378 		size_t len;
379 
380 		adv = bt_mesh_adv_create(BT_MESH_ADV_URI, BT_MESH_ADV_TAG_LOCAL,
381 					 UNPROV_XMIT, K_NO_WAIT);
382 		if (!adv) {
383 			LOG_ERR("Unable to allocate URI adv");
384 			return -ENOBUFS;
385 		}
386 
387 		len = strlen(prov->uri);
388 		if (net_buf_simple_tailroom(&adv->b) < len) {
389 			LOG_WRN("Too long URI to fit advertising data");
390 		} else {
391 			net_buf_simple_add_mem(&adv->b, prov->uri, len);
392 			bt_mesh_adv_send(adv, NULL, NULL);
393 		}
394 
395 		bt_mesh_adv_unref(adv);
396 	}
397 
398 	return 0;
399 }
400 
unprovisioned_beacon_recv(struct net_buf_simple * buf)401 static void unprovisioned_beacon_recv(struct net_buf_simple *buf)
402 {
403 	const struct bt_mesh_prov *prov;
404 	uint8_t *uuid;
405 	uint16_t oob_info;
406 	uint32_t uri_hash_val;
407 	uint32_t *uri_hash = NULL;
408 
409 	prov = bt_mesh_prov_get();
410 
411 	if (!prov->unprovisioned_beacon) {
412 		return;
413 	}
414 
415 	if (buf->len != 18 && buf->len != 22) {
416 		LOG_ERR("Invalid unprovisioned beacon length (%u)", buf->len);
417 		return;
418 	}
419 
420 	uuid = net_buf_simple_pull_mem(buf, 16);
421 	oob_info = net_buf_simple_pull_be16(buf);
422 
423 	if (buf->len == 4) {
424 		uri_hash_val = net_buf_simple_pull_be32(buf);
425 		uri_hash = &uri_hash_val;
426 	}
427 
428 	LOG_DBG("uuid %s", bt_hex(uuid, 16));
429 
430 	prov->unprovisioned_beacon(uuid,
431 				   (bt_mesh_prov_oob_info_t)oob_info,
432 				   uri_hash);
433 }
434 
sub_update_beacon_observation(struct bt_mesh_subnet * sub)435 static void sub_update_beacon_observation(struct bt_mesh_subnet *sub)
436 {
437 	sub->secure_beacon.last = sub->secure_beacon.cur;
438 	sub->secure_beacon.cur = 0U;
439 
440 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
441 	sub->priv_beacon.last = sub->priv_beacon.cur;
442 	sub->priv_beacon.cur = 0U;
443 #endif
444 }
445 
update_beacon_observation(void)446 static void update_beacon_observation(void)
447 {
448 	static bool first_half;
449 
450 	/* Observation period is 20 seconds, whereas the beacon timer
451 	 * runs every 10 seconds. We process what's happened during the
452 	 * window only after the second half.
453 	 */
454 	first_half = !first_half;
455 	if (first_half) {
456 		return;
457 	}
458 
459 	bt_mesh_subnet_foreach(sub_update_beacon_observation);
460 }
461 
net_beacon_is_running(void)462 static bool net_beacon_is_running(void)
463 {
464 	return secure_beacon_is_running() ||
465 	       (bt_mesh_priv_beacon_get() == BT_MESH_FEATURE_ENABLED);
466 }
467 
beacons_send_next(void)468 static bool beacons_send_next(void)
469 {
470 	int err;
471 	struct bt_mesh_subnet *sub_first = bt_mesh_subnet_next(NULL);
472 	struct bt_mesh_subnet *sub_next;
473 
474 	do {
475 		sub_next = bt_mesh_subnet_next(beacon_send_sub_curr);
476 		if (sub_next == sub_first && beacon_send_sub_curr != NULL) {
477 			beacon_send_sub_curr = NULL;
478 			return false;
479 		}
480 
481 		beacon_send_sub_curr = sub_next;
482 		err = net_beacon_for_subnet_send(beacon_send_sub_curr);
483 		if (err < 0 && (err != -ENOMSG)) {
484 			LOG_ERR("Failed to advertise subnet %d: err %d",
485 				beacon_send_sub_curr->net_idx, err);
486 		}
487 	} while (err);
488 
489 	return true;
490 }
491 
beacon_send(struct k_work * work)492 static void beacon_send(struct k_work *work)
493 {
494 	LOG_DBG("");
495 
496 	if (bt_mesh_is_provisioned()) {
497 		if (!net_beacon_is_running()) {
498 			return;
499 		}
500 
501 		if (!beacon_send_sub_curr) {
502 			update_beacon_observation();
503 		}
504 
505 		if (!beacons_send_next()) {
506 			k_work_schedule(&beacon_timer, PROVISIONED_INTERVAL);
507 		}
508 
509 		return;
510 	}
511 
512 	if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV)) {
513 		/* Don't send anything if we have an active provisioning link */
514 		if (!bt_mesh_prov_active()) {
515 			unprovisioned_beacon_send();
516 		}
517 
518 		k_work_schedule(&beacon_timer, K_SECONDS(CONFIG_BT_MESH_UNPROV_BEACON_INT));
519 	}
520 }
521 
auth_match(struct bt_mesh_subnet_keys * keys,const struct beacon_params * params)522 static bool auth_match(struct bt_mesh_subnet_keys *keys,
523 		       const struct beacon_params *params)
524 {
525 	uint8_t net_auth[8];
526 
527 	if (memcmp(params->net_id, keys->net_id, 8)) {
528 		return false;
529 	}
530 
531 	if (bt_mesh_beacon_auth(&keys->beacon, params->flags, keys->net_id, params->iv_index,
532 				net_auth)) {
533 		return false;
534 	}
535 
536 	if (memcmp(params->auth, net_auth, 8)) {
537 		LOG_WRN("Invalid auth value. Received auth: %s", bt_hex(params->auth, 8));
538 		LOG_WRN("Calculated auth: %s", bt_hex(net_auth, 8));
539 		return false;
540 	}
541 
542 	return true;
543 }
544 
secure_beacon_authenticate(struct bt_mesh_subnet * sub,void * cb_data)545 static bool secure_beacon_authenticate(struct bt_mesh_subnet *sub, void *cb_data)
546 {
547 	struct beacon_params *params = cb_data;
548 
549 	for (int i = 0; i < ARRAY_SIZE(sub->keys); i++) {
550 		if (sub->keys[i].valid && auth_match(&sub->keys[i], params)) {
551 			params->new_key = (i > 0);
552 #if defined(CONFIG_BT_TESTING)
553 			struct bt_mesh_snb beacon_info;
554 
555 			beacon_info.flags = params->flags;
556 			memcpy(&beacon_info.net_id, params->net_id, 8);
557 			beacon_info.iv_idx = params->iv_index;
558 			memcpy(&beacon_info.auth_val, params->auth, 8);
559 
560 			STRUCT_SECTION_FOREACH(bt_mesh_beacon_cb, cb) {
561 				if (cb->snb_received) {
562 					cb->snb_received(&beacon_info);
563 				}
564 			}
565 #endif
566 
567 			return true;
568 		}
569 	}
570 
571 	return false;
572 }
573 
priv_beacon_decrypt(struct bt_mesh_subnet * sub,void * cb_data)574 static bool priv_beacon_decrypt(struct bt_mesh_subnet *sub, void *cb_data)
575 {
576 	struct beacon_params *params = cb_data;
577 	uint8_t out[5];
578 	int err;
579 
580 	for (int i = 0; i < ARRAY_SIZE(sub->keys); i++) {
581 		if (!sub->keys[i].valid) {
582 			continue;
583 		}
584 
585 		err = bt_mesh_beacon_decrypt(&sub->keys[i].priv_beacon, params->random,
586 					     params->data, params->auth, out);
587 		if (!err) {
588 			params->new_key = (i > 0);
589 			params->flags = out[0];
590 			params->iv_index = sys_get_be32(&out[1]);
591 
592 #if defined(CONFIG_BT_TESTING)
593 			struct bt_mesh_prb beacon_info;
594 
595 			memcpy(beacon_info.random, params->random, 13);
596 			beacon_info.flags = params->flags;
597 			beacon_info.iv_idx = params->iv_index;
598 			memcpy(&beacon_info.auth_tag, params->auth, 8);
599 
600 			STRUCT_SECTION_FOREACH(bt_mesh_beacon_cb, cb) {
601 				if (cb->priv_received) {
602 					cb->priv_received(&beacon_info);
603 				}
604 			}
605 #endif
606 			return true;
607 		}
608 	}
609 
610 	return false;
611 }
612 
net_beacon_register(struct bt_mesh_beacon * beacon,bool priv)613 static void net_beacon_register(struct bt_mesh_beacon *beacon, bool priv)
614 {
615 	if (((priv && bt_mesh_priv_beacon_get() == BT_MESH_PRIV_GATT_PROXY_ENABLED) ||
616 	     bt_mesh_beacon_enabled()) && beacon->cur < 0xff) {
617 		beacon->cur++;
618 		beacon->recv = k_uptime_get_32();
619 	}
620 }
621 
net_beacon_recv(struct bt_mesh_subnet * sub,const struct beacon_params * params)622 static void net_beacon_recv(struct bt_mesh_subnet *sub,
623 			    const struct beacon_params *params)
624 {
625 	bt_mesh_kr_update(sub, BT_MESH_KEY_REFRESH(params->flags),
626 			  params->new_key);
627 
628 	/* If we have NetKey0 accept IV index initiation only from it */
629 	if (bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY) &&
630 	    sub->net_idx != BT_MESH_KEY_PRIMARY) {
631 		LOG_WRN("Ignoring secure beacon on non-primary subnet");
632 		return;
633 	}
634 
635 	LOG_DBG("net_idx 0x%04x flags %u iv_index 0x%08x, "
636 		"current iv_index 0x%08x",
637 		sub->net_idx, params->flags, params->iv_index, bt_mesh.iv_index);
638 
639 	if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_INITIATOR) &&
640 	    (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ==
641 	     BT_MESH_IV_UPDATE(params->flags))) {
642 		bt_mesh_beacon_ivu_initiator(false);
643 	}
644 
645 	bt_mesh_net_iv_update(params->iv_index,
646 			      BT_MESH_IV_UPDATE(params->flags));
647 }
648 
net_beacon_resolve(struct beacon_params * params,bool (* matcher)(struct bt_mesh_subnet * sub,void * cb_data))649 static void net_beacon_resolve(struct beacon_params *params,
650 			       bool (*matcher)(struct bt_mesh_subnet *sub,
651 					       void *cb_data))
652 {
653 	struct bt_mesh_subnet *sub;
654 	struct bt_mesh_beacon *beacon;
655 
656 	sub = bt_mesh_subnet_find(beacon_cache_match, (void *)params);
657 	if (sub) {
658 		beacon = subnet_beacon_get_by_type(sub, params->private);
659 
660 		/* We've seen this beacon before - just update the stats */
661 		net_beacon_register(beacon, params->private);
662 		return;
663 	}
664 
665 	sub = bt_mesh_subnet_find(matcher, params);
666 	if (!sub) {
667 		LOG_DBG("No subnet that matched beacon");
668 		return;
669 	}
670 
671 	if (sub->kr_phase == BT_MESH_KR_PHASE_2 && !params->new_key) {
672 		LOG_WRN("Ignoring Phase 2 KR Update secured using old key");
673 		return;
674 	}
675 
676 	beacon = subnet_beacon_get_by_type(sub, params->private);
677 
678 	cache_add(params->auth, beacon);
679 
680 	net_beacon_recv(sub, params);
681 	net_beacon_register(beacon, params->private);
682 }
683 
secure_beacon_recv(struct net_buf_simple * buf)684 static void secure_beacon_recv(struct net_buf_simple *buf)
685 {
686 	struct beacon_params params;
687 
688 	if (buf->len < 21) {
689 		LOG_ERR("Too short secure beacon (len %u)", buf->len);
690 		return;
691 	}
692 
693 	params.private = false;
694 	params.flags = net_buf_simple_pull_u8(buf);
695 	params.net_id = net_buf_simple_pull_mem(buf, 8);
696 	params.iv_index = net_buf_simple_pull_be32(buf);
697 	params.auth = buf->data;
698 
699 	net_beacon_resolve(&params, secure_beacon_authenticate);
700 }
701 
private_beacon_recv(struct net_buf_simple * buf)702 static void private_beacon_recv(struct net_buf_simple *buf)
703 {
704 	struct beacon_params params;
705 
706 	if (buf->len < 26) {
707 		LOG_ERR("Too short private beacon (len %u)", buf->len);
708 		return;
709 	}
710 
711 	params.private = true;
712 	params.random = net_buf_simple_pull_mem(buf, 13);
713 	params.data = net_buf_simple_pull_mem(buf, 5);
714 	params.auth = buf->data;
715 
716 	net_beacon_resolve(&params, priv_beacon_decrypt);
717 }
718 
bt_mesh_beacon_recv(struct net_buf_simple * buf)719 void bt_mesh_beacon_recv(struct net_buf_simple *buf)
720 {
721 	uint8_t type;
722 
723 	LOG_DBG("%u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
724 
725 	if (buf->len < 1) {
726 		LOG_ERR("Too short beacon");
727 		return;
728 	}
729 
730 	type = net_buf_simple_pull_u8(buf);
731 	switch (type) {
732 	case BEACON_TYPE_UNPROVISIONED:
733 		if (IS_ENABLED(CONFIG_BT_MESH_PB_ADV)) {
734 			unprovisioned_beacon_recv(buf);
735 		}
736 		break;
737 	case BEACON_TYPE_SECURE:
738 		secure_beacon_recv(buf);
739 		break;
740 	case BEACON_TYPE_PRIVATE:
741 		private_beacon_recv(buf);
742 		break;
743 	default:
744 		LOG_WRN("Unknown beacon type 0x%02x", type);
745 		break;
746 	}
747 }
748 
bt_mesh_beacon_update(struct bt_mesh_subnet * sub)749 void bt_mesh_beacon_update(struct bt_mesh_subnet *sub)
750 {
751 	uint8_t flags = bt_mesh_net_flags(sub);
752 	struct bt_mesh_subnet_keys *keys;
753 
754 	keys = &sub->keys[SUBNET_KEY_TX_IDX(sub)];
755 
756 	LOG_DBG("NetIndex 0x%03x Using %s key", sub->net_idx,
757 		SUBNET_KEY_TX_IDX(sub) ? "new" : "current");
758 	LOG_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index);
759 
760 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
761 	/* Invalidate private beacon to force regeneration: */
762 	sub->priv_beacon_ctx.idx = priv_random.idx - 1;
763 	priv_random.timestamp = 0;
764 #endif
765 
766 	bt_mesh_beacon_auth(&keys->beacon, flags, keys->net_id, bt_mesh.iv_index,
767 			    sub->secure_beacon.auth);
768 }
769 
subnet_evt(struct bt_mesh_subnet * sub,enum bt_mesh_key_evt evt)770 static void subnet_evt(struct bt_mesh_subnet *sub, enum bt_mesh_key_evt evt)
771 {
772 	if (evt != BT_MESH_KEY_DELETED) {
773 		bt_mesh_beacon_update(sub);
774 	}
775 }
776 
777 BT_MESH_SUBNET_CB_DEFINE(beacon) = {
778 	.evt_handler = subnet_evt,
779 };
780 
bt_mesh_beacon_init(void)781 void bt_mesh_beacon_init(void)
782 {
783 	k_work_init_delayable(&beacon_timer, beacon_send);
784 
785 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
786 	private_random_update();
787 #endif
788 }
789 
bt_mesh_beacon_ivu_initiator(bool enable)790 void bt_mesh_beacon_ivu_initiator(bool enable)
791 {
792 	atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_INITIATOR, enable);
793 
794 	/* Fire the beacon handler straight away if it's not already pending -
795 	 * in which case we'll fire according to the ongoing periodic sending.
796 	 * If beacons are disabled, the handler will exit early.
797 	 *
798 	 * An alternative solution would be to check whether beacons are enabled
799 	 * here, and cancel if not. As the cancel operation may fail, we would
800 	 * still have to implement an early exit mechanism, so we might as well
801 	 * just use this every time.
802 	 */
803 	beacon_send_sub_curr = NULL;
804 	k_work_schedule(&beacon_timer, K_NO_WAIT);
805 }
806 
subnet_beacon_enable(struct bt_mesh_subnet * sub)807 static void subnet_beacon_enable(struct bt_mesh_subnet *sub)
808 {
809 	sub->secure_beacon.last = 0U;
810 	sub->secure_beacon.cur = 0U;
811 
812 #if defined(CONFIG_BT_MESH_PRIV_BEACONS)
813 	sub->priv_beacon.last = 0U;
814 	sub->priv_beacon.cur = 0U;
815 #endif
816 
817 	bt_mesh_beacon_update(sub);
818 }
819 
bt_mesh_beacon_enable(void)820 void bt_mesh_beacon_enable(void)
821 {
822 	if (bt_mesh_is_provisioned()) {
823 		bt_mesh_subnet_foreach(subnet_beacon_enable);
824 	}
825 
826 	beacon_send_sub_curr = NULL;
827 	k_work_reschedule(&beacon_timer, K_NO_WAIT);
828 }
829 
bt_mesh_beacon_disable(void)830 void bt_mesh_beacon_disable(void)
831 {
832 	/* If this fails, we'll do an early exit in the work handler. */
833 	beacon_send_sub_curr = NULL;
834 	(void)k_work_cancel_delayable(&beacon_timer);
835 }
836