1 /*  Bluetooth Mesh */
2 
3 /*
4  * Copyright (c) 2017 Intel Corporation
5  * Additional Copyright (c) 2018 Espressif Systems (Shanghai) PTE 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             BT_WARN("Performing IV Index Recovery");
678             (void)memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
679             bt_mesh.iv_index = iv_index;
680             bt_mesh.seq = 0U;
681             goto do_update;
682         }
683 
684         if (iv_index == bt_mesh.iv_index + 1 && !iv_update) {
685             BT_WARN("Ignoring new index in normal mode");
686             return false;
687         }
688 
689         if (!iv_update) {
690             /* Nothing to do */
691             BT_DBG("Already in Normal state");
692             return false;
693         }
694     }
695 
696     if (!(IS_ENABLED(CONFIG_BLE_MESH_IV_UPDATE_TEST) &&
697             bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_TEST))) {
698         if (bt_mesh.ivu_duration < BLE_MESH_IVU_MIN_HOURS) {
699             BT_WARN("IV Update before minimum duration");
700             return false;
701         }
702     }
703 
704     /* Defer change to Normal Operation if there are pending acks */
705     if (!iv_update && bt_mesh_tx_in_progress()) {
706         BT_WARN("IV Update deferred because of pending transfer");
707         bt_mesh_atomic_set_bit(bt_mesh.flags, BLE_MESH_IVU_PENDING);
708         return false;
709     }
710 
711 do_update:
712     bt_mesh_atomic_set_bit_to(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS, iv_update);
713     bt_mesh.ivu_duration = 0U;
714 
715     if (iv_update) {
716         bt_mesh.iv_index = iv_index;
717         BT_INFO("IV Update state entered. New index 0x%08x",
718                bt_mesh.iv_index);
719 
720         bt_mesh_rpl_reset();
721     } else {
722         BT_INFO("Normal mode entered");
723         bt_mesh.seq = 0U;
724     }
725 
726     k_delayed_work_submit(&bt_mesh.ivu_timer, BLE_MESH_IVU_TIMEOUT);
727 
728     size_t subnet_size = bt_mesh_rx_netkey_size();
729 
730     for (i = 0; i < subnet_size; i++) {
731         struct bt_mesh_subnet *sub = bt_mesh_rx_netkey_get(i);
732         if (sub && sub->net_idx != BLE_MESH_KEY_UNUSED) {
733             bt_mesh_net_beacon_update(sub);
734         }
735     }
736 
737     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
738         bt_mesh_store_iv(false);
739     }
740 
741     return true;
742 }
743 
bt_mesh_primary_subnet_exist(void)744 bool bt_mesh_primary_subnet_exist(void)
745 {
746     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
747         if (bt_mesh_subnet_get(BLE_MESH_KEY_PRIMARY)) {
748             return true;
749         }
750     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en()) {
751         if (bt_mesh_provisioner_subnet_get(BLE_MESH_KEY_PRIMARY)) {
752             return true;
753         }
754     }
755 
756     return false;
757 }
758 
bt_mesh_next_seq(void)759 uint32_t bt_mesh_next_seq(void)
760 {
761     uint32_t seq = bt_mesh.seq++;
762 
763     if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
764         bt_mesh_store_seq();
765     }
766 
767     if (!bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS) &&
768             bt_mesh.seq > IV_UPDATE_SEQ_LIMIT &&
769             bt_mesh_primary_subnet_exist()) {
770         bt_mesh_beacon_ivu_initiator(true);
771         bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
772         bt_mesh_net_sec_update(NULL);
773     }
774 
775     return seq;
776 }
777 
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)778 int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf,
779                        bool new_key, const struct bt_mesh_send_cb *cb,
780                        void *cb_data)
781 {
782     const uint8_t *enc = NULL, *priv = NULL;
783     uint32_t seq = 0U;
784     uint16_t dst = 0U;
785     int err = 0;
786 
787     BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key,
788            buf->len);
789 
790     enc = sub->keys[new_key].enc;
791     priv = sub->keys[new_key].privacy;
792 
793     err = bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
794     if (err) {
795         BT_ERR("De-obfuscate failed (err %d)", err);
796         return err;
797     }
798 
799     err = bt_mesh_net_decrypt(enc, &buf->b, BLE_MESH_NET_IVI_TX, false);
800     if (err) {
801         BT_ERR("Decrypt failed (err %d)", err);
802         return err;
803     }
804 
805     /* Update with a new sequence number */
806     seq = bt_mesh_next_seq();
807     sys_put_be24(seq, &buf->data[2]);
808 
809     /* Get destination, in case it's a proxy client */
810     dst = DST(buf->data);
811 
812     err = bt_mesh_net_encrypt(enc, &buf->b, BLE_MESH_NET_IVI_TX, false);
813     if (err) {
814         BT_ERR("Encrypt failed (err %d)", err);
815         return err;
816     }
817 
818     err = bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
819     if (err) {
820         BT_ERR("Obfuscate failed (err %d)", err);
821         return err;
822     }
823 
824     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
825         bt_mesh_proxy_server_relay(&buf->b, dst) &&
826         BLE_MESH_ADDR_IS_UNICAST(dst)) {
827         send_cb_finalize(cb, cb_data);
828         return 0;
829     }
830 
831     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_CLIENT) &&
832         bt_mesh_proxy_client_relay(&buf->b, dst)) {
833         send_cb_finalize(cb, cb_data);
834         return 0;
835     }
836 
837     bt_mesh_adv_send(buf, cb, cb_data);
838     return 0;
839 }
840 
bt_mesh_net_local(struct k_work * work)841 static void bt_mesh_net_local(struct k_work *work)
842 {
843     struct net_buf *buf = NULL;
844 
845     while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
846         BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
847         bt_mesh_net_recv(&buf->b, 0, BLE_MESH_NET_IF_LOCAL);
848         net_buf_unref(buf);
849     }
850 }
851 
bt_mesh_net_encode(struct bt_mesh_net_tx * tx,struct net_buf_simple * buf,bool proxy)852 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf,
853                        bool proxy)
854 {
855     const bool ctl = (tx->ctx->app_idx == BLE_MESH_KEY_UNUSED);
856     const uint8_t *enc = NULL, *priv = NULL;
857     uint8_t nid = 0U;
858     int err = 0;
859 
860     if (ctl && net_buf_simple_tailroom(buf) < BLE_MESH_MIC_LONG) {
861         BT_ERR("Insufficient MIC space for CTL PDU");
862         return -EINVAL;
863     } else if (net_buf_simple_tailroom(buf) < BLE_MESH_MIC_SHORT) {
864         BT_ERR("Insufficient MIC space for PDU");
865         return -EINVAL;
866     }
867 
868     BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x",
869            tx->src, tx->ctx->addr, ctl, bt_mesh.seq);
870 
871     net_buf_simple_push_be16(buf, tx->ctx->addr);
872     net_buf_simple_push_be16(buf, tx->src);
873 
874     net_buf_simple_push_be24(buf, bt_mesh_next_seq());
875 
876     if (ctl) {
877         net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80);
878     } else {
879         net_buf_simple_push_u8(buf, tx->ctx->send_ttl);
880     }
881 
882     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER) && tx->friend_cred) {
883         if (friend_cred_get(tx->sub, BLE_MESH_ADDR_UNASSIGNED,
884                             &nid, &enc, &priv)) {
885             BT_WARN("Falling back to master credentials");
886 
887             tx->friend_cred = 0U;
888 
889             nid = tx->sub->keys[tx->sub->kr_flag].nid;
890             enc = tx->sub->keys[tx->sub->kr_flag].enc;
891             priv = tx->sub->keys[tx->sub->kr_flag].privacy;
892         }
893     } else {
894         tx->friend_cred = 0U;
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 
900     net_buf_simple_push_u8(buf, (nid | (BLE_MESH_NET_IVI_TX & 1) << 7));
901 
902     err = bt_mesh_net_encrypt(enc, buf, BLE_MESH_NET_IVI_TX, proxy);
903     if (err) {
904         return err;
905     }
906 
907     return bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_TX, priv);
908 }
909 
bt_mesh_net_send(struct bt_mesh_net_tx * tx,struct net_buf * buf,const struct bt_mesh_send_cb * cb,void * cb_data)910 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf,
911                      const struct bt_mesh_send_cb *cb, void *cb_data)
912 {
913     int err = 0;
914 
915     BT_DBG("src 0x%04x dst 0x%04x len %u headroom %u tailroom %u",
916            tx->src, tx->ctx->addr, buf->len, net_buf_headroom(buf),
917            net_buf_tailroom(buf));
918     BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len));
919     BT_DBG("Seq 0x%06x", bt_mesh.seq);
920 
921     if (tx->ctx->send_ttl == BLE_MESH_TTL_DEFAULT) {
922         tx->ctx->send_ttl = bt_mesh_default_ttl_get();
923     }
924 
925     err = bt_mesh_net_encode(tx, &buf->b, false);
926     if (err) {
927         goto done;
928     }
929 
930     /* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2:
931      * "The output filter of the interface connected to advertising or
932      * GATT bearers shall drop all messages with TTL value set to 1."
933      */
934     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
935             tx->ctx->send_ttl != 1U) {
936         if (bt_mesh_proxy_server_relay(&buf->b, tx->ctx->addr) &&
937                 BLE_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
938             /* Notify completion if this only went
939              * through the Mesh Proxy.
940              */
941             send_cb_finalize(cb, cb_data);
942 
943             err = 0;
944             goto done;
945         }
946     }
947 
948     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_CLIENT) &&
949             tx->ctx->send_ttl != 1U) {
950         if (bt_mesh_proxy_client_relay(&buf->b, tx->ctx->addr)) {
951             /* If Proxy Client succeeds to send messages with GATT bearer,
952              * we can directly finish here. And if not, which means no
953              * connection has been created with Proxy Client, here we will
954              * use advertising bearer for the messages.
955              */
956             send_cb_finalize(cb, cb_data);
957 
958             err = 0;
959             goto done;
960         }
961     }
962 
963     /* Deliver to local network interface if necessary */
964     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned() &&
965         (bt_mesh_fixed_group_match(tx->ctx->addr) ||
966             bt_mesh_elem_find(tx->ctx->addr))) {
967         if (cb && cb->start) {
968             cb->start(0, 0, cb_data);
969         }
970         net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf));
971         if (cb && cb->end) {
972             cb->end(0, cb_data);
973         }
974         k_work_submit(&bt_mesh.local_work);
975     } else if (tx->ctx->send_ttl != 1U) {
976         /* Deliver to the advertising network interface. Mesh spec
977          * 3.4.5.2: "The output filter of the interface connected to
978          * advertising or GATT bearers shall drop all messages with
979          * TTL value set to 1."
980          */
981         bt_mesh_adv_send(buf, cb, cb_data);
982     }
983 
984 done:
985     net_buf_unref(buf);
986     return err;
987 }
988 
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])989 static bool auth_match(struct bt_mesh_subnet_keys *keys,
990                        const uint8_t net_id[8], uint8_t flags,
991                        uint32_t iv_index, const uint8_t auth[8])
992 {
993     uint8_t net_auth[8] = {0};
994 
995     if (memcmp(net_id, keys->net_id, 8)) {
996         return false;
997     }
998 
999     bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index,
1000                         net_auth);
1001 
1002     if (memcmp(auth, net_auth, 8)) {
1003         BT_WARN("Authentication Value %s != %s",
1004                 bt_hex(auth, 8), bt_hex(net_auth, 8));
1005         return false;
1006     }
1007 
1008     return true;
1009 }
1010 
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)1011 struct bt_mesh_subnet *bt_mesh_subnet_find(const uint8_t net_id[8], uint8_t flags,
1012                                            uint32_t iv_index, const uint8_t auth[8],
1013                                            bool *new_key)
1014 {
1015     size_t subnet_size = 0U;
1016     int i;
1017 
1018     subnet_size = bt_mesh_rx_netkey_size();
1019 
1020     for (i = 0; i < subnet_size; i++) {
1021         struct bt_mesh_subnet *sub = bt_mesh_rx_netkey_get(i);
1022 
1023         if (sub == NULL || sub->net_idx == BLE_MESH_KEY_UNUSED) {
1024             continue;
1025         }
1026 
1027         if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) {
1028             *new_key = false;
1029             return sub;
1030         }
1031 
1032         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1033             continue;
1034         }
1035 
1036         if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) {
1037             *new_key = true;
1038             return sub;
1039         }
1040     }
1041 
1042     return NULL;
1043 }
1044 
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)1045 static int net_decrypt(struct bt_mesh_subnet *sub, const uint8_t *enc,
1046                        const uint8_t *priv, const uint8_t *data,
1047                        size_t data_len, struct bt_mesh_net_rx *rx,
1048                        struct net_buf_simple *buf)
1049 {
1050     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1051     BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index);
1052 
1053     rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01));
1054 
1055     net_buf_simple_reset(buf);
1056     memcpy(net_buf_simple_add(buf, data_len), data, data_len);
1057 
1058     if (bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_RX(rx), priv)) {
1059         return -ENOENT;
1060     }
1061 
1062     rx->ctx.addr = SRC(buf->data);
1063     if (!BLE_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) {
1064         BT_INFO("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr);
1065         return -EINVAL;
1066     }
1067 
1068     if (rx->net_if == BLE_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) {
1069         BT_DBG("Duplicate found in Network Message Cache");
1070         return -EALREADY;
1071     }
1072 
1073     BT_DBG("src 0x%04x", rx->ctx.addr);
1074 
1075     if (IS_ENABLED(CONFIG_BLE_MESH_PROXY) &&
1076             rx->net_if == BLE_MESH_NET_IF_PROXY_CFG) {
1077         return bt_mesh_net_decrypt(enc, buf, BLE_MESH_NET_IVI_RX(rx),
1078                                    true);
1079     }
1080 
1081     return bt_mesh_net_decrypt(enc, buf, BLE_MESH_NET_IVI_RX(rx), false);
1082 }
1083 
1084 #if (defined(CONFIG_BLE_MESH_LOW_POWER) || \
1085      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)1086 static int friend_decrypt(struct bt_mesh_subnet *sub, const uint8_t *data,
1087                           size_t data_len, struct bt_mesh_net_rx *rx,
1088                           struct net_buf_simple *buf)
1089 {
1090     int i;
1091 
1092     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1093 
1094     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
1095         struct friend_cred *cred = &friend_cred[i];
1096 
1097         if (cred->net_idx != sub->net_idx) {
1098             continue;
1099         }
1100 
1101         if (NID(data) == cred->cred[0].nid &&
1102                 !net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy,
1103                              data, data_len, rx, buf)) {
1104             return 0;
1105         }
1106 
1107         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1108             continue;
1109         }
1110 
1111         if (NID(data) == cred->cred[1].nid &&
1112                 !net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy,
1113                              data, data_len, rx, buf)) {
1114             rx->new_key = 1U;
1115             return 0;
1116         }
1117     }
1118 
1119     return -ENOENT;
1120 }
1121 #endif
1122 
net_find_and_decrypt(const uint8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1123 static bool net_find_and_decrypt(const uint8_t *data, size_t data_len,
1124                                  struct bt_mesh_net_rx *rx,
1125                                  struct net_buf_simple *buf)
1126 {
1127     struct bt_mesh_subnet *sub = NULL;
1128     size_t array_size = 0U;
1129     int i;
1130 
1131     BT_DBG("%s", __func__);
1132 
1133     array_size = bt_mesh_rx_netkey_size();
1134 
1135     for (i = 0; i < array_size; i++) {
1136         sub = bt_mesh_rx_netkey_get(i);
1137         if (!sub) {
1138             BT_DBG("Subnet not found");
1139             continue;
1140         }
1141 
1142         if (sub->net_idx == BLE_MESH_KEY_UNUSED) {
1143             continue;
1144         }
1145 
1146 #if (defined(CONFIG_BLE_MESH_LOW_POWER) || defined(CONFIG_BLE_MESH_FRIEND))
1147         if (!friend_decrypt(sub, data, data_len, rx, buf)) {
1148             rx->friend_cred = 1;
1149             rx->ctx.net_idx = sub->net_idx;
1150             rx->sub = sub;
1151             return true;
1152         }
1153 #endif
1154 
1155         if (NID(data) == sub->keys[0].nid &&
1156                 !net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy,
1157                              data, data_len, rx, buf)) {
1158             rx->ctx.net_idx = sub->net_idx;
1159             rx->sub = sub;
1160             return true;
1161         }
1162 
1163         if (sub->kr_phase == BLE_MESH_KR_NORMAL) {
1164             continue;
1165         }
1166 
1167         if (NID(data) == sub->keys[1].nid &&
1168                 !net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy,
1169                              data, data_len, rx, buf)) {
1170             rx->new_key = 1U;
1171             rx->ctx.net_idx = sub->net_idx;
1172             rx->sub = sub;
1173             return true;
1174         }
1175     }
1176 
1177     return false;
1178 }
1179 
1180 /* Relaying from advertising to the advertising bearer should only happen
1181  * if the Relay state is set to enabled. Locally originated packets always
1182  * get sent to the advertising bearer. If the packet came in through GATT,
1183  * then we should only relay it if the GATT Proxy state is enabled.
1184  */
relay_to_adv(enum bt_mesh_net_if net_if)1185 static bool relay_to_adv(enum bt_mesh_net_if net_if)
1186 {
1187     switch (net_if) {
1188     case BLE_MESH_NET_IF_LOCAL:
1189         return true;
1190     case BLE_MESH_NET_IF_ADV:
1191         return (bt_mesh_relay_get() == BLE_MESH_RELAY_ENABLED);
1192     case BLE_MESH_NET_IF_PROXY:
1193         return (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED);
1194     default:
1195         return false;
1196     }
1197 }
1198 
bt_mesh_net_relay(struct net_buf_simple * sbuf,struct bt_mesh_net_rx * rx)1199 static void bt_mesh_net_relay(struct net_buf_simple *sbuf,
1200                               struct bt_mesh_net_rx *rx)
1201 {
1202     const uint8_t *enc = NULL, *priv = NULL;
1203     struct net_buf *buf = NULL;
1204     uint8_t nid = 0U, transmit = 0U;
1205 
1206     if (rx->net_if == BLE_MESH_NET_IF_LOCAL) {
1207         /* Locally originated PDUs with TTL=1 will only be delivered
1208          * to local elements as per Mesh Profile 1.0 section 3.4.5.2:
1209          * "The output filter of the interface connected to
1210          * advertising or GATT bearers shall drop all messages with
1211          * TTL value set to 1."
1212          */
1213         if (rx->ctx.recv_ttl == 1U) {
1214             return;
1215         }
1216     } else {
1217         if (rx->ctx.recv_ttl <= 1U) {
1218             return;
1219         }
1220     }
1221 
1222     if (rx->net_if == BLE_MESH_NET_IF_ADV &&
1223             bt_mesh_relay_get() != BLE_MESH_RELAY_ENABLED &&
1224             bt_mesh_gatt_proxy_get() != BLE_MESH_GATT_PROXY_ENABLED) {
1225         return;
1226     }
1227 
1228     BT_DBG("TTL %u CTL %u dst 0x%04x", rx->ctx.recv_ttl, rx->ctl,
1229            rx->ctx.recv_dst);
1230 
1231     /* The Relay Retransmit state is only applied to adv-adv relaying.
1232      * Anything else (like GATT to adv, or locally originated packets)
1233      * use the Network Transmit state.
1234      */
1235     if (rx->net_if == BLE_MESH_NET_IF_ADV) {
1236         transmit = bt_mesh_relay_retransmit_get();
1237     } else {
1238         transmit = bt_mesh_net_transmit_get();
1239     }
1240 
1241     /**
1242      * When the node tries to relay a Segment ACK message, in this case
1243      * the corresponding segment packets (if exist) can be removed from
1244      * the relay queue.
1245      */
1246 
1247 #if !defined(CONFIG_BLE_MESH_RELAY_ADV_BUF)
1248     buf = bt_mesh_adv_create(BLE_MESH_ADV_DATA, transmit, K_NO_WAIT);
1249 #else
1250     /**
1251      * Check if the number of relay packets in queue is too large, if so
1252      * use minimum relay retransmit value for later relay packets.
1253      */
1254     if (bt_mesh_get_stored_relay_count() >= BLE_MESH_MAX_STORED_RELAY_COUNT) {
1255         transmit = BLE_MESH_TRANSMIT(0, 20);
1256     }
1257     buf = bt_mesh_relay_adv_create(BLE_MESH_ADV_DATA, transmit, K_NO_WAIT);
1258 #endif
1259 
1260     if (!buf) {
1261         BT_ERR("Out of relay buffers");
1262         return;
1263     }
1264 
1265     /* Only decrement TTL for non-locally originated packets */
1266     if (rx->net_if != BLE_MESH_NET_IF_LOCAL) {
1267         /* Leave CTL bit intact */
1268         sbuf->data[1] &= 0x80;
1269         sbuf->data[1] |= rx->ctx.recv_ttl - 1U;
1270     }
1271 
1272     net_buf_add_mem(buf, sbuf->data, sbuf->len);
1273 
1274     enc = rx->sub->keys[rx->sub->kr_flag].enc;
1275     priv = rx->sub->keys[rx->sub->kr_flag].privacy;
1276     nid = rx->sub->keys[rx->sub->kr_flag].nid;
1277 
1278     BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data));
1279 
1280     /* Update NID if RX or RX was with friend credentials */
1281     if (rx->friend_cred) {
1282         buf->data[0] &= 0x80; /* Clear everything except IVI */
1283         buf->data[0] |= nid;
1284     }
1285 
1286     /* We re-encrypt and obfuscate using the received IVI rather than
1287      * the normal TX IVI (which may be different) since the transport
1288      * layer nonce includes the IVI.
1289      */
1290     if (bt_mesh_net_encrypt(enc, &buf->b, BLE_MESH_NET_IVI_RX(rx), false)) {
1291         BT_ERR("Re-encrypting failed");
1292         goto done;
1293     }
1294 
1295     if (bt_mesh_net_obfuscate(buf->data, BLE_MESH_NET_IVI_RX(rx), priv)) {
1296         BT_ERR("Re-obfuscating failed");
1297         goto done;
1298     }
1299 
1300     /* Sending to the GATT bearer should only happen if GATT Proxy
1301      * is enabled or the message originates from the local node.
1302      */
1303     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1304             (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_ENABLED ||
1305              rx->net_if == BLE_MESH_NET_IF_LOCAL)) {
1306         if (bt_mesh_proxy_server_relay(&buf->b, rx->ctx.recv_dst) &&
1307                 BLE_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) {
1308             goto done;
1309         }
1310     }
1311 
1312     if (relay_to_adv(rx->net_if)) {
1313 #if !defined(CONFIG_BLE_MESH_RELAY_ADV_BUF)
1314         bt_mesh_adv_send(buf, NULL, NULL);
1315 #else
1316         bt_mesh_relay_adv_send(buf, NULL, NULL, rx->ctx.addr, rx->ctx.recv_dst);
1317 #endif
1318     }
1319 
1320 done:
1321     net_buf_unref(buf);
1322 }
1323 
bt_mesh_net_header_parse(struct net_buf_simple * buf,struct bt_mesh_net_rx * rx)1324 void bt_mesh_net_header_parse(struct net_buf_simple *buf,
1325                               struct bt_mesh_net_rx *rx)
1326 {
1327     rx->old_iv = (IVI(buf->data) != (bt_mesh.iv_index & 0x01));
1328     rx->ctl = CTL(buf->data);
1329     rx->ctx.recv_ttl = TTL(buf->data);
1330     rx->seq = SEQ(buf->data);
1331     rx->ctx.addr = SRC(buf->data);
1332     rx->ctx.recv_dst = DST(buf->data);
1333 }
1334 
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)1335 int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if,
1336                        struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
1337 {
1338     if (data->len < BLE_MESH_NET_MIN_PDU_LEN) {
1339         BT_WARN("Dropping too short mesh packet (len %u)", data->len);
1340         BT_WARN("%s", bt_hex(data->data, data->len));
1341         return -EINVAL;
1342     }
1343 
1344     if (net_if == BLE_MESH_NET_IF_ADV && check_dup(data)) {
1345         return -EINVAL;
1346     }
1347 
1348     BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len));
1349 
1350     rx->net_if = net_if;
1351 
1352     if (!net_find_and_decrypt(data->data, data->len, rx, buf)) {
1353         BT_DBG("Unable to find matching net for packet");
1354         return -ENOENT;
1355     }
1356 
1357     /* Initialize AppIdx to a sane value */
1358     rx->ctx.app_idx = BLE_MESH_KEY_UNUSED;
1359 
1360     rx->ctx.recv_ttl = TTL(buf->data);
1361 
1362     /* Default to responding with TTL 0 for non-routed messages */
1363     if (rx->ctx.recv_ttl == 0U) {
1364         rx->ctx.send_ttl = 0U;
1365     } else {
1366         rx->ctx.send_ttl = BLE_MESH_TTL_DEFAULT;
1367     }
1368 
1369     rx->ctl = CTL(buf->data);
1370     rx->seq = SEQ(buf->data);
1371     rx->ctx.recv_dst = DST(buf->data);
1372 
1373     BT_DBG("Decryption successful. Payload len %u", buf->len);
1374 
1375     if (net_if != BLE_MESH_NET_IF_PROXY_CFG &&
1376             rx->ctx.recv_dst == BLE_MESH_ADDR_UNASSIGNED) {
1377         BT_ERR("Destination address is unassigned; dropping packet");
1378         return -EBADMSG;
1379     }
1380 
1381     if (BLE_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) {
1382         BT_ERR("Destination address is RFU; dropping packet");
1383         return -EBADMSG;
1384     }
1385 
1386     if (net_if != BLE_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) {
1387         BT_DBG("Dropping locally originated packet");
1388         return -EBADMSG;
1389     }
1390 
1391     BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst,
1392            rx->ctx.recv_ttl);
1393     BT_DBG("PDU: %s", bt_hex(buf->data, buf->len));
1394 
1395     msg_cache_add(rx);
1396 
1397     return 0;
1398 }
1399 
ready_to_recv(void)1400 static bool ready_to_recv(void)
1401 {
1402     if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
1403         return true;
1404     } else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en()) {
1405         if (bt_mesh_provisioner_get_node_count()) {
1406             return true;
1407         }
1408     }
1409 
1410     return false;
1411 }
1412 
ignore_net_msg(uint16_t src,uint16_t dst)1413 static bool ignore_net_msg(uint16_t src, uint16_t dst)
1414 {
1415     if (IS_ENABLED(CONFIG_BLE_MESH_FAST_PROV)) {
1416         /* When fast provisioning is enabled, the node addr
1417          * message will be sent to the Primary Provisioner,
1418          * which shall not be ignored here.
1419          */
1420         return false;
1421     }
1422 
1423     if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) &&
1424         bt_mesh_is_provisioner_en() &&
1425         BLE_MESH_ADDR_IS_UNICAST(dst) &&
1426         bt_mesh_elem_find(dst)) {
1427         /* If the destination address of the message is the element
1428          * address of Provisioner, but Provisioner fails to find the
1429          * node in its provisioning database, then this message will
1430          * be ignored.
1431          */
1432         if (!bt_mesh_provisioner_get_node_with_addr(src)) {
1433             BT_INFO("Not found node address 0x%04x", src);
1434             return true;
1435         }
1436     }
1437     return false;
1438 }
1439 
bt_mesh_net_recv(struct net_buf_simple * data,int8_t rssi,enum bt_mesh_net_if net_if)1440 void bt_mesh_net_recv(struct net_buf_simple *data, int8_t rssi,
1441                       enum bt_mesh_net_if net_if)
1442 {
1443     NET_BUF_SIMPLE_DEFINE(buf, 29);
1444     struct bt_mesh_net_rx rx = { .ctx.recv_rssi = rssi };
1445     struct net_buf_simple_state state = {0};
1446 
1447     BT_DBG("rssi %d net_if %u", rssi, net_if);
1448 
1449     if (!ready_to_recv()) {
1450         return;
1451     }
1452 
1453     if (bt_mesh_net_decode(data, net_if, &rx, &buf)) {
1454         return;
1455     }
1456 
1457     if (ignore_net_msg(rx.ctx.addr, rx.ctx.recv_dst)) {
1458         return;
1459     }
1460 
1461     /* Save the state so the buffer can later be relayed */
1462     net_buf_simple_save(&buf, &state);
1463 
1464     rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) ||
1465                       bt_mesh_elem_find(rx.ctx.recv_dst));
1466 
1467     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1468             net_if == BLE_MESH_NET_IF_PROXY) {
1469         bt_mesh_proxy_server_addr_add(data, rx.ctx.addr);
1470 
1471         if (bt_mesh_gatt_proxy_get() == BLE_MESH_GATT_PROXY_DISABLED &&
1472             !rx.local_match) {
1473             BT_INFO("Proxy is disabled; ignoring message");
1474             return;
1475         }
1476     }
1477 
1478     /* The transport layer has indicated that it has rejected the message,
1479     * but would like to see it again if it is received in the future.
1480     * This can happen if a message is received when the device is in
1481     * Low Power mode, but the message was not encrypted with the friend
1482     * credentials. Remove it from the message cache so that we accept
1483     * it again in the future.
1484     */
1485     if (bt_mesh_trans_recv(&buf, &rx) == -EAGAIN) {
1486         BT_WARN("Removing rejected message from Network Message Cache");
1487         msg_cache[rx.msg_cache_idx].src = BLE_MESH_ADDR_UNASSIGNED;
1488         /* Rewind the next index now that we're not using this entry */
1489         msg_cache_next = rx.msg_cache_idx;
1490     }
1491 
1492     /* Relay if this was a group/virtual address, or if the destination
1493      * was neither a local element nor an LPN we're Friends for.
1494      */
1495     if (!BLE_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) ||
1496             (!rx.local_match && !rx.friend_match)) {
1497         net_buf_simple_restore(&buf, &state);
1498         bt_mesh_net_relay(&buf, &rx);
1499     }
1500 }
1501 
ivu_refresh(struct k_work * work)1502 static void ivu_refresh(struct k_work *work)
1503 {
1504     bt_mesh.ivu_duration += BLE_MESH_IVU_HOURS;
1505 
1506     BT_INFO("%s for %u hour%s",
1507            bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS) ?
1508            "IVU in Progress" : "IVU Normal mode",
1509            bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s");
1510 
1511     if (bt_mesh.ivu_duration < BLE_MESH_IVU_MIN_HOURS) {
1512         if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1513             bt_mesh_store_iv(true);
1514         }
1515 
1516         k_delayed_work_submit(&bt_mesh.ivu_timer, BLE_MESH_IVU_TIMEOUT);
1517         return;
1518     }
1519 
1520     if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
1521         bt_mesh_beacon_ivu_initiator(true);
1522         bt_mesh_net_iv_update(bt_mesh.iv_index, false);
1523     } else if (IS_ENABLED(CONFIG_BLE_MESH_SETTINGS)) {
1524         bt_mesh_store_iv(true);
1525     }
1526 }
1527 
bt_mesh_net_start(void)1528 void bt_mesh_net_start(void)
1529 {
1530     if (bt_mesh_beacon_get() == BLE_MESH_BEACON_ENABLED) {
1531         bt_mesh_beacon_enable();
1532     } else {
1533         bt_mesh_beacon_disable();
1534     }
1535 
1536     if (IS_ENABLED(CONFIG_BLE_MESH_GATT_PROXY_SERVER) &&
1537             bt_mesh_gatt_proxy_get() != BLE_MESH_GATT_PROXY_NOT_SUPPORTED) {
1538         bt_mesh_proxy_server_gatt_enable();
1539         bt_mesh_adv_update();
1540     }
1541 
1542 #if defined(CONFIG_BLE_MESH_USE_DUPLICATE_SCAN)
1543     /* Add Mesh beacon type (Secure Network Beacon) to the exceptional list */
1544     bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_ADD,
1545                                     BLE_MESH_EXCEP_INFO_MESH_BEACON, NULL);
1546 #endif
1547 
1548     if (IS_ENABLED(CONFIG_BLE_MESH_LOW_POWER)) {
1549         /* TODO: Enable duplicate scan in Low Power Mode */
1550         bt_mesh_lpn_init();
1551     } else {
1552         bt_mesh_scan_enable();
1553     }
1554 
1555     if (IS_ENABLED(CONFIG_BLE_MESH_FRIEND)) {
1556         bt_mesh_friend_init();
1557     }
1558 
1559     if (IS_ENABLED(CONFIG_BLE_MESH_PROV)) {
1560         uint16_t net_idx = bt_mesh.sub[0].net_idx;
1561         uint16_t addr = bt_mesh_primary_addr();
1562         uint32_t iv_index = bt_mesh.iv_index;
1563         uint8_t flags = (uint8_t)bt_mesh.sub[0].kr_flag;
1564         const uint8_t *net_key = bt_mesh.sub[0].keys[flags].net;
1565         if (bt_mesh_atomic_test_bit(bt_mesh.flags, BLE_MESH_IVU_IN_PROGRESS)) {
1566             flags |= BLE_MESH_NET_FLAG_IVU;
1567         }
1568 
1569         bt_mesh_prov_complete(net_idx, net_key, addr, flags, iv_index);
1570     }
1571 }
1572 
bt_mesh_net_init(void)1573 void bt_mesh_net_init(void)
1574 {
1575     k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh);
1576 
1577     k_work_init(&bt_mesh.local_work, bt_mesh_net_local);
1578 }
1579 
bt_mesh_net_reset(void)1580 void bt_mesh_net_reset(void)
1581 {
1582     k_delayed_work_cancel(&bt_mesh.ivu_timer);
1583 
1584 #if FRIEND_CRED_COUNT > 0
1585     memset(friend_cred, 0, sizeof(friend_cred));
1586 #endif
1587 
1588     memset(msg_cache, 0, sizeof(msg_cache));
1589     msg_cache_next = 0U;
1590 
1591     memset(dup_cache, 0, sizeof(dup_cache));
1592     dup_cache_next = 0U;
1593 
1594     bt_mesh.iv_index = 0U;
1595     bt_mesh.seq = 0U;
1596 }
1597 
1598 #if CONFIG_BLE_MESH_DEINIT
bt_mesh_net_deinit(void)1599 void bt_mesh_net_deinit(void)
1600 {
1601     bt_mesh_net_reset();
1602 
1603     k_delayed_work_free(&bt_mesh.ivu_timer);
1604 
1605     k_work_init(&bt_mesh.local_work, NULL);
1606 
1607     /* Local queue uses a while loop, currently no need
1608      * to handle this.
1609      */
1610 }
1611 #endif /* CONFIG_BLE_MESH_DEINIT */
1612