1 /*
2 * Copyright (c) 2017 Intel Corporation
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <stdbool.h>
11 #include <sys/atomic.h>
12 #include <sys/util.h>
13 #include <sys/byteorder.h>
14
15 #include <net/buf.h>
16 #include <bluetooth/bluetooth.h>
17 #include <bluetooth/conn.h>
18 #include <bluetooth/mesh.h>
19
20 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_NET)
21 #define LOG_MODULE_NAME bt_mesh_net
22 #include "common/log.h"
23
24 #include "crypto.h"
25 #include "adv.h"
26 #include "mesh.h"
27 #include "net.h"
28 #include "rpl.h"
29 #include "lpn.h"
30 #include "friend.h"
31 #include "proxy.h"
32 #include "transport.h"
33 #include "access.h"
34 #include "foundation.h"
35 #include "beacon.h"
36 #include "settings.h"
37 #include "host/ecc.h"
38 #include "prov.h"
39 #include "cfg.h"
40
41 #define LOOPBACK_MAX_PDU_LEN (BT_MESH_NET_HDR_LEN + 16)
42 #define LOOPBACK_USER_DATA_SIZE sizeof(struct bt_mesh_subnet *)
43 #define LOOPBACK_BUF_SUB(buf) (*(struct bt_mesh_subnet **)net_buf_user_data(buf))
44
45 /* Seq limit after IV Update is triggered */
46 #define IV_UPDATE_SEQ_LIMIT CONFIG_BT_MESH_IV_UPDATE_SEQ_LIMIT
47
48 #define IVI(pdu) ((pdu)[0] >> 7)
49 #define NID(pdu) ((pdu)[0] & 0x7f)
50 #define CTL(pdu) ((pdu)[1] >> 7)
51 #define TTL(pdu) ((pdu)[1] & 0x7f)
52 #define SEQ(pdu) (sys_get_be24(&pdu[2]))
53 #define SRC(pdu) (sys_get_be16(&(pdu)[5]))
54 #define DST(pdu) (sys_get_be16(&(pdu)[7]))
55
56 /** Define CONFIG_BT_MESH_SEQ_STORE_RATE even if settings are disabled to
57 * compile the code.
58 */
59 #ifndef CONFIG_BT_SETTINGS
60 #define CONFIG_BT_MESH_SEQ_STORE_RATE 1
61 #endif
62
63 /* Mesh network information for persistent storage. */
64 struct net_val {
65 uint16_t primary_addr;
66 uint8_t dev_key[16];
67 } __packed;
68
69 /* Sequence number information for persistent storage. */
70 struct seq_val {
71 uint8_t val[3];
72 } __packed;
73
74 /* IV Index & IV Update information for persistent storage. */
75 struct iv_val {
76 uint32_t iv_index;
77 uint8_t iv_update:1,
78 iv_duration:7;
79 } __packed;
80
81 static struct {
82 uint32_t src : 15, /* MSb of source is always 0 */
83 seq : 17;
84 } msg_cache[CONFIG_BT_MESH_MSG_CACHE_SIZE];
85 static uint16_t msg_cache_next;
86
87 /* Singleton network context (the implementation only supports one) */
88 struct bt_mesh_net bt_mesh = {
89 .local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue),
90 };
91
92 NET_BUF_POOL_DEFINE(loopback_buf_pool, CONFIG_BT_MESH_LOOPBACK_BUFS,
93 LOOPBACK_MAX_PDU_LEN, LOOPBACK_USER_DATA_SIZE, NULL);
94
95 static uint32_t dup_cache[CONFIG_BT_MESH_MSG_CACHE_SIZE];
96 static int dup_cache_next;
97
check_dup(struct net_buf_simple * data)98 static bool check_dup(struct net_buf_simple *data)
99 {
100 const uint8_t *tail = net_buf_simple_tail(data);
101 uint32_t val;
102 int i;
103
104 val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8);
105
106 for (i = 0; i < ARRAY_SIZE(dup_cache); i++) {
107 if (dup_cache[i] == val) {
108 return true;
109 }
110 }
111
112 dup_cache[dup_cache_next++] = val;
113 dup_cache_next %= ARRAY_SIZE(dup_cache);
114
115 return false;
116 }
117
msg_cache_match(struct net_buf_simple * pdu)118 static bool msg_cache_match(struct net_buf_simple *pdu)
119 {
120 uint16_t i;
121
122 for (i = 0U; i < ARRAY_SIZE(msg_cache); i++) {
123 if (msg_cache[i].src == SRC(pdu->data) &&
124 msg_cache[i].seq == (SEQ(pdu->data) & BIT_MASK(17))) {
125 return true;
126 }
127 }
128
129 return false;
130 }
131
msg_cache_add(struct bt_mesh_net_rx * rx)132 static void msg_cache_add(struct bt_mesh_net_rx *rx)
133 {
134 rx->msg_cache_idx = msg_cache_next++;
135 msg_cache[rx->msg_cache_idx].src = rx->ctx.addr;
136 msg_cache[rx->msg_cache_idx].seq = rx->seq;
137 msg_cache_next %= ARRAY_SIZE(msg_cache);
138 }
139
store_iv(bool only_duration)140 static void store_iv(bool only_duration)
141 {
142 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_IV_PENDING);
143
144 if (!only_duration) {
145 /* Always update Seq whenever IV changes */
146 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_SEQ_PENDING);
147 }
148 }
149
store_seq(void)150 static void store_seq(void)
151 {
152 if (CONFIG_BT_MESH_SEQ_STORE_RATE > 1 &&
153 (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE)) {
154 return;
155 }
156
157 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_SEQ_PENDING);
158 }
159
bt_mesh_net_create(uint16_t idx,uint8_t flags,const uint8_t key[16],uint32_t iv_index)160 int bt_mesh_net_create(uint16_t idx, uint8_t flags, const uint8_t key[16],
161 uint32_t iv_index)
162 {
163 int err;
164
165 BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index);
166
167 BT_DBG("NetKey %s", bt_hex(key, 16));
168
169 if (BT_MESH_KEY_REFRESH(flags)) {
170 err = bt_mesh_subnet_set(idx, BT_MESH_KR_PHASE_2, NULL, key);
171 } else {
172 err = bt_mesh_subnet_set(idx, BT_MESH_KR_NORMAL, key, NULL);
173 }
174
175 if (err) {
176 BT_ERR("Failed creating subnet");
177 return err;
178 }
179
180 (void)memset(msg_cache, 0, sizeof(msg_cache));
181 msg_cache_next = 0U;
182
183 bt_mesh.iv_index = iv_index;
184 atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS,
185 BT_MESH_IV_UPDATE(flags));
186
187 /* If IV Update is already in progress, set minimum required hours,
188 * since the 96-hour minimum requirement doesn't apply in this case straight
189 * after provisioning.
190 */
191 if (BT_MESH_IV_UPDATE(flags)) {
192 bt_mesh.ivu_duration = BT_MESH_IVU_MIN_HOURS;
193 }
194
195 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
196 BT_DBG("Storing network information persistently");
197 bt_mesh_subnet_store(idx);
198 store_iv(false);
199 }
200
201 return 0;
202 }
203
204 #if defined(CONFIG_BT_MESH_IV_UPDATE_TEST)
bt_mesh_iv_update_test(bool enable)205 void bt_mesh_iv_update_test(bool enable)
206 {
207 atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_TEST, enable);
208 /* Reset the duration variable - needed for some PTS tests */
209 bt_mesh.ivu_duration = 0U;
210 }
211
bt_mesh_iv_update(void)212 bool bt_mesh_iv_update(void)
213 {
214 if (!bt_mesh_is_provisioned()) {
215 BT_ERR("Not yet provisioned");
216 return false;
217 }
218
219 if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
220 bt_mesh_net_iv_update(bt_mesh.iv_index, false);
221 } else {
222 bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
223 }
224
225 return atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
226 }
227 #endif /* CONFIG_BT_MESH_IV_UPDATE_TEST */
228
bt_mesh_net_iv_update(uint32_t iv_index,bool iv_update)229 bool bt_mesh_net_iv_update(uint32_t iv_index, bool iv_update)
230 {
231 if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
232 /* We're currently in IV Update mode */
233
234 if (iv_index != bt_mesh.iv_index) {
235 BT_WARN("IV Index mismatch: 0x%08x != 0x%08x",
236 iv_index, bt_mesh.iv_index);
237 return false;
238 }
239
240 if (iv_update) {
241 /* Nothing to do */
242 BT_DBG("Already in IV Update in Progress state");
243 return false;
244 }
245 } else {
246 /* We're currently in Normal mode */
247
248 if (iv_index == bt_mesh.iv_index) {
249 BT_DBG("Same IV Index in normal mode");
250 return false;
251 }
252
253 if (iv_index < bt_mesh.iv_index ||
254 iv_index > bt_mesh.iv_index + 42) {
255 BT_ERR("IV Index out of sync: 0x%08x != 0x%08x",
256 iv_index, bt_mesh.iv_index);
257 return false;
258 }
259
260 if (iv_index > bt_mesh.iv_index + 1) {
261 BT_WARN("Performing IV Index Recovery");
262 bt_mesh_rpl_clear();
263 bt_mesh.iv_index = iv_index;
264 bt_mesh.seq = 0U;
265 goto do_update;
266 }
267
268 if (iv_index == bt_mesh.iv_index + 1 && !iv_update) {
269 BT_WARN("Ignoring new index in normal mode");
270 return false;
271 }
272
273 if (!iv_update) {
274 /* Nothing to do */
275 BT_DBG("Already in Normal state");
276 return false;
277 }
278 }
279
280 if (!(IS_ENABLED(CONFIG_BT_MESH_IV_UPDATE_TEST) &&
281 atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_TEST))) {
282 if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
283 BT_WARN("IV Update before minimum duration");
284 return false;
285 }
286 }
287
288 /* Defer change to Normal Operation if there are pending acks */
289 if (!iv_update && bt_mesh_tx_in_progress()) {
290 BT_WARN("IV Update deferred because of pending transfer");
291 atomic_set_bit(bt_mesh.flags, BT_MESH_IVU_PENDING);
292 return false;
293 }
294
295 do_update:
296 atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv_update);
297 bt_mesh.ivu_duration = 0U;
298
299 if (iv_update) {
300 bt_mesh.iv_index = iv_index;
301 BT_DBG("IV Update state entered. New index 0x%08x",
302 bt_mesh.iv_index);
303
304 bt_mesh_rpl_reset();
305 } else {
306 BT_DBG("Normal mode entered");
307 bt_mesh.seq = 0U;
308 }
309
310 k_work_reschedule(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
311
312 /* Notify other modules */
313 if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
314 bt_mesh_friend_sec_update(BT_MESH_KEY_ANY);
315 }
316
317 bt_mesh_subnet_foreach(bt_mesh_beacon_update);
318
319 if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
320 bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
321 bt_mesh_proxy_beacon_send(NULL);
322 }
323
324 if (IS_ENABLED(CONFIG_BT_MESH_CDB)) {
325 bt_mesh_cdb_iv_update(iv_index, iv_update);
326 }
327
328 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
329 store_iv(false);
330 }
331
332 return true;
333 }
334
bt_mesh_next_seq(void)335 uint32_t bt_mesh_next_seq(void)
336 {
337 uint32_t seq = bt_mesh.seq++;
338
339 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
340 store_seq();
341 }
342
343 if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) &&
344 bt_mesh.seq > IV_UPDATE_SEQ_LIMIT &&
345 bt_mesh_subnet_get(BT_MESH_KEY_PRIMARY)) {
346 bt_mesh_beacon_ivu_initiator(true);
347 bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
348 }
349
350 return seq;
351 }
352
bt_mesh_net_local(struct k_work * work)353 static void bt_mesh_net_local(struct k_work *work)
354 {
355 struct net_buf *buf;
356
357 while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
358 struct bt_mesh_subnet *sub = LOOPBACK_BUF_SUB(buf);
359 struct bt_mesh_net_rx rx = {
360 .ctx = {
361 .net_idx = sub->net_idx,
362 /* Initialize AppIdx to a sane value */
363 .app_idx = BT_MESH_KEY_UNUSED,
364 .recv_ttl = TTL(buf->data),
365 /* TTL=1 only goes to local IF */
366 .send_ttl = 1U,
367 .addr = SRC(buf->data),
368 .recv_dst = DST(buf->data),
369 .recv_rssi = 0,
370 },
371 .net_if = BT_MESH_NET_IF_LOCAL,
372 .sub = sub,
373 .old_iv = (IVI(buf->data) != (bt_mesh.iv_index & 0x01)),
374 .ctl = CTL(buf->data),
375 .seq = SEQ(buf->data),
376 .new_key = SUBNET_KEY_TX_IDX(sub),
377 .local_match = 1U,
378 .friend_match = 0U,
379 };
380
381 BT_DBG("src: 0x%04x dst: 0x%04x seq 0x%06x sub %p", rx.ctx.addr,
382 rx.ctx.addr, rx.seq, sub);
383
384 (void) bt_mesh_trans_recv(&buf->b, &rx);
385 net_buf_unref(buf);
386 }
387 }
388
net_tx_cred_get(struct bt_mesh_net_tx * tx)389 static const struct bt_mesh_net_cred *net_tx_cred_get(struct bt_mesh_net_tx *tx)
390 {
391 #if defined(CONFIG_BT_MESH_LOW_POWER)
392 if (tx->friend_cred && bt_mesh.lpn.frnd) {
393 return &bt_mesh.lpn.cred[SUBNET_KEY_TX_IDX(tx->sub)];
394 }
395 #endif
396
397 tx->friend_cred = 0U;
398 return &tx->sub->keys[SUBNET_KEY_TX_IDX(tx->sub)].msg;
399 }
400
net_header_encode(struct bt_mesh_net_tx * tx,uint8_t nid,struct net_buf_simple * buf)401 static int net_header_encode(struct bt_mesh_net_tx *tx, uint8_t nid,
402 struct net_buf_simple *buf)
403 {
404 const bool ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED);
405
406 if (ctl && net_buf_simple_tailroom(buf) < 8) {
407 BT_ERR("Insufficient MIC space for CTL PDU");
408 return -EINVAL;
409 } else if (net_buf_simple_tailroom(buf) < 4) {
410 BT_ERR("Insufficient MIC space for PDU");
411 return -EINVAL;
412 }
413
414 BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x",
415 tx->src, tx->ctx->addr, ctl, bt_mesh.seq);
416
417 net_buf_simple_push_be16(buf, tx->ctx->addr);
418 net_buf_simple_push_be16(buf, tx->src);
419 net_buf_simple_push_be24(buf, bt_mesh_next_seq());
420
421 if (ctl) {
422 net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80);
423 } else {
424 net_buf_simple_push_u8(buf, tx->ctx->send_ttl);
425 }
426
427 net_buf_simple_push_u8(buf, (nid | (BT_MESH_NET_IVI_TX & 1) << 7));
428
429 return 0;
430 }
431
net_encrypt(struct net_buf_simple * buf,const struct bt_mesh_net_cred * cred,uint32_t iv_index,bool proxy)432 static int net_encrypt(struct net_buf_simple *buf,
433 const struct bt_mesh_net_cred *cred, uint32_t iv_index,
434 bool proxy)
435 {
436 int err;
437
438 err = bt_mesh_net_encrypt(cred->enc, buf, iv_index, proxy);
439 if (err) {
440 return err;
441 }
442
443 return bt_mesh_net_obfuscate(buf->data, iv_index, cred->privacy);
444 }
445
bt_mesh_net_encode(struct bt_mesh_net_tx * tx,struct net_buf_simple * buf,bool proxy)446 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf,
447 bool proxy)
448 {
449 const struct bt_mesh_net_cred *cred;
450 int err;
451
452 cred = net_tx_cred_get(tx);
453 err = net_header_encode(tx, cred->nid, buf);
454 if (err) {
455 return err;
456 }
457
458 return net_encrypt(buf, cred, BT_MESH_NET_IVI_TX, proxy);
459 }
460
loopback(const struct bt_mesh_net_tx * tx,const uint8_t * data,size_t len)461 static int loopback(const struct bt_mesh_net_tx *tx, const uint8_t *data,
462 size_t len)
463 {
464 struct net_buf *buf;
465
466 buf = net_buf_alloc(&loopback_buf_pool, K_NO_WAIT);
467 if (!buf) {
468 BT_WARN("Unable to allocate loopback");
469 return -ENOMEM;
470 }
471
472 BT_DBG("");
473
474 LOOPBACK_BUF_SUB(buf) = tx->sub;
475
476 net_buf_add_mem(buf, data, len);
477
478 net_buf_slist_put(&bt_mesh.local_queue, buf);
479
480 k_work_submit(&bt_mesh.local_work);
481
482 return 0;
483 }
484
bt_mesh_net_send(struct bt_mesh_net_tx * tx,struct net_buf * buf,const struct bt_mesh_send_cb * cb,void * cb_data)485 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf,
486 const struct bt_mesh_send_cb *cb, void *cb_data)
487 {
488 const struct bt_mesh_net_cred *cred;
489 int err;
490
491 BT_DBG("src 0x%04x dst 0x%04x len %u headroom %zu tailroom %zu",
492 tx->src, tx->ctx->addr, buf->len, net_buf_headroom(buf),
493 net_buf_tailroom(buf));
494 BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len));
495 BT_DBG("Seq 0x%06x", bt_mesh.seq);
496
497 cred = net_tx_cred_get(tx);
498 err = net_header_encode(tx, cred->nid, &buf->b);
499 if (err) {
500 goto done;
501 }
502
503 /* Deliver to local network interface if necessary */
504 if (bt_mesh_fixed_group_match(tx->ctx->addr) ||
505 bt_mesh_has_addr(tx->ctx->addr)) {
506 err = loopback(tx, buf->data, buf->len);
507
508 /* Local unicast messages should not go out to network */
509 if (BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr) ||
510 tx->ctx->send_ttl == 1U) {
511 if (!err) {
512 send_cb_finalize(cb, cb_data);
513 }
514
515 goto done;
516 }
517 }
518
519 /* Mesh spec 3.4.5.2: "The output filter of the interface connected to
520 * advertising or GATT bearers shall drop all messages with TTL value
521 * set to 1." If a TTL=1 packet wasn't for a local interface, it is
522 * invalid.
523 */
524 if (tx->ctx->send_ttl == 1U) {
525 err = -EINVAL;
526 goto done;
527 }
528
529 err = net_encrypt(&buf->b, cred, BT_MESH_NET_IVI_TX, false);
530 if (err) {
531 goto done;
532 }
533
534 BT_MESH_ADV(buf)->cb = cb;
535 BT_MESH_ADV(buf)->cb_data = cb_data;
536
537 /* Deliver to GATT Proxy Clients if necessary. */
538 if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
539 bt_mesh_proxy_relay(buf, tx->ctx->addr) &&
540 BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
541
542 err = 0;
543 goto done;
544 }
545
546 bt_mesh_adv_send(buf, cb, cb_data);
547
548 done:
549 net_buf_unref(buf);
550 return err;
551 }
552
bt_mesh_net_loopback_clear(uint16_t net_idx)553 void bt_mesh_net_loopback_clear(uint16_t net_idx)
554 {
555 sys_slist_t new_list;
556 struct net_buf *buf;
557
558 BT_DBG("0x%04x", net_idx);
559
560 sys_slist_init(&new_list);
561
562 while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
563 struct bt_mesh_subnet *sub = LOOPBACK_BUF_SUB(buf);
564
565 if (net_idx == BT_MESH_KEY_ANY || net_idx == sub->net_idx) {
566 BT_DBG("Dropped 0x%06x", SEQ(buf->data));
567 net_buf_unref(buf);
568 } else {
569 net_buf_slist_put(&new_list, buf);
570 }
571 }
572
573 bt_mesh.local_queue = new_list;
574 }
575
net_decrypt(struct bt_mesh_net_rx * rx,struct net_buf_simple * in,struct net_buf_simple * out,const struct bt_mesh_net_cred * cred)576 static bool net_decrypt(struct bt_mesh_net_rx *rx, struct net_buf_simple *in,
577 struct net_buf_simple *out,
578 const struct bt_mesh_net_cred *cred)
579 {
580 bool proxy = (rx->net_if == BT_MESH_NET_IF_PROXY_CFG);
581
582 if (NID(in->data) != cred->nid) {
583 return false;
584 }
585
586 BT_DBG("NID 0x%02x", NID(in->data));
587 BT_DBG("IVI %u net->iv_index 0x%08x", IVI(in->data), bt_mesh.iv_index);
588
589 rx->old_iv = (IVI(in->data) != (bt_mesh.iv_index & 0x01));
590
591 net_buf_simple_reset(out);
592 net_buf_simple_add_mem(out, in->data, in->len);
593
594 if (bt_mesh_net_obfuscate(out->data, BT_MESH_NET_IVI_RX(rx),
595 cred->privacy)) {
596 return false;
597 }
598
599 rx->ctx.addr = SRC(out->data);
600 if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) {
601 BT_DBG("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr);
602 return false;
603 }
604
605 if (bt_mesh_has_addr(rx->ctx.addr)) {
606 BT_DBG("Dropping locally originated packet");
607 return false;
608 }
609
610 if (rx->net_if == BT_MESH_NET_IF_ADV && msg_cache_match(out)) {
611 BT_DBG("Duplicate found in Network Message Cache");
612 return false;
613 }
614
615 BT_DBG("src 0x%04x", rx->ctx.addr);
616
617 return bt_mesh_net_decrypt(cred->enc, out, BT_MESH_NET_IVI_RX(rx),
618 proxy) == 0;
619 }
620
621 /* Relaying from advertising to the advertising bearer should only happen
622 * if the Relay state is set to enabled. Locally originated packets always
623 * get sent to the advertising bearer. If the packet came in through GATT,
624 * then we should only relay it if the GATT Proxy state is enabled.
625 */
relay_to_adv(enum bt_mesh_net_if net_if)626 static bool relay_to_adv(enum bt_mesh_net_if net_if)
627 {
628 switch (net_if) {
629 case BT_MESH_NET_IF_ADV:
630 return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED);
631 case BT_MESH_NET_IF_PROXY:
632 return (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED);
633 default:
634 return false;
635 }
636 }
637
bt_mesh_net_relay(struct net_buf_simple * sbuf,struct bt_mesh_net_rx * rx)638 static void bt_mesh_net_relay(struct net_buf_simple *sbuf,
639 struct bt_mesh_net_rx *rx)
640 {
641 const struct bt_mesh_net_cred *cred;
642 struct net_buf *buf;
643 uint8_t transmit;
644
645 if (rx->ctx.recv_ttl <= 1U) {
646 return;
647 }
648
649 if (rx->net_if == BT_MESH_NET_IF_ADV &&
650 !rx->friend_cred &&
651 bt_mesh_relay_get() != BT_MESH_RELAY_ENABLED &&
652 bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_ENABLED) {
653 return;
654 }
655
656 BT_DBG("TTL %u CTL %u dst 0x%04x", rx->ctx.recv_ttl, rx->ctl,
657 rx->ctx.recv_dst);
658
659 /* The Relay Retransmit state is only applied to adv-adv relaying.
660 * Anything else (like GATT to adv, or locally originated packets)
661 * use the Network Transmit state.
662 */
663 if (rx->net_if == BT_MESH_NET_IF_ADV && !rx->friend_cred) {
664 transmit = bt_mesh_relay_retransmit_get();
665 } else {
666 transmit = bt_mesh_net_transmit_get();
667 }
668
669 buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, transmit, K_NO_WAIT);
670 if (!buf) {
671 BT_ERR("Out of relay buffers");
672 return;
673 }
674
675 /* Leave CTL bit intact */
676 sbuf->data[1] &= 0x80;
677 sbuf->data[1] |= rx->ctx.recv_ttl - 1U;
678
679 net_buf_add_mem(buf, sbuf->data, sbuf->len);
680
681 cred = &rx->sub->keys[SUBNET_KEY_TX_IDX(rx->sub)].msg;
682
683 BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data));
684
685 /* Update NID if RX or RX was with friend credentials */
686 if (rx->friend_cred) {
687 buf->data[0] &= 0x80; /* Clear everything except IVI */
688 buf->data[0] |= cred->nid;
689 }
690
691 /* We re-encrypt and obfuscate using the received IVI rather than
692 * the normal TX IVI (which may be different) since the transport
693 * layer nonce includes the IVI.
694 */
695 if (net_encrypt(&buf->b, cred, BT_MESH_NET_IVI_RX(rx), false)) {
696 BT_ERR("Re-encrypting failed");
697 goto done;
698 }
699
700 /* When the Friend node relays message for lpn, the message will be
701 * retransmitted using the managed flooding security credentials and
702 * the Network PDU shall be retransmitted to all network interfaces.
703 */
704 if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
705 (rx->friend_cred ||
706 bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED)) {
707 bt_mesh_proxy_relay(buf, rx->ctx.recv_dst);
708 }
709
710 if (relay_to_adv(rx->net_if) || rx->friend_cred) {
711 bt_mesh_adv_send(buf, NULL, NULL);
712 }
713
714 done:
715 net_buf_unref(buf);
716 }
717
bt_mesh_net_header_parse(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx)718 void bt_mesh_net_header_parse(struct net_buf_simple *buf,
719 struct bt_mesh_net_rx *rx)
720 {
721 rx->old_iv = (IVI(buf->data) != (bt_mesh.iv_index & 0x01));
722 rx->ctl = CTL(buf->data);
723 rx->ctx.recv_ttl = TTL(buf->data);
724 rx->seq = SEQ(buf->data);
725 rx->ctx.addr = SRC(buf->data);
726 rx->ctx.recv_dst = DST(buf->data);
727 }
728
bt_mesh_net_decode(struct net_buf_simple * in,enum bt_mesh_net_if net_if,struct bt_mesh_net_rx * rx,struct net_buf_simple * out)729 int bt_mesh_net_decode(struct net_buf_simple *in, enum bt_mesh_net_if net_if,
730 struct bt_mesh_net_rx *rx, struct net_buf_simple *out)
731 {
732 if (in->len < BT_MESH_NET_MIN_PDU_LEN) {
733 BT_WARN("Dropping too short mesh packet (len %u)", in->len);
734 BT_WARN("%s", bt_hex(in->data, in->len));
735 return -EINVAL;
736 }
737
738 if (in->len > BT_MESH_NET_MAX_PDU_LEN) {
739 BT_WARN("Dropping too long mesh packet (len %u)", in->len);
740 return -EINVAL;
741 }
742
743 if (net_if == BT_MESH_NET_IF_ADV && check_dup(in)) {
744 return -EINVAL;
745 }
746
747 BT_DBG("%u bytes: %s", in->len, bt_hex(in->data, in->len));
748
749 rx->net_if = net_if;
750
751 if (!bt_mesh_net_cred_find(rx, in, out, net_decrypt)) {
752 BT_DBG("Unable to find matching net for packet");
753 return -ENOENT;
754 }
755
756 /* Initialize AppIdx to a sane value */
757 rx->ctx.app_idx = BT_MESH_KEY_UNUSED;
758
759 rx->ctx.recv_ttl = TTL(out->data);
760
761 /* Default to responding with TTL 0 for non-routed messages */
762 if (rx->ctx.recv_ttl == 0U) {
763 rx->ctx.send_ttl = 0U;
764 } else {
765 rx->ctx.send_ttl = BT_MESH_TTL_DEFAULT;
766 }
767
768 rx->ctl = CTL(out->data);
769 rx->seq = SEQ(out->data);
770 rx->ctx.recv_dst = DST(out->data);
771
772 BT_DBG("Decryption successful. Payload len %u", out->len);
773
774 if (net_if != BT_MESH_NET_IF_PROXY_CFG &&
775 rx->ctx.recv_dst == BT_MESH_ADDR_UNASSIGNED) {
776 BT_ERR("Destination address is unassigned; dropping packet");
777 return -EBADMSG;
778 }
779
780 BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst,
781 rx->ctx.recv_ttl);
782 BT_DBG("PDU: %s", bt_hex(out->data, out->len));
783
784 msg_cache_add(rx);
785
786 return 0;
787 }
788
bt_mesh_net_recv(struct net_buf_simple * data,int8_t rssi,enum bt_mesh_net_if net_if)789 void bt_mesh_net_recv(struct net_buf_simple *data, int8_t rssi,
790 enum bt_mesh_net_if net_if)
791 {
792 NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
793 struct bt_mesh_net_rx rx = { .ctx.recv_rssi = rssi };
794 struct net_buf_simple_state state;
795
796 BT_DBG("rssi %d net_if %u", rssi, net_if);
797
798 if (!bt_mesh_is_provisioned()) {
799 return;
800 }
801
802 if (bt_mesh_net_decode(data, net_if, &rx, &buf)) {
803 return;
804 }
805
806 /* Save the state so the buffer can later be relayed */
807 net_buf_simple_save(&buf, &state);
808
809 rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) ||
810 bt_mesh_has_addr(rx.ctx.recv_dst));
811
812 if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
813 net_if == BT_MESH_NET_IF_PROXY) {
814 bt_mesh_proxy_addr_add(data, rx.ctx.addr);
815
816 if (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_DISABLED &&
817 !rx.local_match) {
818 BT_INFO("Proxy is disabled; ignoring message");
819 return;
820 }
821 }
822
823 /* The transport layer has indicated that it has rejected the message,
824 * but would like to see it again if it is received in the future.
825 * This can happen if a message is received when the device is in
826 * Low Power mode, but the message was not encrypted with the friend
827 * credentials. Remove it from the message cache so that we accept
828 * it again in the future.
829 */
830 if (bt_mesh_trans_recv(&buf, &rx) == -EAGAIN) {
831 BT_WARN("Removing rejected message from Network Message Cache");
832 msg_cache[rx.msg_cache_idx].src = BT_MESH_ADDR_UNASSIGNED;
833 /* Rewind the next index now that we're not using this entry */
834 msg_cache_next = rx.msg_cache_idx;
835 }
836
837 /* Relay if this was a group/virtual address, or if the destination
838 * was neither a local element nor an LPN we're Friends for.
839 */
840 if (!BT_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) ||
841 (!rx.local_match && !rx.friend_match)) {
842 net_buf_simple_restore(&buf, &state);
843 bt_mesh_net_relay(&buf, &rx);
844 }
845 }
846
ivu_refresh(struct k_work * work)847 static void ivu_refresh(struct k_work *work)
848 {
849 if (!bt_mesh_is_provisioned()) {
850 return;
851 }
852
853 bt_mesh.ivu_duration = MIN(UINT8_MAX,
854 bt_mesh.ivu_duration + BT_MESH_IVU_HOURS);
855
856 BT_DBG("%s for %u hour%s",
857 atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ?
858 "IVU in Progress" : "IVU Normal mode",
859 bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s");
860
861 if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
862 if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
863 store_iv(true);
864 }
865
866 k_work_reschedule(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
867 return;
868 }
869
870 if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
871 bt_mesh_beacon_ivu_initiator(true);
872 bt_mesh_net_iv_update(bt_mesh.iv_index, false);
873 } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
874 store_iv(true);
875 }
876 }
877
bt_mesh_net_init(void)878 void bt_mesh_net_init(void)
879 {
880 k_work_init_delayable(&bt_mesh.ivu_timer, ivu_refresh);
881
882 k_work_init(&bt_mesh.local_work, bt_mesh_net_local);
883 }
884
net_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)885 static int net_set(const char *name, size_t len_rd, settings_read_cb read_cb,
886 void *cb_arg)
887 {
888 struct net_val net;
889 int err;
890
891 if (len_rd == 0) {
892 BT_DBG("val (null)");
893
894 bt_mesh_comp_unprovision();
895 (void)memset(bt_mesh.dev_key, 0, sizeof(bt_mesh.dev_key));
896 return 0;
897 }
898
899 err = bt_mesh_settings_set(read_cb, cb_arg, &net, sizeof(net));
900 if (err) {
901 BT_ERR("Failed to set \'net\'");
902 return err;
903 }
904
905 memcpy(bt_mesh.dev_key, net.dev_key, sizeof(bt_mesh.dev_key));
906 bt_mesh_comp_provision(net.primary_addr);
907
908 BT_DBG("Provisioned with primary address 0x%04x", net.primary_addr);
909 BT_DBG("Recovered DevKey %s", bt_hex(bt_mesh.dev_key, 16));
910
911 return 0;
912 }
913
914 BT_MESH_SETTINGS_DEFINE(net, "Net", net_set);
915
iv_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)916 static int iv_set(const char *name, size_t len_rd, settings_read_cb read_cb,
917 void *cb_arg)
918 {
919 struct iv_val iv;
920 int err;
921
922 if (len_rd == 0) {
923 BT_DBG("IV deleted");
924
925 bt_mesh.iv_index = 0U;
926 atomic_clear_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
927 return 0;
928 }
929
930 err = bt_mesh_settings_set(read_cb, cb_arg, &iv, sizeof(iv));
931 if (err) {
932 BT_ERR("Failed to set \'iv\'");
933 return err;
934 }
935
936 bt_mesh.iv_index = iv.iv_index;
937 atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv.iv_update);
938 bt_mesh.ivu_duration = iv.iv_duration;
939
940 BT_DBG("IV Index 0x%04x (IV Update Flag %u) duration %u hours",
941 iv.iv_index, iv.iv_update, iv.iv_duration);
942
943 return 0;
944 }
945
946 BT_MESH_SETTINGS_DEFINE(iv, "IV", iv_set);
947
seq_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)948 static int seq_set(const char *name, size_t len_rd, settings_read_cb read_cb,
949 void *cb_arg)
950 {
951 struct seq_val seq;
952 int err;
953
954 if (len_rd == 0) {
955 BT_DBG("val (null)");
956
957 bt_mesh.seq = 0U;
958 return 0;
959 }
960
961 err = bt_mesh_settings_set(read_cb, cb_arg, &seq, sizeof(seq));
962 if (err) {
963 BT_ERR("Failed to set \'seq\'");
964 return err;
965 }
966
967 bt_mesh.seq = sys_get_le24(seq.val);
968
969 if (CONFIG_BT_MESH_SEQ_STORE_RATE > 0) {
970 /* Make sure we have a large enough sequence number. We
971 * subtract 1 so that the first transmission causes a write
972 * to the settings storage.
973 */
974 bt_mesh.seq += (CONFIG_BT_MESH_SEQ_STORE_RATE -
975 (bt_mesh.seq % CONFIG_BT_MESH_SEQ_STORE_RATE));
976 bt_mesh.seq--;
977 }
978
979 BT_DBG("Sequence Number 0x%06x", bt_mesh.seq);
980
981 return 0;
982 }
983
984 BT_MESH_SETTINGS_DEFINE(seq, "Seq", seq_set);
985
clear_iv(void)986 static void clear_iv(void)
987 {
988 int err;
989
990 err = settings_delete("bt/mesh/IV");
991 if (err) {
992 BT_ERR("Failed to clear IV");
993 } else {
994 BT_DBG("Cleared IV");
995 }
996 }
997
store_pending_iv(void)998 static void store_pending_iv(void)
999 {
1000 struct iv_val iv;
1001 int err;
1002
1003 iv.iv_index = bt_mesh.iv_index;
1004 iv.iv_update = atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
1005 iv.iv_duration = bt_mesh.ivu_duration;
1006
1007 err = settings_save_one("bt/mesh/IV", &iv, sizeof(iv));
1008 if (err) {
1009 BT_ERR("Failed to store IV value");
1010 } else {
1011 BT_DBG("Stored IV value");
1012 }
1013 }
1014
bt_mesh_net_pending_iv_store(void)1015 void bt_mesh_net_pending_iv_store(void)
1016 {
1017 if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
1018 store_pending_iv();
1019 } else {
1020 clear_iv();
1021 }
1022 }
1023
clear_net(void)1024 static void clear_net(void)
1025 {
1026 int err;
1027
1028 err = settings_delete("bt/mesh/Net");
1029 if (err) {
1030 BT_ERR("Failed to clear Network");
1031 } else {
1032 BT_DBG("Cleared Network");
1033 }
1034 }
1035
store_pending_net(void)1036 static void store_pending_net(void)
1037 {
1038 struct net_val net;
1039 int err;
1040
1041 BT_DBG("addr 0x%04x DevKey %s", bt_mesh_primary_addr(),
1042 bt_hex(bt_mesh.dev_key, 16));
1043
1044 net.primary_addr = bt_mesh_primary_addr();
1045 memcpy(net.dev_key, bt_mesh.dev_key, 16);
1046
1047 err = settings_save_one("bt/mesh/Net", &net, sizeof(net));
1048 if (err) {
1049 BT_ERR("Failed to store Network value");
1050 } else {
1051 BT_DBG("Stored Network value");
1052 }
1053 }
1054
bt_mesh_net_pending_net_store(void)1055 void bt_mesh_net_pending_net_store(void)
1056 {
1057 if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
1058 store_pending_net();
1059 } else {
1060 clear_net();
1061 }
1062 }
1063
bt_mesh_net_pending_seq_store(void)1064 void bt_mesh_net_pending_seq_store(void)
1065 {
1066 struct seq_val seq;
1067 int err;
1068
1069 if (atomic_test_bit(bt_mesh.flags, BT_MESH_VALID)) {
1070 sys_put_le24(bt_mesh.seq, seq.val);
1071
1072 err = settings_save_one("bt/mesh/Seq", &seq, sizeof(seq));
1073 if (err) {
1074 BT_ERR("Failed to stor Seq value");
1075 } else {
1076 BT_DBG("Stored Seq value");
1077 }
1078 } else {
1079 err = settings_delete("bt/mesh/Seq");
1080 if (err) {
1081 BT_ERR("Failed to clear Seq value");
1082 } else {
1083 BT_DBG("Cleared Seq value");
1084 }
1085 }
1086 }
1087
bt_mesh_net_clear(void)1088 void bt_mesh_net_clear(void)
1089 {
1090 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_NET_PENDING);
1091 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_IV_PENDING);
1092 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_CFG_PENDING);
1093 bt_mesh_settings_store_schedule(BT_MESH_SETTINGS_SEQ_PENDING);
1094 }
1095
bt_mesh_net_settings_commit(void)1096 void bt_mesh_net_settings_commit(void)
1097 {
1098 if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
1099 k_work_reschedule(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
1100 }
1101 }
1102