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