1 /*  Bluetooth Mesh */
2 
3 /*
4  * Copyright (c) 2017 Intel Corporation
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <ble_os.h>
10 #include <string.h>
11 #include <bt_errno.h>
12 #include <stdbool.h>
13 #include <atomic.h>
14 #include <misc/util.h>
15 #include <misc/byteorder.h>
16 
17 #include <net/buf.h>
18 #include <bluetooth/bluetooth.h>
19 #include <bluetooth/conn.h>
20 #include <api/mesh.h>
21 
22 #define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_MESH_DEBUG_NET)
23 
24 #include "common/log.h"
25 
26 #include "crypto.h"
27 #include "adv.h"
28 #include "mesh.h"
29 #include "net.h"
30 #include "lpn.h"
31 #include "friend.h"
32 #include "proxy.h"
33 #include "ble_transport.h"
34 #include "access.h"
35 #include "foundation.h"
36 #include "beacon.h"
37 #include "settings.h"
38 #include "prov.h"
39 
40 #ifdef CONFIG_BT_MESH_PROVISIONER
41 #include "provisioner_prov.h"
42 #include "provisioner_main.h"
43 #include "provisioner_proxy.h"
44 #endif
45 
46 #ifdef CONFIG_BT_MESH_EVENT_CALLBACK
47 #include "mesh_event_port.h"
48 #endif
49 
50 /* Minimum valid Mesh Network PDU length. The Network headers
51  * themselves take up 9 bytes. After that there is a minumum of 1 byte
52  * payload for both CTL=1 and CTL=0 PDUs (smallest OpCode is 1 byte). CTL=1
53  * PDUs must use a 64-bit (8 byte) NetMIC, whereas CTL=0 PDUs have at least
54  * a 32-bit (4 byte) NetMIC and AppMIC giving again a total of 8 bytes.
55  */
56 #define BT_MESH_NET_MIN_PDU_LEN (BT_MESH_NET_HDR_LEN + 1 + 8)
57 
58 /* Seq limit after IV Update is triggered */
59 #ifndef CONFIG_IV_UPDATE_SEQ_LIMIT
60 #define CONFIG_IV_UPDATE_SEQ_LIMIT 8000000
61 #endif
62 
63 #define IVI(pdu) ((pdu)[0] >> 7)
64 #define NID(pdu) ((pdu)[0] & 0x7f)
65 #define CTL(pdu) ((pdu)[1] >> 7)
66 #define TTL(pdu) ((pdu)[1] & 0x7f)
67 #define SEQ(pdu) (((bt_u32_t)(pdu)[2] << 16) | ((bt_u32_t)(pdu)[3] << 8) | (bt_u32_t)(pdu)[4]);
68 #define SRC(pdu) (sys_get_be16(&(pdu)[5]))
69 #define DST(pdu) (sys_get_be16(&(pdu)[7]))
70 
71 /* Determine how many friendship credentials we need */
72 #if defined(CONFIG_BT_MESH_FRIEND)
73 #define FRIEND_CRED_COUNT CONFIG_BT_MESH_FRIEND_LPN_COUNT
74 #elif defined(CONFIG_BT_MESH_LOW_POWER)
75 #define FRIEND_CRED_COUNT CONFIG_BT_MESH_SUBNET_COUNT
76 #else
77 #define FRIEND_CRED_COUNT 0
78 #endif
79 
80 #if FRIEND_CRED_COUNT > 0
81 static struct friend_cred friend_cred[FRIEND_CRED_COUNT];
82 #endif
83 
84 static u64_t msg_cache[CONFIG_BT_MESH_MSG_CACHE_SIZE];
85 static u16_t msg_cache_next;
86 
87 u16_t g_sub_list[CONFIG_BT_MESH_MODEL_GROUP_COUNT];
88 
89 #if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
90 struct net_buf_trace_t net_buf_trace = { 0 };
91 #endif
92 
93 /* Singleton network context (the implementation only supports one) */
94 struct bt_mesh_net bt_mesh = {
95 	.local_queue = SYS_SLIST_STATIC_INIT(&bt_mesh.local_queue),
96 	.sub = {
97 		[0 ... (CONFIG_BT_MESH_SUBNET_COUNT - 1)] = {
98 			.net_idx = BT_MESH_KEY_UNUSED,
99 		}
100 	},
101 	.app_keys = {
102 		[0 ... (CONFIG_BT_MESH_APP_KEY_COUNT - 1)] = {
103 			.net_idx = BT_MESH_KEY_UNUSED,
104 		}
105 	},
106 // #ifdef CONFIG_BT_MESH_PROVISIONER
107 // .p_app_keys = {
108 //      [0 ... (CONFIG_BT_MESH_PROVISIONER_APP_KEY_COUNT - 1)] = {
109 //         .net_idx = BT_MESH_KEY_UNUSED,
110 //     }
111 // },
112 
113 // .p_sub = {
114 //      [0 ... (CONFIG_BT_MESH_PROVISIONER_SUBNET_COUNT - 1)] = {
115 //          .net_idx = BT_MESH_KEY_UNUSED,
116 //       }
117 // },
118 // #endif
119 };
120 
121 static bt_u32_t dup_cache[4];
122 static int dup_cache_next;
123 
check_dup(struct net_buf_simple * data)124 static bool check_dup(struct net_buf_simple *data)
125 {
126     const u8_t *tail = net_buf_simple_tail(data);
127     bt_u32_t val;
128     int i;
129 
130     val = sys_get_be32(tail - 4) ^ sys_get_be32(tail - 8);
131 
132     for (i = 0; i < ARRAY_SIZE(dup_cache); i++) {
133         if (dup_cache[i] == val) {
134             return true;
135         }
136     }
137 
138     dup_cache[dup_cache_next++] = val;
139     dup_cache_next %= ARRAY_SIZE(dup_cache);
140 
141     return false;
142 }
143 
msg_hash(struct bt_mesh_net_rx * rx,struct net_buf_simple * pdu)144 static u64_t msg_hash(struct bt_mesh_net_rx *rx, struct net_buf_simple *pdu)
145 {
146     bt_u32_t hash1, hash2;
147 
148     /* Three least significant bytes of IVI + first byte of SEQ */
149     hash1 = (BT_MESH_NET_IVI_RX(rx) << 8) | pdu->data[2];
150 
151     /* Two last bytes of SEQ + SRC */
152     memcpy(&hash2, &pdu->data[3], 4);
153 
154     return (u64_t)hash1 << 32 | (u64_t)hash2;
155 }
156 
msg_cache_match(struct bt_mesh_net_rx * rx,struct net_buf_simple * pdu)157 static bool msg_cache_match(struct bt_mesh_net_rx *rx, struct net_buf_simple *pdu)
158 {
159     u64_t hash = msg_hash(rx, pdu);
160     u16_t i;
161 
162     for (i = 0; i < ARRAY_SIZE(msg_cache); i++) {
163         if (msg_cache[i] == hash) {
164             return true;
165         }
166     }
167 
168     /* Add to the cache */
169     msg_cache[msg_cache_next++] = hash;
170     msg_cache_next %= ARRAY_SIZE(msg_cache);
171 
172     return false;
173 }
174 
bt_mesh_subnet_get(u16_t net_idx)175 struct bt_mesh_subnet *bt_mesh_subnet_get(u16_t net_idx)
176 {
177     int i;
178     if (net_idx == BT_MESH_KEY_ANY) {
179         return &bt_mesh.sub[0];
180     }
181 
182     for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
183         if (bt_mesh.sub[i].net_idx == net_idx) {
184             return &bt_mesh.sub[i];
185         }
186     }
187 
188     return NULL;
189 }
190 
bt_mesh_net_keys_create(struct bt_mesh_subnet_keys * keys,const u8_t key[16])191 int bt_mesh_net_keys_create(struct bt_mesh_subnet_keys *keys, const u8_t key[16])
192 {
193     u8_t p[] = { 0 };
194     u8_t nid;
195     int err;
196 
197     err = bt_mesh_k2(key, p, sizeof(p), &nid, keys->enc, keys->privacy);
198     if (err) {
199         BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
200         return err;
201     }
202 
203     memcpy(keys->net, key, 16);
204 
205     keys->nid = nid;
206 
207     BT_DBG("NID 0x%02x EncKey %s", keys->nid, bt_hex(keys->enc, 16));
208     BT_DBG("PrivacyKey %s", bt_hex(keys->privacy, 16));
209 
210     err = bt_mesh_k3(key, keys->net_id);
211     if (err) {
212         BT_ERR("Unable to generate Net ID");
213         return err;
214     }
215 
216     BT_DBG("NetID %s", bt_hex(keys->net_id, 8));
217 
218 #if defined(CONFIG_BT_MESH_GATT_PROXY)
219     err = bt_mesh_identity_key(key, keys->identity);
220     if (err) {
221         BT_ERR("Unable to generate IdentityKey");
222         return err;
223     }
224 
225     BT_DBG("IdentityKey %s", bt_hex(keys->identity, 16));
226 #endif /* GATT_PROXY */
227 
228     err = bt_mesh_beacon_key(key, keys->beacon);
229     if (err) {
230         BT_ERR("Unable to generate beacon key");
231         return err;
232     }
233 
234     BT_DBG("BeaconKey %s", bt_hex(keys->beacon, 16));
235 
236     return 0;
237 }
238 
239 #if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
friend_cred_set(struct friend_cred * cred,u8_t idx,const u8_t net_key[16])240 int friend_cred_set(struct friend_cred *cred, u8_t idx, const u8_t net_key[16])
241 {
242     u16_t lpn_addr, frnd_addr;
243     int err;
244     u8_t p[9];
245 
246 #if defined(CONFIG_BT_MESH_LOW_POWER)
247     if (cred->addr == bt_mesh.lpn.frnd) {
248         lpn_addr = bt_mesh_primary_addr();
249         frnd_addr = cred->addr;
250     } else {
251         lpn_addr = cred->addr;
252         frnd_addr = bt_mesh_primary_addr();
253     }
254 #else
255     lpn_addr = cred->addr;
256     frnd_addr = bt_mesh_primary_addr();
257 #endif
258 
259     BT_DBG("LPNAddress 0x%04x FriendAddress 0x%04x", lpn_addr, frnd_addr);
260     BT_DBG("LPNCounter 0x%04x FriendCounter 0x%04x", cred->lpn_counter, cred->frnd_counter);
261 
262     p[0] = 0x01;
263     sys_put_be16(lpn_addr, p + 1);
264     sys_put_be16(frnd_addr, p + 3);
265     sys_put_be16(cred->lpn_counter, p + 5);
266     sys_put_be16(cred->frnd_counter, p + 7);
267 
268     err = bt_mesh_k2(net_key, p, sizeof(p), &cred->cred[idx].nid, cred->cred[idx].enc, cred->cred[idx].privacy);
269     if (err) {
270         BT_ERR("Unable to generate NID, EncKey & PrivacyKey");
271         return err;
272     }
273 
274     BT_DBG("Friend NID 0x%02x EncKey %s", cred->cred[idx].nid, bt_hex(cred->cred[idx].enc, 16));
275     BT_DBG("Friend PrivacyKey %s", bt_hex(cred->cred[idx].privacy, 16));
276 
277     return 0;
278 }
279 
friend_cred_refresh(u16_t net_idx)280 void friend_cred_refresh(u16_t net_idx)
281 {
282     int i;
283 
284     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
285         struct friend_cred *cred = &friend_cred[i];
286 
287         if (cred->addr != BT_MESH_ADDR_UNASSIGNED && cred->net_idx == net_idx) {
288             memcpy(&cred->cred[0], &cred->cred[1], sizeof(cred->cred[0]));
289         }
290     }
291 }
292 
friend_cred_update(struct bt_mesh_subnet * sub)293 int friend_cred_update(struct bt_mesh_subnet *sub)
294 {
295     int err, i;
296 
297     BT_DBG("net_idx 0x%04x", sub->net_idx);
298 
299     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
300         struct friend_cred *cred = &friend_cred[i];
301 
302         if (cred->addr == BT_MESH_ADDR_UNASSIGNED || cred->net_idx != sub->net_idx) {
303             continue;
304         }
305 
306         err = friend_cred_set(cred, 1, sub->keys[1].net);
307         if (err) {
308             return err;
309         }
310     }
311 
312     return 0;
313 }
314 
friend_cred_create(struct bt_mesh_subnet * sub,u16_t addr,u16_t lpn_counter,u16_t frnd_counter)315 struct friend_cred *friend_cred_create(struct bt_mesh_subnet *sub, u16_t addr, u16_t lpn_counter, u16_t frnd_counter)
316 {
317     struct friend_cred *cred;
318     int i, err;
319 
320     BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
321 
322     for (cred = NULL, i = 0; i < ARRAY_SIZE(friend_cred); i++) {
323         if ((friend_cred[i].addr == BT_MESH_ADDR_UNASSIGNED) ||
324             (friend_cred[i].addr == addr && friend_cred[i].net_idx == sub->net_idx)) {
325             cred = &friend_cred[i];
326             break;
327         }
328     }
329 
330     if (!cred) {
331         BT_WARN("No free friend credential slots");
332         return NULL;
333     }
334 
335     cred->net_idx = sub->net_idx;
336     cred->addr = addr;
337     cred->lpn_counter = lpn_counter;
338     cred->frnd_counter = frnd_counter;
339 
340     err = friend_cred_set(cred, 0, sub->keys[0].net);
341     if (err) {
342         friend_cred_clear(cred);
343         return NULL;
344     }
345 
346     if (sub->kr_flag) {
347         err = friend_cred_set(cred, 1, sub->keys[1].net);
348         if (err) {
349             friend_cred_clear(cred);
350             return NULL;
351         }
352     }
353 
354     return cred;
355 }
356 
friend_cred_clear(struct friend_cred * cred)357 void friend_cred_clear(struct friend_cred *cred)
358 {
359     cred->net_idx = BT_MESH_KEY_UNUSED;
360     cred->addr = BT_MESH_ADDR_UNASSIGNED;
361     cred->lpn_counter = 0;
362     cred->frnd_counter = 0;
363     memset(cred->cred, 0, sizeof(cred->cred));
364 }
365 
friend_cred_del(u16_t net_idx,u16_t addr)366 int friend_cred_del(u16_t net_idx, u16_t addr)
367 {
368     int i;
369 
370     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
371         struct friend_cred *cred = &friend_cred[i];
372 
373         if (cred->addr == addr && cred->net_idx == net_idx) {
374             friend_cred_clear(cred);
375             return 0;
376         }
377     }
378 
379     return -ENOENT;
380 }
381 
friend_cred_get(struct bt_mesh_subnet * sub,u16_t addr,u8_t * nid,const u8_t ** enc,const u8_t ** priv)382 int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, const u8_t **enc, const u8_t **priv)
383 {
384     int i;
385 
386     BT_DBG("net_idx 0x%04x addr 0x%04x", sub->net_idx, addr);
387 
388     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
389         struct friend_cred *cred = &friend_cred[i];
390 
391         if (cred->net_idx != sub->net_idx) {
392             continue;
393         }
394 
395         if (addr != BT_MESH_ADDR_UNASSIGNED && cred->addr != addr) {
396             continue;
397         }
398 
399         if (nid) {
400             *nid = cred->cred[sub->kr_flag].nid;
401         }
402 
403         if (enc) {
404             *enc = cred->cred[sub->kr_flag].enc;
405         }
406 
407         if (priv) {
408             *priv = cred->cred[sub->kr_flag].privacy;
409         }
410 
411         return 0;
412     }
413 
414     return -ENOENT;
415 }
416 #else
friend_cred_get(struct bt_mesh_subnet * sub,u16_t addr,u8_t * nid,const u8_t ** enc,const u8_t ** priv)417 int friend_cred_get(struct bt_mesh_subnet *sub, u16_t addr, u8_t *nid, const u8_t **enc, const u8_t **priv)
418 {
419     return -ENOENT;
420 }
421 #endif /* FRIEND || LOW_POWER */
422 
bt_mesh_net_flags(struct bt_mesh_subnet * sub)423 u8_t bt_mesh_net_flags(struct bt_mesh_subnet *sub)
424 {
425     u8_t flags = 0x00;
426 
427     if (sub && sub->kr_flag) {
428         flags |= BT_MESH_NET_FLAG_KR;
429     }
430 
431     if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
432         flags |= BT_MESH_NET_FLAG_IVU;
433     }
434 
435     return flags;
436 }
437 
bt_mesh_net_beacon_update(struct bt_mesh_subnet * sub)438 int bt_mesh_net_beacon_update(struct bt_mesh_subnet *sub)
439 {
440     u8_t flags = bt_mesh_net_flags(sub);
441     struct bt_mesh_subnet_keys *keys;
442 
443     if (sub->kr_flag) {
444         BT_DBG("NetIndex %u Using new key", sub->net_idx);
445         keys = &sub->keys[1];
446     } else {
447         BT_DBG("NetIndex %u Using current key", sub->net_idx);
448         keys = &sub->keys[0];
449     }
450 
451     BT_DBG("flags 0x%02x, IVI 0x%08x", flags, bt_mesh.iv_index);
452 
453     return bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, bt_mesh.iv_index, sub->auth);
454 }
455 
bt_mesh_net_create(u16_t idx,u8_t flags,const u8_t key[16],bt_u32_t iv_index)456 int bt_mesh_net_create(u16_t idx, u8_t flags, const u8_t key[16], bt_u32_t iv_index)
457 {
458     struct bt_mesh_subnet *sub;
459     int err;
460 
461     BT_DBG("idx %u flags 0x%02x iv_index %u", idx, flags, iv_index);
462 
463     BT_DBG("NetKey %s", bt_hex(key, 16));
464 
465     (void)memset(msg_cache, 0, sizeof(msg_cache));
466     msg_cache_next = 0U;
467 
468     sub = &bt_mesh.sub[0];
469 
470     sub->kr_flag = BT_MESH_KEY_REFRESH(flags);
471     if (sub->kr_flag) {
472         err = bt_mesh_net_keys_create(&sub->keys[1], key);
473         if (err) {
474             return -EIO;
475         }
476 
477         sub->kr_phase = BT_MESH_KR_PHASE_2;
478     } else {
479         err = bt_mesh_net_keys_create(&sub->keys[0], key);
480         if (err) {
481             return -EIO;
482         }
483     }
484 
485     sub->net_idx = idx;
486 
487     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY)) {
488         sub->node_id = BT_MESH_NODE_IDENTITY_STOPPED;
489     } else {
490         sub->node_id = BT_MESH_NODE_IDENTITY_NOT_SUPPORTED;
491     }
492 
493     bt_mesh.iv_index = iv_index;
494     atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, BT_MESH_IV_UPDATE(flags));
495 
496     /* Set minimum required hours, since the 96-hour minimum requirement
497 	 * doesn't apply straight after provisioning (since we can't know how
498 	 * long has actually passed since the network changed its state).
499 	 */
500     bt_mesh.ivu_duration = BT_MESH_IVU_MIN_HOURS;
501 
502     /* Make sure we have valid beacon data to be sent */
503     bt_mesh_net_beacon_update(sub);
504 
505     sub->subnet_active = true;
506 
507     return 0;
508 }
509 
bt_mesh_net_revoke_keys(struct bt_mesh_subnet * sub)510 void bt_mesh_net_revoke_keys(struct bt_mesh_subnet *sub)
511 {
512     int i;
513 
514     BT_DBG("idx 0x%04x", sub->net_idx);
515 
516     memcpy(&sub->keys[0], &sub->keys[1], sizeof(sub->keys[0]));
517 
518     for (i = 0; i < ARRAY_SIZE(bt_mesh.app_keys); i++) {
519         struct bt_mesh_app_key *key = &bt_mesh.app_keys[i];
520 
521         if (key->net_idx != sub->net_idx || !key->updated) {
522             continue;
523         }
524 
525         memcpy(&key->keys[0], &key->keys[1], sizeof(key->keys[0]));
526         key->updated = false;
527     }
528 }
529 
bt_mesh_kr_update(struct bt_mesh_subnet * sub,u8_t new_kr,bool new_key)530 bool bt_mesh_kr_update(struct bt_mesh_subnet *sub, u8_t new_kr, bool new_key)
531 {
532     if (new_kr != sub->kr_flag && sub->kr_phase == BT_MESH_KR_NORMAL) {
533         BT_WARN("KR change in normal operation. Are we blacklisted?");
534         return false;
535     }
536 
537     sub->kr_flag = new_kr;
538 
539     if (sub->kr_flag) {
540         if (sub->kr_phase == BT_MESH_KR_PHASE_1) {
541             BT_DBG("Phase 1 -> Phase 2");
542             sub->kr_phase = BT_MESH_KR_PHASE_2;
543             return true;
544         }
545     } else {
546         switch (sub->kr_phase) {
547         case BT_MESH_KR_PHASE_1:
548             if (!new_key) {
549                 /* Ignore */
550                 break;
551             }
552         /* Upon receiving a Secure Network beacon with the KR flag set
553 		 * to 0 using the new NetKey in Phase 1, the node shall
554 		 * immediately transition to Phase 3, which effectively skips
555 		 * Phase 2.
556 		 *
557 		 * Intentional fall-through.
558 		 */
559         case BT_MESH_KR_PHASE_2:
560             BT_DBG("KR Phase 0x%02x -> Normal", sub->kr_phase);
561             bt_mesh_net_revoke_keys(sub);
562             if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) || IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
563                 friend_cred_refresh(sub->net_idx);
564             }
565             sub->kr_phase = BT_MESH_KR_NORMAL;
566             return true;
567         }
568     }
569 
570     return false;
571 }
572 
bt_mesh_rpl_reset(void)573 void bt_mesh_rpl_reset(void)
574 {
575     int i;
576 
577     /* Discard "old old" IV Index entries from RPL and flag
578 	 * any other ones (which are valid) as old.
579 	 */
580     for (i = 0; i < ARRAY_SIZE(bt_mesh.rpl); i++) {
581         struct bt_mesh_rpl *rpl = &bt_mesh.rpl[i];
582 
583         if (rpl->src) {
584             if (rpl->old_iv) {
585                 memset(rpl, 0, sizeof(*rpl));
586             } else {
587                 rpl->old_iv = true;
588             }
589         }
590     }
591 }
592 
593 #if defined(CONFIG_BT_MESH_IV_UPDATE_TEST)
bt_mesh_iv_update_test(bool enable)594 void bt_mesh_iv_update_test(bool enable)
595 {
596     atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_TEST, enable);
597     /* Reset the duration variable - needed for some PTS tests */
598     bt_mesh.ivu_duration = 0;
599 }
600 
bt_mesh_iv_update(void)601 bool bt_mesh_iv_update(void)
602 {
603     if (!bt_mesh_is_provisioned()) {
604         BT_ERR("Not yet provisioned");
605         return false;
606     }
607 
608     if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
609         bt_mesh_net_iv_update(bt_mesh.iv_index, false);
610     } else {
611         bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
612     }
613 
614     bt_mesh_net_sec_update(NULL);
615 
616     return atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS);
617 }
618 #endif /* CONFIG_BT_MESH_IV_UPDATE_TEST */
619 
620 /* Used for sending immediate beacons to Friend queues and GATT clients */
bt_mesh_net_sec_update(struct bt_mesh_subnet * sub)621 void bt_mesh_net_sec_update(struct bt_mesh_subnet *sub)
622 {
623     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
624         bt_mesh_friend_sec_update(sub ? sub->net_idx : BT_MESH_KEY_ANY);
625     }
626 
627     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED) {
628         bt_mesh_proxy_beacon_send(sub);
629     }
630 }
631 
bt_mesh_net_iv_update(bt_u32_t iv_index,bool iv_update)632 bool bt_mesh_net_iv_update(bt_u32_t iv_index, bool iv_update)
633 {
634     int i;
635 
636     if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
637         /* We're currently in IV Update mode */
638 
639         if (iv_index != bt_mesh.iv_index) {
640             BT_WARN("IV Index mismatch: 0x%08x != 0x%08x", iv_index, bt_mesh.iv_index);
641             return false;
642         }
643 
644         if (iv_update) {
645             /* Nothing to do */
646             BT_DBG("Already in IV Update in Progress state");
647             return false;
648         }
649     } else {
650         /* We're currently in Normal mode */
651 
652         if (iv_index == bt_mesh.iv_index) {
653             BT_DBG("Same IV Index in normal mode");
654             return false;
655         }
656 
657         if (iv_index < bt_mesh.iv_index || iv_index > bt_mesh.iv_index + 42) {
658             BT_ERR("IV Index out of sync: 0x%08x != 0x%08x", iv_index, bt_mesh.iv_index);
659             return false;
660         }
661 
662         if (iv_index > bt_mesh.iv_index + 1) {
663             BT_WARN("Performing IV Index Recovery");
664             memset(bt_mesh.rpl, 0, sizeof(bt_mesh.rpl));
665             bt_mesh.iv_index = iv_index;
666             bt_mesh.seq = 0;
667             goto do_update;
668         }
669 
670         if (iv_index == bt_mesh.iv_index + 1 && !iv_update) {
671             BT_WARN("Ignoring new index in normal mode");
672             return false;
673         }
674 
675         if (!iv_update) {
676             /* Nothing to do */
677             BT_DBG("Already in Normal state");
678             return false;
679         }
680     }
681 
682     if (!(IS_ENABLED(CONFIG_BT_MESH_IV_UPDATE_TEST) && atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_TEST))) {
683         if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
684             BT_WARN("IV Update before minimum duration");
685             return false;
686         }
687     }
688 
689     /* Defer change to Normal Operation if there are pending acks */
690     if (!iv_update && bt_mesh_tx_in_progress()) {
691         BT_WARN("IV Update deferred because of pending transfer");
692         atomic_set_bit(bt_mesh.flags, BT_MESH_IVU_PENDING);
693         return false;
694     }
695 
696 do_update:
697     atomic_set_bit_to(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS, iv_update);
698     bt_mesh.ivu_duration = 0U;
699 
700     if (iv_update) {
701         bt_mesh.iv_index = iv_index;
702         BT_DBG("IV Update state entered. New index 0x%08x", bt_mesh.iv_index);
703 
704         bt_mesh_rpl_reset();
705     } else {
706         BT_DBG("Normal mode entered");
707         bt_mesh.seq = 0;
708     }
709 
710     k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
711 
712     for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
713         if (bt_mesh.sub[i].net_idx != BT_MESH_KEY_UNUSED) {
714             bt_mesh_net_beacon_update(&bt_mesh.sub[i]);
715         }
716     }
717 
718     if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
719         bt_mesh_store_iv(false);
720     }
721 
722     return true;
723 }
724 
bt_mesh_next_seq(void)725 bt_u32_t bt_mesh_next_seq(void)
726 {
727     bt_u32_t seq = bt_mesh.seq++;
728 
729     if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
730         bt_mesh_store_seq();
731     }
732 
733     return seq;
734 }
735 
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)736 int bt_mesh_net_resend(struct bt_mesh_subnet *sub, struct net_buf *buf, bool new_key, const struct bt_mesh_send_cb *cb,
737                        void *cb_data)
738 {
739     const u8_t *enc, *priv;
740     bt_u32_t seq;
741     int err;
742 
743     BT_DBG("net_idx 0x%04x new_key %u len %u", sub->net_idx, new_key, buf->len);
744 
745     if (!sub || !buf || !buf->data) {
746         return -EINVAL;
747     }
748 
749     enc = sub->keys[new_key].enc;
750     priv = sub->keys[new_key].privacy;
751 
752     err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
753     if (err) {
754         BT_WARN("deobfuscate failed (err %d)", err);
755         return err;
756     }
757 
758     err = bt_mesh_net_decrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false);
759     if (err) {
760         BT_WARN("decrypt failed (err %d)", err);
761         return err;
762     }
763 
764     /* Update with a new sequence number */
765     seq = bt_mesh_next_seq();
766     buf->data[2] = seq >> 16;
767     buf->data[3] = seq >> 8;
768     buf->data[4] = seq;
769 
770 #ifdef CONFIG_BT_MESH_EVENT_CALLBACK
771     mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
772     if (event_cb) {
773         event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, NULL);
774     }
775 #endif
776     err = bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_TX, false);
777     if (err) {
778         BT_WARN("encrypt failed (err %d)", err);
779         return err;
780     }
781 
782     err = bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
783     if (err) {
784         BT_WARN("obfuscate failed (err %d)", err);
785         return err;
786     }
787 
788     bt_mesh_adv_send(buf, cb, cb_data);
789 
790     if (!atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) && bt_mesh.seq > CONFIG_IV_UPDATE_SEQ_LIMIT) {
791         bt_mesh_beacon_ivu_initiator(true);
792         bt_mesh_net_iv_update(bt_mesh.iv_index + 1, true);
793         bt_mesh_net_sec_update(NULL);
794     }
795 
796     return 0;
797 }
798 
bt_mesh_net_local(struct k_work * work)799 static void bt_mesh_net_local(struct k_work *work)
800 {
801     struct net_buf *buf;
802 
803     while ((buf = net_buf_slist_get(&bt_mesh.local_queue))) {
804         BT_DBG("len %u: %s", buf->len, bt_hex(buf->data, buf->len));
805         bt_mesh_net_recv(&buf->b, 0, BT_MESH_NET_IF_LOCAL);
806         net_buf_unref(buf);
807     }
808 }
809 
bt_mesh_net_encode(struct bt_mesh_net_tx * tx,struct net_buf_simple * buf,bool proxy)810 int bt_mesh_net_encode(struct bt_mesh_net_tx *tx, struct net_buf_simple *buf, bool proxy)
811 {
812     const bool ctl = (tx->ctx->app_idx == BT_MESH_KEY_UNUSED);
813     bt_u32_t seq_val;
814     u8_t nid;
815     const u8_t *enc, *priv;
816     u8_t *seq;
817     int err;
818 
819     if (ctl && net_buf_simple_tailroom(buf) < 8) {
820         BT_ERR("Insufficient MIC space for CTL PDU");
821         return -EINVAL;
822     } else if (net_buf_simple_tailroom(buf) < 4) {
823         BT_ERR("Insufficient MIC space for PDU");
824         return -EINVAL;
825     }
826 
827     BT_DBG("src 0x%04x dst 0x%04x ctl %u seq 0x%06x", tx->src, tx->ctx->addr, ctl, bt_mesh.seq);
828 
829     net_buf_simple_push_be16(buf, tx->ctx->addr);
830     net_buf_simple_push_be16(buf, tx->src);
831 
832     seq = net_buf_simple_push(buf, 3);
833     seq_val = bt_mesh_next_seq();
834     seq[0] = seq_val >> 16;
835     seq[1] = seq_val >> 8;
836     seq[2] = seq_val;
837 #ifdef CONFIG_BT_MESH_EVENT_CALLBACK
838     mesh_model_evt_cb event_cb = bt_mesh_event_get_cb_func();
839     if (event_cb) {
840         event_cb(BT_MESH_MODEL_EVT_SEQ_UPDATE, NULL);
841     }
842 #endif
843 
844     if (ctl) {
845         net_buf_simple_push_u8(buf, tx->ctx->send_ttl | 0x80);
846     } else {
847         net_buf_simple_push_u8(buf, tx->ctx->send_ttl);
848     }
849 
850     if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER) && tx->friend_cred) {
851         if (friend_cred_get(tx->sub, BT_MESH_ADDR_UNASSIGNED, &nid, &enc, &priv)) {
852             BT_WARN("Falling back to master credentials");
853 
854             tx->friend_cred = 0;
855 
856             nid = tx->sub->keys[tx->sub->kr_flag].nid;
857             enc = tx->sub->keys[tx->sub->kr_flag].enc;
858             priv = tx->sub->keys[tx->sub->kr_flag].privacy;
859         }
860     } else {
861         tx->friend_cred = 0;
862         nid = tx->sub->keys[tx->sub->kr_flag].nid;
863         enc = tx->sub->keys[tx->sub->kr_flag].enc;
864         priv = tx->sub->keys[tx->sub->kr_flag].privacy;
865     }
866 
867     net_buf_simple_push_u8(buf, (nid | (BT_MESH_NET_IVI_TX & 1) << 7));
868 
869     err = bt_mesh_net_encrypt(enc, buf, BT_MESH_NET_IVI_TX, proxy);
870     if (err) {
871         return err;
872     }
873 
874     return bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_TX, priv);
875 }
876 
bt_mesh_net_send(struct bt_mesh_net_tx * tx,struct net_buf * buf,const struct bt_mesh_send_cb * cb,void * cb_data)877 int bt_mesh_net_send(struct bt_mesh_net_tx *tx, struct net_buf *buf, const struct bt_mesh_send_cb *cb, void *cb_data)
878 {
879     int err;
880 
881     BT_DBG("src 0x%04x dst 0x%04x len %u headroom %zu tailroom %zu", tx->src, tx->ctx->addr, buf->len,
882            net_buf_headroom(buf), net_buf_tailroom(buf));
883     BT_DBG("Payload len %u: %s", buf->len, bt_hex(buf->data, buf->len));
884     BT_DBG("Seq 0x%06x", bt_mesh.seq);
885 
886     if (tx->ctx->send_ttl == BT_MESH_TTL_DEFAULT) {
887         tx->ctx->send_ttl = bt_mesh_default_ttl_get();
888     }
889 
890     err = bt_mesh_net_encode(tx, &buf->b, false);
891     if (err) {
892         goto done;
893     }
894 
895     /* Deliver to GATT Proxy Clients if necessary. Mesh spec 3.4.5.2:
896 	 * "The output filter of the interface connected to advertising or
897 	 * GATT bearers shall drop all messages with TTL value set to 1."
898 	 */
899 #ifdef CONFIG_BT_MESH_PROVISIONER
900     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_is_provisioner_en()) {
901         if (0 == provisioner_proxy_pdu_send(&buf->b)) {
902             goto done;
903         }
904     }
905 #endif
906     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && tx->ctx->send_ttl != 1) {
907         if (bt_mesh_proxy_relay(&buf->b, tx->ctx->addr) && BT_MESH_ADDR_IS_UNICAST(tx->ctx->addr)) {
908             /* Notify completion if this only went
909 			 * through the Mesh Proxy.
910 			 */
911             if (cb) {
912                 if (cb->start) {
913                     cb->start(0, 0, cb_data);
914                 }
915 
916                 if (cb->end) {
917                     cb->end(0, cb_data);
918                 }
919             }
920 
921             err = 0;
922             goto done;
923         }
924     }
925 
926     /* Deliver to local network interface if necessary */
927     if (bt_mesh_fixed_group_match(tx->ctx->addr) || bt_mesh_elem_find(tx->ctx->addr)) {
928         if (cb && cb->start) {
929             cb->start(0, 0, cb_data);
930         }
931         net_buf_slist_put(&bt_mesh.local_queue, net_buf_ref(buf));
932         if (cb && cb->end) {
933             cb->end(0, cb_data);
934         }
935         k_work_submit(&bt_mesh.local_work);
936     } else if (tx->ctx->send_ttl != 1) {
937         /* Deliver to to the advertising network interface. Mesh spec
938 		 * 3.4.5.2: "The output filter of the interface connected to
939 		 * advertising or GATT bearers shall drop all messages with
940 		 * TTL value set to 1."
941 		 */
942         bt_mesh_adv_send(buf, cb, cb_data);
943     }
944 
945 done:
946     net_buf_unref(buf);
947     return err;
948 }
949 
auth_match(struct bt_mesh_subnet_keys * keys,const u8_t net_id[8],u8_t flags,bt_u32_t iv_index,const u8_t auth[8])950 static bool auth_match(struct bt_mesh_subnet_keys *keys, const u8_t net_id[8], u8_t flags, bt_u32_t iv_index,
951                        const u8_t auth[8])
952 {
953     u8_t net_auth[8] = { 0 };
954 
955     if (memcmp(net_id, keys->net_id, 8)) {
956         return false;
957     }
958 
959     bt_mesh_beacon_auth(keys->beacon, flags, keys->net_id, iv_index, net_auth);
960 
961     if (memcmp(auth, net_auth, 8)) {
962         BT_WARN("Authentication Value %s != %s", bt_hex(auth, 8), bt_hex(net_auth, 8));
963         return false;
964     }
965 
966     return true;
967 }
968 
bt_mesh_subnet_find(const u8_t net_id[8],u8_t flags,bt_u32_t iv_index,const u8_t auth[8],bool * new_key)969 struct bt_mesh_subnet *bt_mesh_subnet_find(const u8_t net_id[8], u8_t flags, bt_u32_t iv_index, const u8_t auth[8],
970                                            bool *new_key)
971 {
972     int i;
973 
974     for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
975         struct bt_mesh_subnet *sub = &bt_mesh.sub[i];
976 
977         if (sub->net_idx == BT_MESH_KEY_UNUSED) {
978             continue;
979         }
980 
981         if (auth_match(&sub->keys[0], net_id, flags, iv_index, auth)) {
982             *new_key = false;
983             return sub;
984         }
985 
986         if (sub->kr_phase == BT_MESH_KR_NORMAL) {
987             continue;
988         }
989 
990         if (auth_match(&sub->keys[1], net_id, flags, iv_index, auth)) {
991             *new_key = true;
992             return sub;
993         }
994     }
995 
996     return NULL;
997 }
998 
net_decrypt(struct bt_mesh_subnet * sub,const u8_t * enc,const u8_t * priv,const u8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)999 static int net_decrypt(struct bt_mesh_subnet *sub, const u8_t *enc, const u8_t *priv, const u8_t *data, size_t data_len,
1000                        struct bt_mesh_net_rx *rx, struct net_buf_simple *buf)
1001 {
1002     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1003     BT_DBG("IVI %u net->iv_index 0x%08x", IVI(data), bt_mesh.iv_index);
1004 
1005     rx->old_iv = (IVI(data) != (bt_mesh.iv_index & 0x01));
1006 
1007     net_buf_simple_reset(buf);
1008     memcpy(net_buf_simple_add(buf, data_len), data, data_len);
1009 
1010     if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) {
1011         return -ENOENT;
1012     }
1013 
1014     if (rx->net_if == BT_MESH_NET_IF_ADV && msg_cache_match(rx, buf)) {
1015         BT_DBG("Duplicate found in Network Message Cache");
1016         return -EALREADY;
1017     }
1018 
1019     rx->ctx.addr = SRC(buf->data);
1020     if (!BT_MESH_ADDR_IS_UNICAST(rx->ctx.addr)) {
1021         BT_WARN("Ignoring non-unicast src addr 0x%04x", rx->ctx.addr);
1022         return -EINVAL;
1023     }
1024 
1025     BT_DBG("src 0x%04x", rx->ctx.addr);
1026 
1027     if (IS_ENABLED(CONFIG_BT_MESH_PROXY) && rx->net_if == BT_MESH_NET_IF_PROXY_CFG) {
1028         return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), true);
1029     }
1030 
1031     return bt_mesh_net_decrypt(enc, buf, BT_MESH_NET_IVI_RX(rx), false);
1032 }
1033 
1034 #if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
friend_decrypt(struct bt_mesh_subnet * sub,const u8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1035 static int friend_decrypt(struct bt_mesh_subnet *sub, const u8_t *data, size_t data_len, struct bt_mesh_net_rx *rx,
1036                           struct net_buf_simple *buf)
1037 {
1038     int i;
1039 
1040     BT_DBG("NID 0x%02x net_idx 0x%04x", NID(data), sub->net_idx);
1041 
1042     for (i = 0; i < ARRAY_SIZE(friend_cred); i++) {
1043         struct friend_cred *cred = &friend_cred[i];
1044 
1045         if (cred->net_idx != sub->net_idx) {
1046             continue;
1047         }
1048 
1049         if (NID(data) == cred->cred[0].nid &&
1050             !net_decrypt(sub, cred->cred[0].enc, cred->cred[0].privacy, data, data_len, rx, buf)) {
1051             return 0;
1052         }
1053 
1054         if (sub->kr_phase == BT_MESH_KR_NORMAL) {
1055             continue;
1056         }
1057 
1058         if (NID(data) == cred->cred[1].nid &&
1059             !net_decrypt(sub, cred->cred[1].enc, cred->cred[1].privacy, data, data_len, rx, buf)) {
1060             rx->new_key = 1;
1061             return 0;
1062         }
1063     }
1064 
1065     return -ENOENT;
1066 }
1067 #endif
1068 
net_find_and_decrypt(const u8_t * data,size_t data_len,struct bt_mesh_net_rx * rx,struct net_buf_simple * buf)1069 static bool net_find_and_decrypt(const u8_t *data, size_t data_len, struct bt_mesh_net_rx *rx,
1070                                  struct net_buf_simple *buf)
1071 {
1072     struct bt_mesh_subnet *sub;
1073     int i;
1074     bt_u32_t array_size = 0;
1075 
1076     BT_DBG("");
1077 
1078     array_size = ARRAY_SIZE(bt_mesh.sub);
1079 
1080     for (i = 0; i < array_size; i++) {
1081         sub = &bt_mesh.sub[i];
1082 
1083         if (sub->net_idx == BT_MESH_KEY_UNUSED) {
1084             continue;
1085         }
1086 
1087 #if (defined(CONFIG_BT_MESH_LOW_POWER) || defined(CONFIG_BT_MESH_FRIEND))
1088         if (!friend_decrypt(sub, data, data_len, rx, buf)) {
1089             rx->friend_cred = 1;
1090             rx->ctx.net_idx = sub->net_idx;
1091             rx->sub = sub;
1092             return true;
1093         }
1094 #endif
1095 
1096         if (NID(data) == sub->keys[0].nid &&
1097             !net_decrypt(sub, sub->keys[0].enc, sub->keys[0].privacy, data, data_len, rx, buf)) {
1098             rx->ctx.net_idx = sub->net_idx;
1099             rx->sub = sub;
1100             return true;
1101         }
1102 
1103         if (sub->kr_phase == BT_MESH_KR_NORMAL) {
1104             continue;
1105         }
1106 
1107         if (NID(data) == sub->keys[1].nid &&
1108             !net_decrypt(sub, sub->keys[1].enc, sub->keys[1].privacy, data, data_len, rx, buf)) {
1109             rx->new_key = 1;
1110             rx->ctx.net_idx = sub->net_idx;
1111             rx->sub = sub;
1112             return true;
1113         }
1114     }
1115 
1116     return false;
1117 }
1118 
1119 /* Relaying from advertising to the advertising bearer should only happen
1120  * if the Relay state is set to enabled. Locally originated packets always
1121  * get sent to the advertising bearer. If the packet came in through GATT,
1122  * then we should only relay it if the GATT Proxy state is enabled.
1123  */
relay_to_adv(enum bt_mesh_net_if net_if)1124 static bool relay_to_adv(enum bt_mesh_net_if net_if)
1125 {
1126     switch (net_if) {
1127     case BT_MESH_NET_IF_LOCAL:
1128         return true;
1129     case BT_MESH_NET_IF_ADV:
1130         return (bt_mesh_relay_get() == BT_MESH_RELAY_ENABLED);
1131     case BT_MESH_NET_IF_PROXY:
1132         return (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED);
1133     default:
1134         return false;
1135     }
1136 }
1137 
bt_mesh_net_relay(struct net_buf_simple * sbuf,struct bt_mesh_net_rx * rx)1138 static void bt_mesh_net_relay(struct net_buf_simple *sbuf, struct bt_mesh_net_rx *rx)
1139 {
1140     const u8_t *enc, *priv;
1141     struct net_buf *buf;
1142     u8_t nid, transmit;
1143 
1144     if (rx->net_if == BT_MESH_NET_IF_LOCAL) {
1145         /* Locally originated PDUs with TTL=1 will only be delivered
1146 		 * to local elements as per Mesh Profile 1.0 section 3.4.5.2:
1147 		 * "The output filter of the interface connected to
1148 		 * advertising or GATT bearers shall drop all messages with
1149 		 * TTL value set to 1."
1150 		 */
1151         if (rx->ctx.recv_ttl == 1) {
1152             return;
1153         }
1154     } else {
1155         if (rx->ctx.recv_ttl <= 1) {
1156             return;
1157         }
1158     }
1159 
1160     if (rx->net_if == BT_MESH_NET_IF_ADV && bt_mesh_relay_get() != BT_MESH_RELAY_ENABLED &&
1161         bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_ENABLED) {
1162         return;
1163     }
1164 
1165 #if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
1166     if (BT_MESH_NET_IF_ADV == rx->net_if) {
1167         if (net_buf_trace.buf == sbuf) {
1168             BT_INFO("TTL %u CTL %u dst 0x%04x recv from 0x%04x (%02X:%02X:%02X:%02X:%02X:%02X (%d)) packet ",
1169                     rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst, rx->ctx.addr, net_buf_trace.addr[5],
1170                     net_buf_trace.addr[4], net_buf_trace.addr[3], net_buf_trace.addr[2], net_buf_trace.addr[1],
1171                     net_buf_trace.addr[0], net_buf_trace.addr[6]);
1172         }
1173     } else {
1174         BT_DBG("TTL %u CTL %u dst 0x%04x packet ", rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst);
1175     }
1176 #else
1177     BT_DBG("TTL %u CTL %u dst 0x%04x packet ", rx->ctx.recv_ttl, rx->ctl, rx->ctx.recv_dst);
1178 #endif
1179 
1180     /* The Relay Retransmit state is only applied to adv-adv relaying.
1181 	 * Anything else (like GATT to adv, or locally originated packets)
1182 	 * use the Network Transmit state.
1183 	 */
1184     if (rx->net_if == BT_MESH_NET_IF_ADV) {
1185         transmit = bt_mesh_relay_retransmit_get();
1186     } else {
1187         transmit = bt_mesh_net_transmit_get();
1188     }
1189 
1190     buf = bt_mesh_adv_create(BT_MESH_ADV_DATA, transmit, K_NO_WAIT);
1191     if (!buf) {
1192         /*[Genie begin] add by wenbing.cwb at 2021-01-21*/
1193         BT_ERR("[%u]Out of relay buffers, Payload: %s", k_uptime_get_32(), bt_hex(sbuf->data, sbuf->len));
1194 #ifdef CONFIG_BT_MESH_CTRL_RELAY
1195         ctrl_relay_set_flood_flg();
1196 #endif
1197         /*[Genie end] add by wenbing.cwb at 2021-01-21*/
1198         return;
1199     }
1200 
1201     /* Only decrement TTL for non-locally originated packets */
1202     if (rx->net_if != BT_MESH_NET_IF_LOCAL) {
1203         /* Leave CTL bit intact */
1204         sbuf->data[1] &= 0x80;
1205         sbuf->data[1] |= rx->ctx.recv_ttl - 1;
1206     }
1207 
1208     net_buf_add_mem(buf, sbuf->data, sbuf->len);
1209 
1210     enc = rx->sub->keys[rx->sub->kr_flag].enc;
1211     priv = rx->sub->keys[rx->sub->kr_flag].privacy;
1212     nid = rx->sub->keys[rx->sub->kr_flag].nid;
1213 
1214     BT_DBG("Relaying packet. TTL is now %u", TTL(buf->data));
1215 
1216     /* Update NID if RX or RX was with friend credentials */
1217     if (rx->friend_cred) {
1218         buf->data[0] &= 0x80; /* Clear everything except IVI */
1219         buf->data[0] |= nid;
1220     }
1221 
1222     /* We re-encrypt and obfuscate using the received IVI rather than
1223 	 * the normal TX IVI (which may be different) since the transport
1224 	 * layer nonce includes the IVI.
1225 	 */
1226     if (bt_mesh_net_encrypt(enc, &buf->b, BT_MESH_NET_IVI_RX(rx), false)) {
1227         BT_ERR("Re-encrypting failed");
1228         goto done;
1229     }
1230 
1231     if (bt_mesh_net_obfuscate(buf->data, BT_MESH_NET_IVI_RX(rx), priv)) {
1232         BT_ERR("Re-obfuscating failed");
1233         goto done;
1234     }
1235 
1236     /* Sending to the GATT bearer should only happen if GATT Proxy
1237 	 * is enabled or the message originates from the local node.
1238 	 */
1239     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) &&
1240         (bt_mesh_gatt_proxy_get() == BT_MESH_GATT_PROXY_ENABLED || rx->net_if == BT_MESH_NET_IF_LOCAL)) {
1241         if (bt_mesh_proxy_relay(&buf->b, rx->ctx.recv_dst) && BT_MESH_ADDR_IS_UNICAST(rx->ctx.recv_dst)) {
1242             goto done;
1243         }
1244     }
1245 
1246     if (relay_to_adv(rx->net_if)) {
1247         bt_mesh_adv_send(buf, NULL, NULL);
1248     }
1249 
1250 done:
1251     net_buf_unref(buf);
1252 }
1253 
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)1254 int bt_mesh_net_decode(struct net_buf_simple *data, enum bt_mesh_net_if net_if, struct bt_mesh_net_rx *rx,
1255                        struct net_buf_simple *buf)
1256 {
1257     if (data->len < BT_MESH_NET_MIN_PDU_LEN) {
1258         BT_WARN("Dropping too short mesh packet (len %u)", data->len);
1259         BT_WARN("%s", bt_hex(data->data, data->len));
1260         return -EINVAL;
1261     }
1262 
1263     if (net_if == BT_MESH_NET_IF_ADV && check_dup(data)) {
1264         return -EINVAL;
1265     }
1266 
1267     BT_DBG("%u bytes: %s", data->len, bt_hex(data->data, data->len));
1268 
1269     rx->net_if = net_if;
1270 
1271     if (!net_find_and_decrypt(data->data, data->len, rx, buf)) {
1272         BT_DBG("Unable to find matching net for packet");
1273         return -ENOENT;
1274     }
1275 
1276     /* Initialize AppIdx to a sane value */
1277     rx->ctx.app_idx = BT_MESH_KEY_UNUSED;
1278 
1279     rx->ctx.recv_ttl = TTL(buf->data);
1280 
1281     /* Default to responding with TTL 0 for non-routed messages */
1282     if (rx->ctx.recv_ttl == 0) {
1283         rx->ctx.send_ttl = 0;
1284     } else {
1285         rx->ctx.send_ttl = BT_MESH_TTL_DEFAULT;
1286     }
1287 
1288     rx->ctl = CTL(buf->data);
1289     rx->seq = SEQ(buf->data);
1290     rx->ctx.recv_dst = DST(buf->data);
1291 
1292     BT_DBG("Decryption successful. Payload len %u", buf->len);
1293 
1294     if (net_if != BT_MESH_NET_IF_PROXY_CFG && rx->ctx.recv_dst == BT_MESH_ADDR_UNASSIGNED) {
1295         BT_ERR("Destination address is unassigned; dropping packet");
1296         return -EBADMSG;
1297     }
1298 
1299     if (BT_MESH_ADDR_IS_RFU(rx->ctx.recv_dst)) {
1300         BT_ERR("Destination address is RFU; dropping packet");
1301         return -EBADMSG;
1302     }
1303 
1304     if (net_if != BT_MESH_NET_IF_LOCAL && bt_mesh_elem_find(rx->ctx.addr)) {
1305         BT_DBG("Dropping locally originated packet");
1306         return -EBADMSG;
1307     }
1308 
1309     BT_DBG("src 0x%04x dst 0x%04x ttl %u", rx->ctx.addr, rx->ctx.recv_dst, rx->ctx.recv_ttl);
1310     BT_DBG("PDU: %s", bt_hex(buf->data, buf->len));
1311 
1312     return 0;
1313 }
1314 
1315 #ifdef CONFIG_GENIE_MESH_ENABLE
1316 static bool bt_mesh_net_rx_stat = false;
bt_mesh_net_is_rx(void)1317 bool bt_mesh_net_is_rx(void)
1318 {
1319     return bt_mesh_net_rx_stat;
1320 }
1321 #endif
1322 
bt_mesh_net_recv(struct net_buf_simple * data,s8_t rssi,enum bt_mesh_net_if net_if)1323 void bt_mesh_net_recv(struct net_buf_simple *data, s8_t rssi, enum bt_mesh_net_if net_if)
1324 {
1325     struct bt_mesh_net_rx rx = { .rssi = rssi };
1326     struct net_buf_simple_state state;
1327 
1328     BT_DBG("rssi %d net_if %u, len %d", rssi, net_if, data->len);
1329 
1330     if (data->len > BT_MESH_NET_MAX_PDU_LEN) {
1331         BT_ERR("Net PDU is too long %d(%d)", data->len, BT_MESH_NET_MAX_PDU_LEN);
1332         return;
1333     }
1334 
1335     NET_BUF_SIMPLE_DEFINE(buf, BT_MESH_NET_MAX_PDU_LEN);
1336 
1337 #if defined(CONFIG_BT_MESH_RELAY_SRC_DBG)
1338     if (BT_MESH_NET_IF_ADV == net_if) {
1339         net_buf_trace.buf = &buf;
1340     }
1341 #endif
1342 
1343     if (!bt_mesh_is_provisioned()) {
1344         return;
1345     }
1346 
1347 #ifdef CONFIG_GENIE_MESH_ENABLE
1348     bt_mesh_net_rx_stat = true;
1349 #endif
1350     if (bt_mesh_net_decode(data, net_if, &rx, &buf)) {
1351 #ifdef CONFIG_GENIE_MESH_ENABLE
1352         bt_mesh_net_rx_stat = false;
1353 #endif
1354         return;
1355     }
1356 
1357     /* Save the state so the buffer can later be relayed */
1358     net_buf_simple_save(&buf, &state);
1359 
1360     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && net_if == BT_MESH_NET_IF_PROXY) {
1361         bt_mesh_proxy_addr_add(data, rx.ctx.addr);
1362     }
1363 
1364     rx.local_match = (bt_mesh_fixed_group_match(rx.ctx.recv_dst) || bt_mesh_elem_find(rx.ctx.recv_dst));
1365 
1366     bt_mesh_trans_recv(&buf, &rx);
1367 
1368     /* Relay if this was a group/virtual address, or if the destination
1369 	 * was neither a local element nor an LPN we're Friends for.
1370 	 */
1371     if (!BT_MESH_ADDR_IS_UNICAST(rx.ctx.recv_dst) || (!rx.local_match && !rx.friend_match)) {
1372         net_buf_simple_restore(&buf, &state);
1373         bt_mesh_net_relay(&buf, &rx);
1374     }
1375 #ifdef CONFIG_GENIE_MESH_ENABLE
1376     bt_mesh_net_rx_stat = false;
1377 #endif
1378 }
1379 
ivu_refresh(struct k_work * work)1380 static void ivu_refresh(struct k_work *work)
1381 {
1382     bt_mesh.ivu_duration += BT_MESH_IVU_HOURS;
1383 
1384     BT_DBG("%s for %u hour%s",
1385            atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS) ? "IVU in Progress" : "IVU Normal mode",
1386            bt_mesh.ivu_duration, bt_mesh.ivu_duration == 1U ? "" : "s");
1387 
1388     if (bt_mesh.ivu_duration < BT_MESH_IVU_MIN_HOURS) {
1389         if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1390             bt_mesh_store_iv(true);
1391         }
1392 
1393         k_delayed_work_submit(&bt_mesh.ivu_timer, BT_MESH_IVU_TIMEOUT);
1394         return;
1395     }
1396 
1397     if (atomic_test_bit(bt_mesh.flags, BT_MESH_IVU_IN_PROGRESS)) {
1398         bt_mesh_beacon_ivu_initiator(true);
1399         bt_mesh_net_iv_update(bt_mesh.iv_index, false);
1400     } else if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1401         bt_mesh_store_iv(true);
1402     }
1403 }
1404 
bt_mesh_net_start(void)1405 void bt_mesh_net_start(void)
1406 {
1407     if (bt_mesh_beacon_get() == BT_MESH_BEACON_ENABLED) {
1408         bt_mesh_beacon_enable();
1409     } else {
1410         bt_mesh_beacon_disable();
1411     }
1412 
1413     if (IS_ENABLED(CONFIG_BT_MESH_GATT_PROXY) && bt_mesh_gatt_proxy_get() != BT_MESH_GATT_PROXY_NOT_SUPPORTED) {
1414         bt_mesh_proxy_gatt_enable();
1415         bt_mesh_adv_update();
1416     }
1417 
1418     if (IS_ENABLED(CONFIG_BT_MESH_LOW_POWER)) {
1419         bt_mesh_lpn_init();
1420     } else {
1421         bt_mesh_scan_enable();
1422     }
1423 
1424     if (IS_ENABLED(CONFIG_BT_MESH_FRIEND)) {
1425         bt_mesh_friend_init();
1426     }
1427 
1428     if (IS_ENABLED(CONFIG_BT_MESH_PROV)) {
1429         u16_t net_idx = bt_mesh.sub[0].net_idx;
1430         u16_t addr = bt_mesh_primary_addr();
1431 
1432         bt_mesh_prov_complete(net_idx, addr);
1433     }
1434 }
1435 
bt_mesh_net_init(void)1436 void bt_mesh_net_init(void)
1437 {
1438     BT_INFO("enter %s\n", __func__);
1439 
1440     k_delayed_work_init(&bt_mesh.ivu_timer, ivu_refresh);
1441 
1442     k_work_init(&bt_mesh.local_work, bt_mesh_net_local);
1443 }
1444