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