1 /*  Bluetooth Mesh */
2 
3 /*
4  * SPDX-FileCopyrightText: 2017 Intel Corporation
5  * SPDX-FileContributor: 2018-2024 Espressif Systems (Shanghai) CO LTD
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #include <string.h>
11 #include <errno.h>
12 #include <stdbool.h>
13 
14 #include "crypto.h"
15 #include "adv.h"
16 #include "scan.h"
17 #include "mesh.h"
18 #include "lpn.h"
19 #include "friend.h"
20 #include "transport.h"
21 #include "access.h"
22 #include "foundation.h"
23 #include "beacon.h"
24 #include "settings.h"
25 #include "prov.h"
26 #include "proxy_client.h"
27 #include "proxy_server.h"
28 #include "provisioner_main.h"
29 
30 /* Minimum valid Mesh Network PDU length. The Network headers
31  * themselves take up 9 bytes. After that there is a minumum of 1 byte
32  * payload for both CTL=1 and CTL=0 PDUs (smallest OpCode is 1 byte). CTL=1
33  * PDUs must use a 64-bit (8 byte) NetMIC, whereas CTL=0 PDUs have at least
34  * a 32-bit (4 byte) NetMIC and AppMIC giving again a total of 8 bytes.
35  */
36 #define BLE_MESH_NET_MIN_PDU_LEN (BLE_MESH_NET_HDR_LEN + 1 + 8)
37 
38 /* Seq limit after IV Update is triggered */
39 #define IV_UPDATE_SEQ_LIMIT 8000000
40 
41 #define IVI(pdu)           ((pdu)[0] >> 7)
42 #define NID(pdu)           ((pdu)[0] & 0x7f)
43 #define CTL(pdu)           ((pdu)[1] >> 7)
44 #define TTL(pdu)           ((pdu)[1] & 0x7f)
45 #define SEQ(pdu)           (sys_get_be24(&(pdu)[2]))
46 #define SRC(pdu)           (sys_get_be16(&(pdu)[5]))
47 #define DST(pdu)           (sys_get_be16(&(pdu)[7]))
48 
49 /* Determine how many friendship credentials we need */
50 #if defined(CONFIG_BLE_MESH_FRIEND)
51 #define FRIEND_CRED_COUNT CONFIG_BLE_MESH_FRIEND_LPN_COUNT
52 #elif defined(CONFIG_BLE_MESH_LOW_POWER)
53 #define FRIEND_CRED_COUNT CONFIG_BLE_MESH_SUBNET_COUNT
54 #else
55 #define FRIEND_CRED_COUNT 0
56 #endif
57 
58 #if FRIEND_CRED_COUNT > 0
59 static struct friend_cred friend_cred[FRIEND_CRED_COUNT];
60 #endif
61 
62 static struct {
63     uint32_t src:15, /* MSB of source address is always 0 */
64              seq:17;
65 } msg_cache[CONFIG_BLE_MESH_MSG_CACHE_SIZE];
66 static uint16_t msg_cache_next;
67 
68 /* Singleton network context (the implementation only supports one) */
69 struct bt_mesh_net bt_mesh = {
70     .local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue),
71     .sub = {
72         [0 ... (CONFIG_BLE_MESH_SUBNET_COUNT - 1)] = {
73             .net_idx = BLE_MESH_KEY_UNUSED,
74         }
75     },
76     .app_keys = {
77         [0 ... (CONFIG_BLE_MESH_APP_KEY_COUNT - 1)] = {
78             .net_idx = BLE_MESH_KEY_UNUSED,
79         }
80     },
81 };
82 
83 static uint32_t dup_cache[4];
84 static int dup_cache_next;
85 
86 #if defined(CONFIG_BLE_MESH_RELAY_ADV_BUF)
87 #define BLE_MESH_MAX_STORED_RELAY_COUNT  (CONFIG_BLE_MESH_RELAY_ADV_BUF_COUNT / 2)
88 #endif
89 
check_dup(struct net_buf_simple * data)90 static bool check_dup(struct net_buf_simple *data)
91 {
92     const uint8_t *tail = net_buf_simple_tail(data);
93     uint32_t val = 0U;
94     int i;
95 
96     val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8);
97 
98     for (i = 0; i < ARRAY_SIZE(dup_cache); i++) {
99         if (dup_cache[i] == val) {
100             return true;
101         }
102     }
103 
104     dup_cache[dup_cache_next++] = val;
105     dup_cache_next %= ARRAY_SIZE(dup_cache);
106 
107     return false;
108 }
109 
msg_cache_match(struct bt_mesh_net_rx * rx,struct net_buf_simple * pdu)110 static bool msg_cache_match(struct bt_mesh_net_rx *rx,
111                             struct net_buf_simple *pdu)
112 {
113     int i;
114 
115     for (i = 0; i < ARRAY_SIZE(msg_cache); i++) {
116         if (msg_cache[i].src == SRC(pdu->data) &&
117             msg_cache[i].seq == (SEQ(pdu->data) & BIT_MASK(17))) {
118             return true;
119         }
120     }
121 
122     return false;
123 }
124 
msg_cache_add(struct bt_mesh_net_rx * rx)125 static void msg_cache_add(struct bt_mesh_net_rx *rx)
126 {
127     rx->msg_cache_idx = msg_cache_next++;
128     msg_cache[rx->msg_cache_idx].src = rx->ctx.addr;
129     msg_cache[rx->msg_cache_idx].seq = rx->seq;
130     msg_cache_next %= ARRAY_SIZE(msg_cache);
131 }
132 
133 #if CONFIG_BLE_MESH_PROVISIONER
bt_mesh_msg_cache_clear(uint16_t unicast_addr,uint8_t elem_num)134 void bt_mesh_msg_cache_clear(uint16_t unicast_addr, uint8_t elem_num)
135 {
136     int i;
137 
138     for (i = 0; i < ARRAY_SIZE(msg_cache); i++) {
139         if (msg_cache[i].src >= unicast_addr &&
140             msg_cache[i].src < unicast_addr + elem_num) {
141             memset(&msg_cache[i], 0, sizeof(msg_cache[i]));
142         }
143     }
144 }
145 #endif /* CONFIG_BLE_MESH_PROVISIONER */
146 
bt_mesh_subnet_get(uint16_t net_idx)147 struct bt_mesh_subnet *bt_mesh_subnet_get(uint16_t net_idx)
148 {
149     int i;
150 
151     if (net_idx == BLE_MESH_KEY_ANY) {
152         return &bt_mesh.sub[0];
153     }
154 
155     for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
156         if (bt_mesh.sub[i].net_idx == net_idx) {
157             return &bt_mesh.sub[i];
158         }
159     }
160 
161     return NULL;
162 }
163 
bt_mesh_net_keys_create(struct bt_mesh_subnet_keys * keys,const uint8_t key[16])164 int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys,
165                             const uint8_t key[16])
166 {
167     uint8_t p[] = { 0 };
168     uint8_t nid = 0U;
169     int err = 0;
170 
171     err = bt_mesh_k2(key, p, sizeof(p), &nid, keys->enc, keys->privacy);
172     if (err) {
173         BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
174         return err;
175     }
176 
177     memcpy(keys->net, key, 16);
178 
179     keys->nid = nid;
180 
181     BT_DBG("NID 0x%02x EncKey %s", keys->nid, bt_hex(keys->enc, 16));
182     BT_DBG("PrivacyKey %s", bt_hex(keys->privacy, 16));
183 
184     err = bt_mesh_k3(key, keys->net_id);
185     if (err) {
186         BT_ERR("Unable to generate Net ID");
187         return err;
188     }
189 
190     BT_DBG("NetID %s", bt_hex(keys->net_id, 8));
191 
192 #if defined(CONFIG_BLE_MESH_GATT_PROXY_SERVER)
193     err = bt_mesh_identity_key(key, keys->identity);
194     if (err) {
195         BT_ERR("Unable to generate IdentityKey");
196         return err;
197     }
198 
199     BT_DBG("IdentityKey %s", bt_hex(keys->identity, 16));
200 #endif /* GATT_PROXY */
201 
202     err = bt_mesh_beacon_key(key, keys->beacon);
203     if (err) {
204         BT_ERR("Unable to generate beacon key");
205         return err;
206     }
207 
208     BT_DBG("BeaconKey %s", bt_hex(keys->beacon, 16));
209 
210     return 0;
211 }
212 
213 #if (defined(CONFIG_BLE_MESH_LOW_POWER) || \
214      defined(CONFIG_BLE_MESH_FRIEND))
friend_cred_set(struct friend_cred * cred,uint8_t idx,const uint8_t net_key[16])215 int friend_cred_set(struct friend_cred *cred, uint8_t idx, const uint8_t net_key[16])
216 {
217     uint16_t lpn_addr = 0U, frnd_addr = 0U;
218     uint8_t p[9] = {0};
219     int err = 0;
220 
221 #if defined(CONFIG_BLE_MESH_LOW_POWER)
222     if (cred->addr == bt_mesh.lpn.frnd) {
223         lpn_addr = bt_mesh_primary_addr();
224         frnd_addr = cred->addr;
225     } else {
226         lpn_addr = cred->addr;
227         frnd_addr = bt_mesh_primary_addr();
228     }
229 #else
230     lpn_addr = cred->addr;
231     frnd_addr = bt_mesh_primary_addr();
232 #endif
233 
234     BT_DBG("LPNAddress 0x%04x FriendAddress 0x%04x", lpn_addr, frnd_addr);
235     BT_DBG("LPNCounter 0x%04x FriendCounter 0x%04x", cred->lpn_counter,
236            cred->frnd_counter);
237 
238     p[0] = 0x01;
239     sys_put_be16(lpn_addr, p + 1);
240     sys_put_be16(frnd_addr, p + 3);
241     sys_put_be16(cred->lpn_counter, p + 5);
242     sys_put_be16(cred->frnd_counter, p + 7);
243 
244     err = bt_mesh_k2(net_key, p, sizeof(p), &cred->cred[idx].nid,
245                      cred->cred[idx].enc, cred->cred[idx].privacy);
246     if (err) {
247         BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
248         return err;
249     }
250 
251     BT_DBG("Friend NID 0x%02x EncKey %s", cred->cred[idx].nid,
252            bt_hex(cred->cred[idx].enc, 16));
253     BT_DBG("Friend PrivacyKey %s", bt_hex(cred->cred[idx].privacy, 16));
254 
255     return 0;
256 }
257 
friend_cred_refresh(uint16_t net_idx)258 void friend_cred_refresh(uint16_t net_idx)
259 {
260     int i;
261 
262     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
263         struct friend_cred *cred = &friend_cred[i];
264 
265         if (cred->addr != BLE_MESH_ADDR_UNASSIGNED &&
266                 cred->net_idx == net_idx) {
267             memcpy(&cred->cred[0], &cred->cred[1],
268                    sizeof(cred->cred[0]));
269         }
270     }
271 }
272 
friend_cred_update(struct bt_mesh_subnet * sub)273 int friend_cred_update(struct bt_mesh_subnet *sub)
274 {
275     int err = 0, i;
276 
277     BT_DBG("net_idx 0x%04x", sub->net_idx);
278 
279     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
280         struct friend_cred *cred = &friend_cred[i];
281 
282         if (cred->addr == BLE_MESH_ADDR_UNASSIGNED ||
283                 cred->net_idx != sub->net_idx) {
284             continue;
285         }
286 
287         err = friend_cred_set(cred, 1, sub->keys[1].net);
288         if (err) {
289             return err;
290         }
291     }
292 
293     return 0;
294 }
295 
friend_cred_create(struct bt_mesh_subnet * sub,uint16_t addr,uint16_t lpn_counter,uint16_t frnd_counter)296 struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, uint16_t addr,
297                                        uint16_t lpn_counter, uint16_t frnd_counter)
298 {
299     struct friend_cred *cred = NULL;
300     int i, err = 0;
301 
302     BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
303 
304     for (cred = NULL, i = 0; i < ARRAY_SIZE(friend_cred); i++) {
305         if ((friend_cred[i].addr == BLE_MESH_ADDR_UNASSIGNED) ||
306                 (friend_cred[i].addr == addr &&
307                  friend_cred[i].net_idx == sub->net_idx)) {
308             cred = &friend_cred[i];
309             break;
310         }
311     }
312 
313     if (!cred) {
314         BT_WARN("No free friend credential slots");
315         return NULL;
316     }
317 
318     cred->net_idx = sub->net_idx;
319     cred->addr = addr;
320     cred->lpn_counter = lpn_counter;
321     cred->frnd_counter = frnd_counter;
322 
323     err = friend_cred_set(cred, 0, sub->keys[0].net);
324     if (err) {
325         friend_cred_clear(cred);
326         return NULL;
327     }
328 
329     if (sub->kr_flag) {
330         err = friend_cred_set(cred, 1, sub->keys[1].net);
331         if (err) {
332             friend_cred_clear(cred);
333             return NULL;
334         }
335     }
336 
337     return cred;
338 }
339 
friend_cred_clear(struct friend_cred * cred)340 void friend_cred_clear(struct friend_cred *cred)
341 {
342     cred->net_idx = BLE_MESH_KEY_UNUSED;
343     cred->addr = BLE_MESH_ADDR_UNASSIGNED;
344     cred->lpn_counter = 0U;
345     cred->frnd_counter = 0U;
346     (void)memset(cred->cred, 0, sizeof(cred->cred));
347 }
348 
friend_cred_del(uint16_t net_idx,uint16_t addr)349 int friend_cred_del(uint16_t net_idx, uint16_t addr)
350 {
351     int i;
352 
353     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
354         struct friend_cred *cred = &friend_cred[i];
355 
356         if (cred->addr == addr && cred->net_idx == net_idx) {
357             friend_cred_clear(cred);
358             return 0;
359         }
360     }
361 
362     return -ENOENT;
363 }
364 
friend_cred_get(struct bt_mesh_subnet * sub,uint16_t addr,uint8_t * nid,const uint8_t ** enc,const uint8_t ** priv)365 int friend_cred_get(struct bt_mesh_subnet *sub, uint16_t addr, uint8_t *nid,
366                     const uint8_t **enc, const uint8_t **priv)
367 {
368     int i;
369 
370     BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
371 
372     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
373         struct friend_cred *cred = &friend_cred[i];
374 
375         if (cred->net_idx != sub->net_idx) {
376             continue;
377         }
378 
379         if (addr != BLE_MESH_ADDR_UNASSIGNED && cred->addr != addr) {
380             continue;
381         }
382 
383         if (nid) {
384             *nid = cred->cred[sub->kr_flag].nid;
385         }
386 
387         if (enc) {
388             *enc = cred->cred[sub->kr_flag].enc;
389         }
390 
391         if (priv) {
392             *priv = cred->cred[sub->kr_flag].privacy;
393         }
394 
395         return 0;
396     }
397 
398     return -ENOENT;
399 }
400 #else
friend_cred_get(struct bt_mesh_subnet * sub,uint16_t addr,uint8_t * nid,const uint8_t ** enc,const uint8_t ** priv)401 int friend_cred_get(struct bt_mesh_subnet *sub, uint16_t addr, uint8_t *nid,
402                     const uint8_t **enc, const uint8_t **priv)
403 {
404     return -ENOENT;
405 }
406 #endif /* FRIEND || LOW_POWER */
407 
bt_mesh_net_flags(struct bt_mesh_subnet * sub)408 uint8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub)
409 {
410     uint8_t flags = 0x00;
411 
412     if (sub && sub->kr_flag) {
413         flags |= BLE_MESH_NET_FLAG_KR;
414     }
415 
416     if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
417         flags |= BLE_MESH_NET_FLAG_IVU;
418     }
419 
420     return flags;
421 }
422 
bt_mesh_net_beacon_update(struct bt_mesh_subnet * sub)423 int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub)
424 {
425     uint8_t flags = bt_mesh_net_flags(sub);
426     struct bt_mesh_subnet_keys *keys = NULL;
427 
428     if (sub->kr_flag) {
429         BT_DBG("NetIndex %u Using new key", sub->net_idx);
430         keys = &sub->keys[1];
431     } else {
432         BT_DBG("NetIndex %u Using current key", sub->net_idx);
433         keys = &sub->keys[0];
434     }
435 
436     BT_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index);
437 
438     return bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id,
439                                bt_mesh.iv_index, sub->auth);
440 }
441 
bt_mesh_net_create(uint16_t idx,uint8_t flags,const uint8_t key[16],uint32_t iv_index)442 int bt_mesh_net_create(uint16_t idx, uint8_t flags, const uint8_t key[16],
443                        uint32_t iv_index)
444 {
445     struct bt_mesh_subnet *sub = NULL;
446     int err = 0;
447 
448     BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index);
449 
450     BT_DBG("NetKey %s", bt_hex(key, 16));
451 
452     (void)memset(msg_cache, 0, sizeof(msg_cache));
453     msg_cache_next = 0U;
454 
455     sub = &bt_mesh.sub[0];
456 
457     sub->kr_flag = BLE_MESH_KEY_REFRESH(flags);
458     if (sub->kr_flag) {
459         err = bt_mesh_net_keys_create(&sub->keys[1], key);
460         if (err) {
461             return -EIO;
462         }
463 
464         sub->kr_phase = BLE_MESH_KR_PHASE_2;
465     } else {
466         err = bt_mesh_net_keys_create(&sub->keys[0], key);
467         if (err) {
468             return -EIO;
469         }
470     }
471 
472     sub->net_idx = idx;
473 
474     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER)) {
475         sub->node_id = BLE_MESH_NODE_IDENTITY_STOPPED;
476     } else {
477         sub->node_id = BLE_MESH_NODE_IDENTITY_NOT_SUPPORTED;
478     }
479 
480     bt_mesh.iv_index = iv_index;
481     bt_mesh_atomic_set_bit_to(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS,
482                               BLE_MESH_IV_UPDATE(flags));
483 
484     /* Set minimum required hours, since the 96-hour minimum requirement
485      * doesn't apply straight after provisioning (since we can't know how
486      * long has actually passed since the network changed its state).
487      */
488     bt_mesh.ivu_duration = BLE_MESH_IVU_MIN_HOURS;
489 
490     /* Make sure we have valid beacon data to be sent */
491     bt_mesh_net_beacon_update(sub);
492 
493     return 0;
494 }
495 
bt_mesh_net_revoke_keys(struct bt_mesh_subnet * sub)496 void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub)
497 {
498     int i;
499 
500     BT_DBG("idx 0x%04x", sub->net_idx);
501 
502     memcpy(&sub->keys[0], &sub->keys[1], sizeof(sub->keys[0]));
503 
504     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
505         BT_DBG("Store updated NetKey persistently");
506         bt_mesh_store_subnet(sub);
507     }
508 
509     for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
510         struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
511 
512         if (key->net_idx != sub->net_idx || !key->updated) {
513             continue;
514         }
515 
516         memcpy(&key->keys[0], &key->keys[1], sizeof(key->keys[0]));
517         key->updated = false;
518 
519         if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
520             BT_DBG("Store updated AppKey persistently");
521             bt_mesh_store_app_key(key);
522         }
523     }
524 }
525 
bt_mesh_kr_update(struct bt_mesh_subnet * sub,uint8_t new_kr,bool new_key)526 bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, uint8_t new_kr, bool new_key)
527 {
528     if (new_kr != sub->kr_flag && sub->kr_phase == BLE_MESH_KR_NORMAL) {
529         BT_WARN("KR change in normal operation. Are we blacklisted?");
530         return false;
531     }
532 
533     sub->kr_flag = new_kr;
534 
535     if (sub->kr_flag) {
536         if (sub->kr_phase == BLE_MESH_KR_PHASE_1) {
537             BT_INFO("Phase 1 -> Phase 2");
538             sub->kr_phase = BLE_MESH_KR_PHASE_2;
539 
540             if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
541                 BT_DBG("Storing kr phase persistently");
542                 bt_mesh_store_subnet(sub);
543             }
544 
545             return true;
546         }
547     } else {
548         switch (sub->kr_phase) {
549         case BLE_MESH_KR_PHASE_1:
550             if (!new_key) {
551                 /* Ignore */
552                 break;
553             }
554         /* Upon receiving a Secure Network beacon with the KR flag set
555          * to 0 using the new NetKey in Phase 1, the node shall
556          * immediately transition to Phase 3, which effectively skips
557          * Phase 2.
558          *
559          * Intentional fall-through.
560          */
561         case BLE_MESH_KR_PHASE_2:
562             BT_INFO("KR Phase 0x%02x -> Normal", sub->kr_phase);
563 
564             sub->kr_phase = BLE_MESH_KR_NORMAL;
565             bt_mesh_net_revoke_keys(sub);
566 
567             if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) ||
568                     IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
569                 friend_cred_refresh(sub->net_idx);
570             }
571 
572             return true;
573         }
574     }
575 
576     return false;
577 }
578 
bt_mesh_rpl_reset(void)579 void bt_mesh_rpl_reset(void)
580 {
581     int i;
582 
583     /* Discard "old old" IV Index entries from RPL and flag
584      * any other ones (which are valid) as old.
585      */
586     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
587         struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
588 
589         if (rpl->src) {
590             if (rpl->old_iv) {
591                 (void)memset(rpl, 0, sizeof(*rpl));
592             } else {
593                 rpl->old_iv = true;
594             }
595 
596             if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
597                 bt_mesh_store_rpl(rpl);
598             }
599         }
600     }
601 }
602 
603 #if defined(CONFIG_BLE_MESH_IV_UPDATE_TEST)
bt_mesh_iv_update_test(bool enable)604 void bt_mesh_iv_update_test(bool enable)
605 {
606     bt_mesh_atomic_set_bit_to(bt_mesh.flags, BLE_MESH_IVU_TEST, enable);
607     /* Reset the duration variable - needed for some PTS tests */
608     bt_mesh.ivu_duration = 0U;
609 }
610 
bt_mesh_iv_update(void)611 bool bt_mesh_iv_update(void)
612 {
613     if (!bt_mesh_is_provisioned()) {
614         BT_ERR("Not yet provisioned");
615         return false;
616     }
617 
618     if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
619         bt_mesh_net_iv_update(bt_mesh.iv_index, false);
620     } else {
621         bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
622     }
623 
624     bt_mesh_net_sec_update(NULL);
625 
626     return bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS);
627 }
628 #endif /* CONFIG_BLE_MESH_IV_UPDATE_TEST */
629 
630 /* Used for sending immediate beacons to Friend queues and GATT clients */
bt_mesh_net_sec_update(struct bt_mesh_subnet * sub)631 void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub)
632 {
633     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
634         bt_mesh_friend_sec_update(sub ? sub->net_idx : BLE_MESH_KEY_ANY);
635     }
636 
637     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
638             bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED) {
639         bt_mesh_proxy_server_beacon_send(sub);
640     }
641 }
642 
bt_mesh_net_iv_update(uint32_t iv_index,bool iv_update)643 bool bt_mesh_net_iv_update(uint32_t iv_index, bool iv_update)
644 {
645     int i;
646 
647     if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
648         /* We're currently in IV Update mode */
649 
650         if (iv_index != bt_mesh.iv_index) {
651             BT_WARN("IV Index mismatch: 0x%08x != 0x%08x",
652                     iv_index, bt_mesh.iv_index);
653             return false;
654         }
655 
656         if (iv_update) {
657             /* Nothing to do */
658             BT_DBG("Already in IV Update in Progress state");
659             return false;
660         }
661     } else {
662         /* We're currently in Normal mode */
663 
664         if (iv_index == bt_mesh.iv_index) {
665             BT_DBG("Same IV Index in normal mode");
666             return false;
667         }
668 
669         if (iv_index < bt_mesh.iv_index ||
670                 iv_index > bt_mesh.iv_index + 42) {
671             BT_ERR("IV Index out of sync: 0x%08x != 0x%08x",
672                    iv_index, bt_mesh.iv_index);
673             return false;
674         }
675 
676         if ((iv_index > bt_mesh.iv_index + 1)
677 #if CONFIG_BLE_MESH_IVU_RECOVERY_IVI
678             || (iv_index == bt_mesh.iv_index + 1 && !iv_update)
679 #endif
680             ) {
681             BT_WARN("Performing IV Index Recovery");
682             (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
683             bt_mesh.iv_index = iv_index;
684             bt_mesh.seq = 0U;
685             goto do_update;
686         }
687 
688 #if !CONFIG_BLE_MESH_IVU_RECOVERY_IVI
689         if (iv_index == bt_mesh.iv_index + 1 && !iv_update) {
690             BT_WARN("Ignoring new index in normal mode");
691             return false;
692         }
693 #endif
694 
695         if (!iv_update) {
696             /* Nothing to do */
697             BT_DBG("Already in Normal state");
698             return false;
699         }
700     }
701 
702     if (!(IS_ENABLED(CONFIG_BLE_MESH_IV_UPDATE_TEST) &&
703             bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_TEST))) {
704         if (bt_mesh.ivu_duration < BLE_MESH_IVU_MIN_HOURS) {
705             BT_WARN("IV Update before minimum duration");
706             return false;
707         }
708     }
709 
710     /* Defer change to Normal Operation if there are pending acks */
711     if (!iv_update && bt_mesh_tx_in_progress()) {
712         BT_WARN("IV Update deferred because of pending transfer");
713         bt_mesh_atomic_set_bit(bt_mesh.flags, BLE_MESH_IVU_PENDING);
714         return false;
715     }
716 
717 do_update:
718     bt_mesh_atomic_set_bit_to(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS, iv_update);
719     bt_mesh.ivu_duration = 0U;
720 
721     if (iv_update) {
722         bt_mesh.iv_index = iv_index;
723         BT_INFO("IV Update state entered. New index 0x%08x",
724                bt_mesh.iv_index);
725 
726         bt_mesh_rpl_reset();
727     } else {
728         BT_INFO("Normal mode entered");
729         bt_mesh.seq = 0U;
730     }
731 
732     k_delayed_work_submit(&bt_mesh.ivu_timer, BLE_MESH_IVU_TIMEOUT);
733 
734     size_t subnet_size = bt_mesh_rx_netkey_size();
735 
736     for (i = 0; i < subnet_size; i++) {
737         struct bt_mesh_subnet *sub = bt_mesh_rx_netkey_get(i);
738         if (sub && sub->net_idx != BLE_MESH_KEY_UNUSED) {
739             bt_mesh_net_beacon_update(sub);
740         }
741     }
742 
743     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
744         bt_mesh_store_iv(false);
745     }
746 
747     return true;
748 }
749 
bt_mesh_primary_subnet_exist(void)750 bool bt_mesh_primary_subnet_exist(void)
751 {
752     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
753         if (bt_mesh_subnet_get(BLE_MESH_KEY_PRIMARY)) {
754             return true;
755         }
756     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en()) {
757         if (bt_mesh_provisioner_subnet_get(BLE_MESH_KEY_PRIMARY)) {
758             return true;
759         }
760     }
761 
762     return false;
763 }
764 
bt_mesh_next_seq(void)765 uint32_t bt_mesh_next_seq(void)
766 {
767     uint32_t seq = bt_mesh.seq++;
768 
769     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
770         bt_mesh_store_seq();
771     }
772 
773     if (!bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS) &&
774             bt_mesh.seq > IV_UPDATE_SEQ_LIMIT &&
775             bt_mesh_primary_subnet_exist()) {
776         bt_mesh_beacon_ivu_initiator(true);
777         bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
778         bt_mesh_net_sec_update(NULL);
779     }
780 
781     return seq;
782 }
783 
bt_mesh_net_resend(struct bt_mesh_subnet * sub,struct net_buf * buf,bool new_key,const struct bt_mesh_send_cb * cb,void * cb_data)784 int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf,
785                        bool new_key, const struct bt_mesh_send_cb *cb,
786                        void *cb_data)
787 {
788     const uint8_t *enc = NULL, *priv = NULL;
789     uint32_t seq = 0U;
790     uint16_t dst = 0U;
791     int err = 0;
792 
793     BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key,
794            buf->len);
795 
796     enc = sub->keys[new_key].enc;
797     priv = sub->keys[new_key].privacy;
798 
799     err = bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
800     if (err) {
801         BT_ERR("De-obfuscate failed (err %d)", err);
802         return err;
803     }
804 
805     err = bt_mesh_net_decrypt(enc, &buf->b, BLE_MESH_NET_IVI_TX, false);
806     if (err) {
807         BT_ERR("Decrypt failed (err %d)", err);
808         return err;
809     }
810 
811     /* Update with a new sequence number */
812     seq = bt_mesh_next_seq();
813     sys_put_be24(seq, &buf->data[2]);
814 
815     /* Get destination, in case it's a proxy client */
816     dst = DST(buf->data);
817 
818     err = bt_mesh_net_encrypt(enc, &buf->b, BLE_MESH_NET_IVI_TX, false);
819     if (err) {
820         BT_ERR("Encrypt failed (err %d)", err);
821         return err;
822     }
823 
824     err = bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
825     if (err) {
826         BT_ERR("Obfuscate failed (err %d)", err);
827         return err;
828     }
829 
830     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
831         bt_mesh_proxy_server_relay(&buf->b, dst) &&
832         BLE_MESH_ADDR_IS_UNICAST(dst)) {
833         send_cb_finalize(cb, cb_data);
834         return 0;
835     }
836 
837     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_CLIENT) &&
838         bt_mesh_proxy_client_relay(&buf->b, dst)) {
839         send_cb_finalize(cb, cb_data);
840         return 0;
841     }
842 
843     bt_mesh_adv_send(buf, cb, cb_data);
844     return 0;
845 }
846 
bt_mesh_net_local(struct k_work * work)847 static void bt_mesh_net_local(struct k_work *work)
848 {
849     struct net_buf *buf = NULL;
850 
851     while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
852         BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
853         bt_mesh_net_recv(&buf->b, 0, BLE_MESH_NET_IF_LOCAL);
854         net_buf_unref(buf);
855     }
856 }
857 
bt_mesh_net_encode(struct bt_mesh_net_tx * tx,struct net_buf_simple * buf,bool proxy)858 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf,
859                        bool proxy)
860 {
861     const bool ctl = (tx->ctx->app_idx == BLE_MESH_KEY_UNUSED);
862     const uint8_t *enc = NULL, *priv = NULL;
863     uint8_t nid = 0U;
864     int err = 0;
865 
866     if (ctl && net_buf_simple_tailroom(buf) < BLE_MESH_MIC_LONG) {
867         BT_ERR("Insufficient MIC space for CTL PDU");
868         return -EINVAL;
869     } else if (net_buf_simple_tailroom(buf) < BLE_MESH_MIC_SHORT) {
870         BT_ERR("Insufficient MIC space for PDU");
871         return -EINVAL;
872     }
873 
874     BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x",
875            tx->src, tx->ctx->addr, ctl, bt_mesh.seq);
876 
877     net_buf_simple_push_be16(buf, tx->ctx->addr);
878     net_buf_simple_push_be16(buf, tx->src);
879 
880     net_buf_simple_push_be24(buf, bt_mesh_next_seq());
881 
882     if (ctl) {
883         net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80);
884     } else {
885         net_buf_simple_push_u8(buf, tx->ctx->send_ttl);
886     }
887 
888     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) && tx->friend_cred) {
889         if (friend_cred_get(tx->sub, BLE_MESH_ADDR_UNASSIGNED,
890                             &nid, &enc, &priv)) {
891             BT_WARN("Falling back to master credentials");
892 
893             tx->friend_cred = 0U;
894 
895             nid = tx->sub->keys[tx->sub->kr_flag].nid;
896             enc = tx->sub->keys[tx->sub->kr_flag].enc;
897             priv = tx->sub->keys[tx->sub->kr_flag].privacy;
898         }
899     } else {
900         tx->friend_cred = 0U;
901         nid = tx->sub->keys[tx->sub->kr_flag].nid;
902         enc = tx->sub->keys[tx->sub->kr_flag].enc;
903         priv = tx->sub->keys[tx->sub->kr_flag].privacy;
904     }
905 
906     net_buf_simple_push_u8(buf, (nid | (BLE_MESH_NET_IVI_TX & 1) << 7));
907 
908     err = bt_mesh_net_encrypt(enc, buf, BLE_MESH_NET_IVI_TX, proxy);
909     if (err) {
910         return err;
911     }
912 
913     return bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
914 }
915 
bt_mesh_net_send(struct bt_mesh_net_tx * tx,struct net_buf * buf,const struct bt_mesh_send_cb * cb,void * cb_data)916 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf,
917                      const struct bt_mesh_send_cb *cb, void *cb_data)
918 {
919     int err = 0;
920 
921     BT_DBG("src 0x%04x dst 0x%04x len %u headroom %u tailroom %u",
922            tx->src, tx->ctx->addr, buf->len, net_buf_headroom(buf),
923            net_buf_tailroom(buf));
924     BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len));
925     BT_DBG("Seq 0x%06x", bt_mesh.seq);
926 
927     if (tx->ctx->send_ttl == BLE_MESH_TTL_DEFAULT) {
928         tx->ctx->send_ttl = bt_mesh_default_ttl_get();
929     }
930 
931     err = bt_mesh_net_encode(tx, &buf->b, false);
932     if (err) {
933         goto done;
934     }
935 
936     /* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2:
937      * "The output filter of the interface connected to advertising or
938      * GATT bearers shall drop all messages with TTL value set to 1."
939      */
940     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
941             tx->ctx->send_ttl != 1U) {
942         if (bt_mesh_proxy_server_relay(&buf->b, tx->ctx->addr) &&
943                 BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
944             /* Notify completion if this only went
945              * through the Mesh Proxy.
946              */
947             send_cb_finalize(cb, cb_data);
948 
949             err = 0;
950             goto done;
951         }
952     }
953 
954     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_CLIENT) &&
955             tx->ctx->send_ttl != 1U) {
956         if (bt_mesh_proxy_client_relay(&buf->b, tx->ctx->addr)) {
957             /* If Proxy Client succeeds to send messages with GATT bearer,
958              * we can directly finish here. And if not, which means no
959              * connection has been created with Proxy Client, here we will
960              * use advertising bearer for the messages.
961              */
962             send_cb_finalize(cb, cb_data);
963 
964             err = 0;
965             goto done;
966         }
967     }
968 
969     /* Deliver to local network interface if necessary */
970     if (((IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) ||
971         (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en())) &&
972         (bt_mesh_fixed_group_match(tx->ctx->addr) || bt_mesh_elem_find(tx->ctx->addr))) {
973         /**
974          * If the target address isn't a unicast address, then the callback function
975          * will be called by `adv task` in place of here, to avoid the callback function
976          * being called twice.
977          * See BLEMESH24-76 for more details.
978          */
979         if (BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
980             if (cb && cb->start) {
981                 cb->start(0, 0, cb_data);
982             }
983 
984             net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf));
985 
986             if (cb && cb->end) {
987                 cb->end(0, cb_data);
988             }
989 
990             k_work_submit(&bt_mesh.local_work);
991 
992             goto done;
993         } else {
994             net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf));
995             k_work_submit(&bt_mesh.local_work);
996         }
997     }
998 
999     if (tx->ctx->send_ttl != 1U) {
1000         /* Deliver to the advertising network interface. Mesh spec
1001          * 3.4.5.2: "The output filter of the interface connected to
1002          * advertising or GATT bearers shall drop all messages with
1003          * TTL value set to 1."
1004          */
1005         bt_mesh_adv_send(buf, cb, cb_data);
1006     }
1007 
1008 done:
1009     net_buf_unref(buf);
1010     return err;
1011 }
1012 
auth_match(struct bt_mesh_subnet_keys * keys,const uint8_t net_id[8],uint8_t flags,uint32_t iv_index,const uint8_t auth[8])1013 static bool auth_match(struct bt_mesh_subnet_keys *keys,
1014                        const uint8_t net_id[8], uint8_t flags,
1015                        uint32_t iv_index, const uint8_t auth[8])
1016 {
1017     uint8_t net_auth[8] = {0};
1018 
1019     if (memcmp(net_id, keys->net_id, 8)) {
1020         return false;
1021     }
1022 
1023     bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index,
1024                         net_auth);
1025 
1026     if (memcmp(auth, net_auth, 8)) {
1027         BT_WARN("Authentication Value %s != %s",
1028                 bt_hex(auth, 8), bt_hex(net_auth, 8));
1029         return false;
1030     }
1031 
1032     return true;
1033 }
1034 
bt_mesh_subnet_find(const uint8_t net_id[8],uint8_t flags,uint32_t iv_index,const uint8_t auth[8],bool * new_key)1035 struct bt_mesh_subnet *bt_mesh_subnet_find(const uint8_t net_id[8], uint8_t flags,
1036                                            uint32_t iv_index, const uint8_t auth[8],
1037                                            bool *new_key)
1038 {
1039     size_t subnet_size = 0U;
1040     int i;
1041 
1042     subnet_size = bt_mesh_rx_netkey_size();
1043 
1044     for (i = 0; i < subnet_size; i++) {
1045         struct bt_mesh_subnet *sub = bt_mesh_rx_netkey_get(i);
1046 
1047         if (sub == NULL || sub->net_idx == BLE_MESH_KEY_UNUSED) {
1048             continue;
1049         }
1050 
1051         if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) {
1052             *new_key = false;
1053             return sub;
1054         }
1055 
1056         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1057             continue;
1058         }
1059 
1060         if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) {
1061             *new_key = true;
1062             return sub;
1063         }
1064     }
1065 
1066     return NULL;
1067 }
1068 
net_decrypt(struct bt_mesh_subnet * sub,const uint8_t * enc,const uint8_t * priv,const uint8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1069 static int net_decrypt(struct bt_mesh_subnet *sub, const uint8_t *enc,
1070                        const uint8_t *priv, const uint8_t *data,
1071                        size_t data_len, struct bt_mesh_net_rx *rx,
1072                        struct net_buf_simple *buf)
1073 {
1074     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1075     BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index);
1076 
1077     rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01));
1078 
1079     net_buf_simple_reset(buf);
1080     memcpy(net_buf_simple_add(buf, data_len), data, data_len);
1081 
1082     if (bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_RX(rx), priv)) {
1083         return -ENOENT;
1084     }
1085 
1086     rx->ctx.addr = SRC(buf->data);
1087     if (!BLE_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) {
1088         BT_INFO("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr);
1089         return -EINVAL;
1090     }
1091 
1092     if (rx->net_if == BLE_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) {
1093         BT_DBG("Duplicate found in Network Message Cache");
1094         return -EALREADY;
1095     }
1096 
1097     BT_DBG("src 0x%04x", rx->ctx.addr);
1098 
1099     if (IS_ENABLED(CONFIG_BLE_MESH_PROXY) &&
1100             rx->net_if == BLE_MESH_NET_IF_PROXY_CFG) {
1101         return bt_mesh_net_decrypt(enc, buf, BLE_MESH_NET_IVI_RX(rx),
1102                                    true);
1103     }
1104 
1105     return bt_mesh_net_decrypt(enc, buf, BLE_MESH_NET_IVI_RX(rx), false);
1106 }
1107 
1108 #if (defined(CONFIG_BLE_MESH_LOW_POWER) || \
1109      defined(CONFIG_BLE_MESH_FRIEND))
friend_decrypt(struct bt_mesh_subnet * sub,const uint8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1110 static int friend_decrypt(struct bt_mesh_subnet *sub, const uint8_t *data,
1111                           size_t data_len, struct bt_mesh_net_rx *rx,
1112                           struct net_buf_simple *buf)
1113 {
1114     int i;
1115 
1116     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1117 
1118     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
1119         struct friend_cred *cred = &friend_cred[i];
1120 
1121         if (cred->net_idx != sub->net_idx) {
1122             continue;
1123         }
1124 
1125         if (NID(data) == cred->cred[0].nid &&
1126                 !net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy,
1127                              data, data_len, rx, buf)) {
1128             return 0;
1129         }
1130 
1131         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1132             continue;
1133         }
1134 
1135         if (NID(data) == cred->cred[1].nid &&
1136                 !net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy,
1137                              data, data_len, rx, buf)) {
1138             rx->new_key = 1U;
1139             return 0;
1140         }
1141     }
1142 
1143     return -ENOENT;
1144 }
1145 #endif
1146 
net_find_and_decrypt(const uint8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1147 static bool net_find_and_decrypt(const uint8_t *data, size_t data_len,
1148                                  struct bt_mesh_net_rx *rx,
1149                                  struct net_buf_simple *buf)
1150 {
1151     struct bt_mesh_subnet *sub = NULL;
1152     size_t array_size = 0U;
1153     int i;
1154 
1155     BT_DBG("%s", __func__);
1156 
1157     array_size = bt_mesh_rx_netkey_size();
1158 
1159     for (i = 0; i < array_size; i++) {
1160         sub = bt_mesh_rx_netkey_get(i);
1161         if (!sub) {
1162             BT_DBG("Subnet not found");
1163             continue;
1164         }
1165 
1166         if (sub->net_idx == BLE_MESH_KEY_UNUSED) {
1167             continue;
1168         }
1169 
1170 #if (defined(CONFIG_BLE_MESH_LOW_POWER) || defined(CONFIG_BLE_MESH_FRIEND))
1171         if (!friend_decrypt(sub, data, data_len, rx, buf)) {
1172             rx->friend_cred = 1;
1173             rx->ctx.net_idx = sub->net_idx;
1174             rx->sub = sub;
1175             return true;
1176         }
1177 #endif
1178 
1179         if (NID(data) == sub->keys[0].nid &&
1180                 !net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy,
1181                              data, data_len, rx, buf)) {
1182             rx->ctx.net_idx = sub->net_idx;
1183             rx->sub = sub;
1184             return true;
1185         }
1186 
1187         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1188             continue;
1189         }
1190 
1191         if (NID(data) == sub->keys[1].nid &&
1192                 !net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy,
1193                              data, data_len, rx, buf)) {
1194             rx->new_key = 1U;
1195             rx->ctx.net_idx = sub->net_idx;
1196             rx->sub = sub;
1197             return true;
1198         }
1199     }
1200 
1201     return false;
1202 }
1203 
1204 /* Relaying from advertising to the advertising bearer should only happen
1205  * if the Relay state is set to enabled. Locally originated packets always
1206  * get sent to the advertising bearer. If the packet came in through GATT,
1207  * then we should only relay it if the GATT Proxy state is enabled.
1208  */
relay_to_adv(enum bt_mesh_net_if net_if)1209 static bool relay_to_adv(enum bt_mesh_net_if net_if)
1210 {
1211     switch (net_if) {
1212     case BLE_MESH_NET_IF_LOCAL:
1213         return true;
1214     case BLE_MESH_NET_IF_ADV:
1215         return (bt_mesh_relay_get() == BLE_MESH_RELAY_ENABLED);
1216     case BLE_MESH_NET_IF_PROXY:
1217         return (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED);
1218     default:
1219         return false;
1220     }
1221 }
1222 
bt_mesh_net_relay(struct net_buf_simple * sbuf,struct bt_mesh_net_rx * rx)1223 static void bt_mesh_net_relay(struct net_buf_simple *sbuf,
1224                               struct bt_mesh_net_rx *rx)
1225 {
1226     const uint8_t *enc = NULL, *priv = NULL;
1227     struct net_buf *buf = NULL;
1228     uint8_t nid = 0U, transmit = 0U;
1229 
1230     if (rx->net_if == BLE_MESH_NET_IF_LOCAL) {
1231         /* Locally originated PDUs with TTL=1 will only be delivered
1232          * to local elements as per Mesh Profile 1.0 section 3.4.5.2:
1233          * "The output filter of the interface connected to
1234          * advertising or GATT bearers shall drop all messages with
1235          * TTL value set to 1."
1236          */
1237         if (rx->ctx.recv_ttl == 1U) {
1238             return;
1239         }
1240     } else {
1241         if (rx->ctx.recv_ttl <= 1U) {
1242             return;
1243         }
1244     }
1245 
1246     if (rx->net_if == BLE_MESH_NET_IF_ADV &&
1247             !rx->friend_cred &&
1248             bt_mesh_relay_get() != BLE_MESH_RELAY_ENABLED &&
1249             bt_mesh_gatt_proxy_get() != BLE_MESH_GATT_PROXY_ENABLED) {
1250         return;
1251     }
1252 
1253     BT_DBG("TTL %u CTL %u dst 0x%04x", rx->ctx.recv_ttl, rx->ctl,
1254            rx->ctx.recv_dst);
1255 
1256     /* The Relay Retransmit state is only applied to adv-adv relaying.
1257      * Anything else (like GATT to adv, or locally originated packets)
1258      * use the Network Transmit state.
1259      */
1260     if (rx->net_if == BLE_MESH_NET_IF_ADV && !rx->friend_cred) {
1261         transmit = bt_mesh_relay_retransmit_get();
1262     } else {
1263         transmit = bt_mesh_net_transmit_get();
1264     }
1265 
1266     /**
1267      * When the node tries to relay a Segment ACK message, in this case
1268      * the corresponding segment packets (if exist) can be removed from
1269      * the relay queue.
1270      */
1271 
1272 #if !defined(CONFIG_BLE_MESH_RELAY_ADV_BUF)
1273     buf = bt_mesh_adv_create(BLE_MESH_ADV_DATA, transmit, K_NO_WAIT);
1274 #else
1275     /**
1276      * Check if the number of relay packets in queue is too large, if so
1277      * use minimum relay retransmit value for later relay packets.
1278      */
1279     if (bt_mesh_get_stored_relay_count() >= BLE_MESH_MAX_STORED_RELAY_COUNT) {
1280         transmit = BLE_MESH_TRANSMIT(0, 20);
1281     }
1282     buf = bt_mesh_relay_adv_create(BLE_MESH_ADV_DATA, transmit, K_NO_WAIT);
1283 #endif
1284 
1285     if (!buf) {
1286         BT_INFO("Out of relay buffers");
1287         return;
1288     }
1289 
1290     /* Only decrement TTL for non-locally originated packets */
1291     if (rx->net_if != BLE_MESH_NET_IF_LOCAL) {
1292         /* Leave CTL bit intact */
1293         sbuf->data[1] &= 0x80;
1294         sbuf->data[1] |= rx->ctx.recv_ttl - 1U;
1295     }
1296 
1297     net_buf_add_mem(buf, sbuf->data, sbuf->len);
1298 
1299     enc = rx->sub->keys[rx->sub->kr_flag].enc;
1300     priv = rx->sub->keys[rx->sub->kr_flag].privacy;
1301     nid = rx->sub->keys[rx->sub->kr_flag].nid;
1302 
1303     BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data));
1304 
1305     /* Update NID if RX or RX was with friend credentials */
1306     if (rx->friend_cred) {
1307         buf->data[0] &= 0x80; /* Clear everything except IVI */
1308         buf->data[0] |= nid;
1309     }
1310 
1311     /* We re-encrypt and obfuscate using the received IVI rather than
1312      * the normal TX IVI (which may be different) since the transport
1313      * layer nonce includes the IVI.
1314      */
1315     if (bt_mesh_net_encrypt(enc, &buf->b, BLE_MESH_NET_IVI_RX(rx), false)) {
1316         BT_ERR("Re-encrypting failed");
1317         goto done;
1318     }
1319 
1320     if (bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_RX(rx), priv)) {
1321         BT_ERR("Re-obfuscating failed");
1322         goto done;
1323     }
1324 
1325     /* Sending to the GATT bearer should only happen if GATT Proxy
1326      * is enabled or the message originates from the local node.
1327      */
1328     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1329             (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED ||
1330              rx->friend_cred ||
1331              rx->net_if == BLE_MESH_NET_IF_LOCAL)) {
1332         if (bt_mesh_proxy_server_relay(&buf->b, rx->ctx.recv_dst) &&
1333                 BLE_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) {
1334             goto done;
1335         }
1336     }
1337 
1338     if (relay_to_adv(rx->net_if) || rx->friend_cred) {
1339 #if !defined(CONFIG_BLE_MESH_RELAY_ADV_BUF)
1340         bt_mesh_adv_send(buf, NULL, NULL);
1341 #else
1342         bt_mesh_relay_adv_send(buf, NULL, NULL, rx->ctx.addr, rx->ctx.recv_dst);
1343 #endif
1344     }
1345 
1346 done:
1347     net_buf_unref(buf);
1348 }
1349 
bt_mesh_net_header_parse(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx)1350 void bt_mesh_net_header_parse(struct net_buf_simple *buf,
1351                               struct bt_mesh_net_rx *rx)
1352 {
1353     rx->old_iv = (IVI(buf->data) != (bt_mesh.iv_index & 0x01));
1354     rx->ctl = CTL(buf->data);
1355     rx->ctx.recv_ttl = TTL(buf->data);
1356     rx->seq = SEQ(buf->data);
1357     rx->ctx.addr = SRC(buf->data);
1358     rx->ctx.recv_dst = DST(buf->data);
1359 }
1360 
bt_mesh_net_decode(struct net_buf_simple * data,enum bt_mesh_net_if net_if,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1361 int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if,
1362                        struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
1363 {
1364     if (data->len < BLE_MESH_NET_MIN_PDU_LEN) {
1365         BT_WARN("Dropping too short mesh packet (len %u)", data->len);
1366         BT_WARN("%s", bt_hex(data->data, data->len));
1367         return -EINVAL;
1368     }
1369 
1370     if (net_if == BLE_MESH_NET_IF_ADV && check_dup(data)) {
1371         return -EINVAL;
1372     }
1373 
1374     BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len));
1375 
1376     rx->net_if = net_if;
1377 
1378     if (!net_find_and_decrypt(data->data, data->len, rx, buf)) {
1379         BT_DBG("Unable to find matching net for packet");
1380         return -ENOENT;
1381     }
1382 
1383     /* Initialize AppIdx to a sane value */
1384     rx->ctx.app_idx = BLE_MESH_KEY_UNUSED;
1385 
1386     rx->ctx.recv_ttl = TTL(buf->data);
1387 
1388     /* Default to responding with TTL 0 for non-routed messages */
1389     if (rx->ctx.recv_ttl == 0U) {
1390         rx->ctx.send_ttl = 0U;
1391     } else {
1392         rx->ctx.send_ttl = BLE_MESH_TTL_DEFAULT;
1393     }
1394 
1395     rx->ctl = CTL(buf->data);
1396     rx->seq = SEQ(buf->data);
1397     rx->ctx.recv_dst = DST(buf->data);
1398 
1399     BT_DBG("Decryption successful. Payload len %u", buf->len);
1400 
1401     if (net_if != BLE_MESH_NET_IF_PROXY_CFG &&
1402             rx->ctx.recv_dst == BLE_MESH_ADDR_UNASSIGNED) {
1403         BT_ERR("Destination address is unassigned; dropping packet");
1404         return -EBADMSG;
1405     }
1406 
1407     /* For case MESH/NODE/RLY/BV-01-C, even the DST is RFU, it needs to be forwarded. */
1408 #if !CONFIG_BLE_MESH_BQB_TEST
1409     if (BLE_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) {
1410         BT_ERR("Destination address is RFU; dropping packet 0x%02x", rx->ctx.recv_dst);
1411         return -EBADMSG;
1412     }
1413 #endif
1414 
1415     if (net_if != BLE_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) {
1416         BT_DBG("Dropping locally originated packet");
1417         return -EBADMSG;
1418     }
1419 
1420     BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst,
1421            rx->ctx.recv_ttl);
1422     BT_DBG("PDU: %s", bt_hex(buf->data, buf->len));
1423 
1424     msg_cache_add(rx);
1425 
1426     return 0;
1427 }
1428 
ready_to_recv(void)1429 static bool ready_to_recv(void)
1430 {
1431     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
1432         return true;
1433     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en()) {
1434         if (bt_mesh_provisioner_get_node_count()) {
1435             return true;
1436         }
1437     }
1438 
1439     return false;
1440 }
1441 
ignore_net_msg(uint16_t src,uint16_t dst)1442 static bool ignore_net_msg(uint16_t src, uint16_t dst)
1443 {
1444     if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV)) {
1445         /* When fast provisioning is enabled, the node addr
1446          * message will be sent to the Primary Provisioner,
1447          * which shall not be ignored here.
1448          */
1449         return false;
1450     }
1451 
1452     if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) &&
1453         bt_mesh_is_provisioner_en()) {
1454         /* If the destination address of the message is the element
1455          * address of Provisioner, but Provisioner fails to find the
1456          * node in its provisioning database, then this message will
1457          * be ignored.
1458          */
1459         if (!bt_mesh_provisioner_get_node_with_addr(src)) {
1460             BT_INFO("Not found node address 0x%04x", src);
1461             return true;
1462         }
1463     }
1464     return false;
1465 }
1466 
bt_mesh_net_recv(struct net_buf_simple * data,int8_t rssi,enum bt_mesh_net_if net_if)1467 void bt_mesh_net_recv(struct net_buf_simple *data, int8_t rssi,
1468                       enum bt_mesh_net_if net_if)
1469 {
1470     NET_BUF_SIMPLE_DEFINE(buf, 29);
1471     struct bt_mesh_net_rx rx = { .ctx.recv_rssi = rssi };
1472     struct net_buf_simple_state state = {0};
1473 
1474     BT_DBG("rssi %d net_if %u", rssi, net_if);
1475 
1476     if (!ready_to_recv()) {
1477         return;
1478     }
1479 
1480     if (bt_mesh_net_decode(data, net_if, &rx, &buf)) {
1481         return;
1482     }
1483 
1484     if (ignore_net_msg(rx.ctx.addr, rx.ctx.recv_dst)) {
1485         return;
1486     }
1487 
1488     /* Save the state so the buffer can later be relayed */
1489     net_buf_simple_save(&buf, &state);
1490 
1491     BT_BQB(BLE_MESH_BQB_TEST_LOG_LEVEL_PRIMARY_ID_NODE | BLE_MESH_BQB_TEST_LOG_LEVEL_SUB_ID_NET,
1492            "\nNetRecv: ctl: %d, src: %d, dst: %d, ttl: %d, data: 0x%s",
1493            CTL(buf.data), SRC(buf.data), DST(buf.data), TTL(buf.data),
1494            bt_hex(buf.data + BLE_MESH_NET_HDR_LEN, buf.len - BLE_MESH_NET_HDR_LEN));
1495 
1496     rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) ||
1497                       bt_mesh_elem_find(rx.ctx.recv_dst));
1498 
1499     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1500             net_if == BLE_MESH_NET_IF_PROXY) {
1501         bt_mesh_proxy_server_addr_add(data, rx.ctx.addr);
1502 
1503         if (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_DISABLED &&
1504             !rx.local_match) {
1505             BT_INFO("Proxy is disabled; ignoring message");
1506             return;
1507         }
1508     }
1509 
1510     /* The transport layer has indicated that it has rejected the message,
1511     * but would like to see it again if it is received in the future.
1512     * This can happen if a message is received when the device is in
1513     * Low Power mode, but the message was not encrypted with the friend
1514     * credentials. Remove it from the message cache so that we accept
1515     * it again in the future.
1516     */
1517     if (bt_mesh_trans_recv(&buf, &rx) == -EAGAIN) {
1518         BT_WARN("Removing rejected message from Network Message Cache");
1519         msg_cache[rx.msg_cache_idx].src = BLE_MESH_ADDR_UNASSIGNED;
1520         /* Rewind the next index now that we're not using this entry */
1521         msg_cache_next = rx.msg_cache_idx;
1522     }
1523 
1524     /* Relay if this was a group/virtual address, or if the destination
1525      * was neither a local element nor an LPN we're Friends for.
1526      */
1527     if (!BLE_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) ||
1528         (!rx.local_match && !rx.friend_match
1529 #if CONFIG_BLE_MESH_NOT_RELAY_REPLAY_MSG
1530         && !rx.replay_msg
1531 #endif
1532         )) {
1533         net_buf_simple_restore(&buf, &state);
1534         bt_mesh_net_relay(&buf, &rx);
1535     }
1536 }
1537 
ivu_refresh(struct k_work * work)1538 static void ivu_refresh(struct k_work *work)
1539 {
1540     bt_mesh.ivu_duration += BLE_MESH_IVU_HOURS;
1541 
1542     BT_INFO("%s for %u hour%s",
1543            bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS) ?
1544            "IVU in Progress" : "IVU Normal mode",
1545            bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s");
1546 
1547     if (bt_mesh.ivu_duration < BLE_MESH_IVU_MIN_HOURS) {
1548         if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1549             bt_mesh_store_iv(true);
1550         }
1551 
1552         k_delayed_work_submit(&bt_mesh.ivu_timer, BLE_MESH_IVU_TIMEOUT);
1553         return;
1554     }
1555 
1556     if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
1557         bt_mesh_beacon_ivu_initiator(true);
1558         bt_mesh_net_iv_update(bt_mesh.iv_index, false);
1559     } else if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1560         bt_mesh_store_iv(true);
1561     }
1562 }
1563 
bt_mesh_net_start(void)1564 void bt_mesh_net_start(void)
1565 {
1566     if (bt_mesh_beacon_get() == BLE_MESH_BEACON_ENABLED) {
1567         bt_mesh_beacon_enable();
1568     } else {
1569         bt_mesh_beacon_disable();
1570     }
1571 
1572     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1573             bt_mesh_gatt_proxy_get() != BLE_MESH_GATT_PROXY_NOT_SUPPORTED) {
1574         bt_mesh_proxy_server_gatt_enable();
1575         bt_mesh_adv_update();
1576     }
1577 
1578 #if defined(CONFIG_BLE_MESH_USE_DUPLICATE_SCAN)
1579     /* Add Mesh beacon type (Secure Network Beacon) to the exceptional list */
1580     bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_SUB_CODE_ADD,
1581                                     BLE_MESH_EXCEP_LIST_TYPE_MESH_BEACON, NULL);
1582 #endif
1583 
1584     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER)) {
1585         /* TODO: Enable duplicate scan in Low Power Mode */
1586         bt_mesh_lpn_init();
1587     } else {
1588         bt_mesh_scan_enable();
1589     }
1590 
1591     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
1592         bt_mesh_friend_init();
1593     }
1594 
1595     if (IS_ENABLED(CONFIG_BLE_MESH_PROV)) {
1596         uint16_t net_idx = bt_mesh.sub[0].net_idx;
1597         uint16_t addr = bt_mesh_primary_addr();
1598         uint32_t iv_index = bt_mesh.iv_index;
1599         uint8_t flags = (uint8_t)bt_mesh.sub[0].kr_flag;
1600         const uint8_t *net_key = bt_mesh.sub[0].keys[flags].net;
1601         if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
1602             flags |= BLE_MESH_NET_FLAG_IVU;
1603         }
1604 
1605         bt_mesh_prov_complete(net_idx, net_key, addr, flags, iv_index);
1606     }
1607 }
1608 
bt_mesh_net_init(void)1609 void bt_mesh_net_init(void)
1610 {
1611     k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh);
1612 
1613     k_work_init(&bt_mesh.local_work, bt_mesh_net_local);
1614 }
1615 
bt_mesh_net_reset(void)1616 void bt_mesh_net_reset(void)
1617 {
1618     k_delayed_work_cancel(&bt_mesh.ivu_timer);
1619 
1620 #if FRIEND_CRED_COUNT > 0
1621     memset(friend_cred, 0, sizeof(friend_cred));
1622 #endif
1623 
1624     memset(msg_cache, 0, sizeof(msg_cache));
1625     msg_cache_next = 0U;
1626 
1627     memset(dup_cache, 0, sizeof(dup_cache));
1628     dup_cache_next = 0U;
1629 
1630     bt_mesh.iv_index = 0U;
1631     bt_mesh.seq = 0U;
1632 }
1633 
1634 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_net_deinit(void)1635 void bt_mesh_net_deinit(void)
1636 {
1637     bt_mesh_net_reset();
1638 
1639     k_delayed_work_free(&bt_mesh.ivu_timer);
1640 
1641     k_work_init(&bt_mesh.local_work, NULL);
1642 
1643     /* Local queue uses a while loop, currently no need
1644      * to handle this.
1645      */
1646 }
1647 #endif /* CONFIG_BLE_MESH_DEINIT */
1648