1 /*
2  * Copyright (c) 2017-2024 Nordic Semiconductor ASA
3  * Copyright (c) 2015-2016 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdbool.h>
9 #include <stdint.h>
10 
11 #include <zephyr/bluetooth/hci_types.h>
12 #include <zephyr/settings/settings.h>
13 #include <zephyr/sys/byteorder.h>
14 #include <zephyr/sys/check.h>
15 
16 #include <zephyr/bluetooth/addr.h>
17 #include <zephyr/bluetooth/bluetooth.h>
18 #include <zephyr/bluetooth/hci_vs.h>
19 #include <zephyr/bluetooth/buf.h>
20 #include <zephyr/sys/__assert.h>
21 
22 #include "hci_core.h"
23 #include "id.h"
24 #include "scan.h"
25 #include "adv.h"
26 #include "smp.h"
27 #include "conn_internal.h"
28 #include "keys.h"
29 #include "common/rpa.h"
30 
31 #include "settings.h"
32 
33 #include <zephyr/bluetooth/hci.h>
34 #include <zephyr/sys/util_macro.h>
35 #include <zephyr/toolchain.h>
36 
37 #include "common/bt_str.h"
38 
39 #define LOG_LEVEL CONFIG_BT_HCI_CORE_LOG_LEVEL
40 #include <zephyr/logging/log.h>
41 LOG_MODULE_REGISTER(bt_id);
42 
43 struct bt_adv_id_check_data {
44 	uint8_t id;
45 	bool adv_enabled;
46 };
47 
48 #if defined(CONFIG_BT_OBSERVER) || defined(CONFIG_BT_BROADCASTER)
bt_lookup_id_addr(uint8_t id,const bt_addr_le_t * addr)49 const bt_addr_le_t *bt_lookup_id_addr(uint8_t id, const bt_addr_le_t *addr)
50 {
51 	CHECKIF(id >= CONFIG_BT_ID_MAX || addr == NULL) {
52 		return NULL;
53 	}
54 
55 	if (IS_ENABLED(CONFIG_BT_SMP)) {
56 		struct bt_keys *keys;
57 
58 		keys = bt_keys_find_irk(id, addr);
59 		if (keys) {
60 			LOG_DBG("Identity %s matched RPA %s", bt_addr_le_str(&keys->addr),
61 				bt_addr_le_str(addr));
62 			return &keys->addr;
63 		}
64 	}
65 
66 	return addr;
67 }
68 #endif /* CONFIG_BT_OBSERVER || CONFIG_BT_CONN */
69 
adv_id_check_func(struct bt_le_ext_adv * adv,void * data)70 static void adv_id_check_func(struct bt_le_ext_adv *adv, void *data)
71 {
72 	struct bt_adv_id_check_data *check_data = data;
73 
74 	if (IS_ENABLED(CONFIG_BT_EXT_ADV)) {
75 		/* Only check if the ID is in use, as the advertiser can be
76 		 * started and stopped without reconfiguring parameters.
77 		 */
78 		if (check_data->id == adv->id) {
79 			check_data->adv_enabled = true;
80 		}
81 	} else {
82 		if (check_data->id == adv->id &&
83 		    atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
84 			check_data->adv_enabled = true;
85 		}
86 	}
87 }
88 
adv_is_private_enabled(struct bt_le_ext_adv * adv,void * data)89 static void adv_is_private_enabled(struct bt_le_ext_adv *adv, void *data)
90 {
91 	bool *adv_enabled = data;
92 
93 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
94 	    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
95 		*adv_enabled = true;
96 	}
97 }
98 
99 #if defined(CONFIG_BT_SMP)
adv_is_limited_enabled(struct bt_le_ext_adv * adv,void * data)100 static void adv_is_limited_enabled(struct bt_le_ext_adv *adv, void *data)
101 {
102 	bool *adv_enabled = data;
103 
104 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
105 	    atomic_test_bit(adv->flags, BT_ADV_LIMITED)) {
106 		*adv_enabled = true;
107 	}
108 }
109 
adv_pause_enabled(struct bt_le_ext_adv * adv,void * data)110 static void adv_pause_enabled(struct bt_le_ext_adv *adv, void *data)
111 {
112 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
113 		atomic_set_bit(adv->flags, BT_ADV_PAUSED);
114 		bt_le_adv_set_enable(adv, false);
115 	}
116 }
117 
adv_unpause_enabled(struct bt_le_ext_adv * adv,void * data)118 static void adv_unpause_enabled(struct bt_le_ext_adv *adv, void *data)
119 {
120 	if (atomic_test_and_clear_bit(adv->flags, BT_ADV_PAUSED)) {
121 		bt_le_adv_set_enable(adv, true);
122 	}
123 }
124 #endif /* defined(CONFIG_BT_SMP) */
125 
set_random_address(const bt_addr_t * addr)126 static int set_random_address(const bt_addr_t *addr)
127 {
128 	struct net_buf *buf;
129 	int err;
130 
131 	LOG_DBG("%s", bt_addr_str(addr));
132 
133 	/* Do nothing if we already have the right address */
134 	if (bt_addr_eq(addr, &bt_dev.random_addr.a)) {
135 		return 0;
136 	}
137 
138 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, sizeof(*addr));
139 	if (!buf) {
140 		return -ENOBUFS;
141 	}
142 
143 	net_buf_add_mem(buf, addr, sizeof(*addr));
144 
145 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RANDOM_ADDRESS, buf, NULL);
146 	if (err) {
147 		if (err == -EACCES) {
148 			/* If we are here we probably tried to set a random
149 			 * address while a legacy advertising, scanning or
150 			 * initiating is enabled, this is illegal.
151 			 *
152 			 * See Core Spec @ Vol 4, Part E 7.8.4
153 			 */
154 			LOG_WRN("cmd disallowed");
155 		}
156 		return err;
157 	}
158 
159 	bt_addr_copy(&bt_dev.random_addr.a, addr);
160 	bt_dev.random_addr.type = BT_ADDR_LE_RANDOM;
161 	return 0;
162 }
163 
bt_id_set_adv_random_addr(struct bt_le_ext_adv * adv,const bt_addr_t * addr)164 int bt_id_set_adv_random_addr(struct bt_le_ext_adv *adv,
165 			      const bt_addr_t *addr)
166 {
167 	struct bt_hci_cp_le_set_adv_set_random_addr *cp;
168 	struct net_buf *buf;
169 	int err;
170 
171 	CHECKIF(adv == NULL || addr == NULL) {
172 		return -EINVAL;
173 	}
174 
175 	if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
176 	      BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
177 		return set_random_address(addr);
178 	}
179 
180 	LOG_DBG("%s", bt_addr_str(addr));
181 
182 	if (!atomic_test_bit(adv->flags, BT_ADV_PARAMS_SET)) {
183 		bt_addr_copy(&adv->random_addr.a, addr);
184 		adv->random_addr.type = BT_ADDR_LE_RANDOM;
185 		atomic_set_bit(adv->flags, BT_ADV_RANDOM_ADDR_PENDING);
186 		return 0;
187 	}
188 
189 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR,
190 				sizeof(*cp));
191 	if (!buf) {
192 		return -ENOBUFS;
193 	}
194 
195 	cp = net_buf_add(buf, sizeof(*cp));
196 
197 	cp->handle = adv->handle;
198 	bt_addr_copy(&cp->bdaddr, addr);
199 
200 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR, buf,
201 				   NULL);
202 	if (err) {
203 		return err;
204 	}
205 
206 	if (&adv->random_addr.a != addr) {
207 		bt_addr_copy(&adv->random_addr.a, addr);
208 	}
209 	adv->random_addr.type = BT_ADDR_LE_RANDOM;
210 	return 0;
211 }
212 
213 /*	If rpa sharing is enabled, then rpa expired cb of adv-sets belonging
214  *	to same id is verified to return true. If not, adv-sets will continue
215  *	with old rpa through out the rpa rotations.
216  */
adv_rpa_expired(struct bt_le_ext_adv * adv,void * data)217 static void adv_rpa_expired(struct bt_le_ext_adv *adv, void *data)
218 {
219 	bool rpa_invalid = true;
220 #if defined(CONFIG_BT_EXT_ADV) && defined(CONFIG_BT_PRIVACY)
221 	/* Notify the user about the RPA timeout and set the RPA validity. */
222 	if (atomic_test_bit(adv->flags, BT_ADV_RPA_VALID) &&
223 	    adv->cb && adv->cb->rpa_expired) {
224 		rpa_invalid = adv->cb->rpa_expired(adv);
225 	}
226 #endif
227 
228 	if (IS_ENABLED(CONFIG_BT_RPA_SHARING)) {
229 
230 		if (adv->id >= bt_dev.id_count) {
231 			return;
232 		}
233 		bool *rpa_invalid_set_ptr = data;
234 
235 		if (!rpa_invalid) {
236 			rpa_invalid_set_ptr[adv->id] = false;
237 		}
238 	} else {
239 		if (rpa_invalid) {
240 			atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID);
241 		}
242 	}
243 }
244 
adv_rpa_invalidate(struct bt_le_ext_adv * adv,void * data)245 static void adv_rpa_invalidate(struct bt_le_ext_adv *adv, void *data)
246 {
247 	/* RPA of Advertisers limited by timeout or number of packets only expire
248 	 * when they are stopped.
249 	 */
250 	if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED) &&
251 	    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
252 		adv_rpa_expired(adv, data);
253 	}
254 }
255 
256 #if defined(CONFIG_BT_RPA_SHARING)
adv_rpa_clear_data(struct bt_le_ext_adv * adv,void * data)257 static void adv_rpa_clear_data(struct bt_le_ext_adv *adv, void *data)
258 {
259 	if (adv->id >= bt_dev.id_count) {
260 		return;
261 	}
262 	bool *rpa_invalid_set_ptr = data;
263 
264 	if (rpa_invalid_set_ptr[adv->id]) {
265 		atomic_clear_bit(adv->flags, BT_ADV_RPA_VALID);
266 		bt_addr_copy(&bt_dev.rpa[adv->id], BT_ADDR_NONE);
267 	} else {
268 		LOG_WRN("Adv sets rpa expired cb with id %d returns false\n", adv->id);
269 	}
270 }
271 #endif
272 
le_rpa_invalidate(void)273 static void le_rpa_invalidate(void)
274 {
275 	/* Invalidate RPA */
276 	if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
277 	      atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED))) {
278 		atomic_clear_bit(bt_dev.flags, BT_DEV_RPA_VALID);
279 	}
280 
281 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
282 
283 		if (bt_dev.id_count == 0) {
284 			return;
285 		}
286 		bool rpa_expired_data[bt_dev.id_count];
287 
288 		bt_le_ext_adv_foreach(adv_rpa_invalidate, &rpa_expired_data);
289 #if defined(CONFIG_BT_RPA_SHARING)
290 		/* rpa_expired data collected. now clear data based on data collected. */
291 		bt_le_ext_adv_foreach(adv_rpa_clear_data, &rpa_expired_data);
292 #endif
293 	}
294 }
295 
296 #if defined(CONFIG_BT_PRIVACY)
297 
298 #if defined(CONFIG_BT_RPA_TIMEOUT_DYNAMIC)
le_rpa_timeout_update(void)299 static void le_rpa_timeout_update(void)
300 {
301 	int err = 0;
302 
303 	if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_RPA_TIMEOUT_CHANGED)) {
304 		struct net_buf *buf;
305 		struct bt_hci_cp_le_set_rpa_timeout *cp;
306 
307 		buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_RPA_TIMEOUT,
308 					sizeof(*cp));
309 		if (!buf) {
310 			LOG_ERR("Failed to create HCI RPA timeout command");
311 			err = -ENOBUFS;
312 			goto submit;
313 		}
314 
315 		cp = net_buf_add(buf, sizeof(*cp));
316 		cp->rpa_timeout = sys_cpu_to_le16(bt_dev.rpa_timeout);
317 		err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_RPA_TIMEOUT, buf, NULL);
318 		if (err) {
319 			LOG_ERR("Failed to send HCI RPA timeout command");
320 			goto submit;
321 		}
322 	}
323 
324 submit:
325 	if (err) {
326 		atomic_set_bit(bt_dev.flags, BT_DEV_RPA_TIMEOUT_CHANGED);
327 	}
328 }
329 #endif
330 
le_rpa_timeout_submit(void)331 static void le_rpa_timeout_submit(void)
332 {
333 #if defined(CONFIG_BT_RPA_TIMEOUT_DYNAMIC)
334 	le_rpa_timeout_update();
335 #endif
336 
337 	(void)k_work_schedule(&bt_dev.rpa_update, K_SECONDS(bt_dev.rpa_timeout));
338 }
339 
340 /* this function sets new RPA only if current one is no longer valid */
bt_id_set_private_addr(uint8_t id)341 int bt_id_set_private_addr(uint8_t id)
342 {
343 	bt_addr_t rpa;
344 	int err;
345 
346 	CHECKIF(id >= CONFIG_BT_ID_MAX) {
347 		return -EINVAL;
348 	}
349 
350 	/* check if RPA is valid */
351 	if (atomic_test_bit(bt_dev.flags, BT_DEV_RPA_VALID)) {
352 		return 0;
353 	}
354 
355 	err = bt_rpa_create(bt_dev.irk[id], &rpa);
356 	if (!err) {
357 		err = set_random_address(&rpa);
358 		if (!err) {
359 			atomic_set_bit(bt_dev.flags, BT_DEV_RPA_VALID);
360 		}
361 	}
362 
363 	le_rpa_timeout_submit();
364 
365 	if (err) {
366 		return err;
367 	}
368 
369 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
370 		LOG_INF("RPA: %s", bt_addr_str(&rpa));
371 	}
372 
373 	return 0;
374 }
375 
376 #if defined(CONFIG_BT_RPA_SHARING)
adv_rpa_get(struct bt_le_ext_adv * adv,bt_addr_t * rpa)377 static int adv_rpa_get(struct bt_le_ext_adv *adv, bt_addr_t *rpa)
378 {
379 	int err;
380 
381 	if (bt_addr_eq(&bt_dev.rpa[adv->id], BT_ADDR_NONE)) {
382 		err = bt_rpa_create(bt_dev.irk[adv->id], &bt_dev.rpa[adv->id]);
383 		if (err) {
384 			return err;
385 		}
386 	}
387 
388 	bt_addr_copy(rpa, &bt_dev.rpa[adv->id]);
389 
390 	return 0;
391 }
392 #else
adv_rpa_get(struct bt_le_ext_adv * adv,bt_addr_t * rpa)393 static int adv_rpa_get(struct bt_le_ext_adv *adv, bt_addr_t *rpa)
394 {
395 	int err;
396 
397 	err = bt_rpa_create(bt_dev.irk[adv->id], rpa);
398 	if (err) {
399 		return err;
400 	}
401 
402 	return 0;
403 }
404 #endif /* defined(CONFIG_BT_RPA_SHARING) */
405 
bt_id_set_adv_private_addr(struct bt_le_ext_adv * adv)406 int bt_id_set_adv_private_addr(struct bt_le_ext_adv *adv)
407 {
408 	bt_addr_t rpa;
409 	int err;
410 
411 	CHECKIF(adv == NULL) {
412 		return -EINVAL;
413 	}
414 
415 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
416 	    (adv->options & BT_LE_ADV_OPT_USE_NRPA)) {
417 		/* The host doesn't support setting NRPAs when BT_PRIVACY=y.
418 		 * In that case you probably want to use an RPA anyway.
419 		 */
420 		LOG_ERR("NRPA not supported when BT_PRIVACY=y");
421 
422 		return -ENOSYS;
423 	}
424 
425 	if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
426 	      BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
427 		return bt_id_set_private_addr(adv->id);
428 	}
429 
430 	/* check if RPA is valid */
431 	if (atomic_test_bit(adv->flags, BT_ADV_RPA_VALID)) {
432 		/* Schedule the RPA timer if it is not running.
433 		 * The RPA may be valid without the timer running.
434 		 */
435 		if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED)) {
436 			le_rpa_timeout_submit();
437 		}
438 
439 		return 0;
440 	}
441 
442 	if (adv == bt_le_adv_lookup_legacy() && adv->id == BT_ID_DEFAULT) {
443 		/* Make sure that a Legacy advertiser using default ID has same
444 		 * RPA address as scanner roles.
445 		 */
446 		err = bt_id_set_private_addr(BT_ID_DEFAULT);
447 		if (err) {
448 			return err;
449 		}
450 
451 		err = bt_id_set_adv_random_addr(adv, &bt_dev.random_addr.a);
452 		if (!err) {
453 			atomic_set_bit(adv->flags, BT_ADV_RPA_VALID);
454 		}
455 
456 		return 0;
457 	}
458 
459 	err = adv_rpa_get(adv, &rpa);
460 	if (!err) {
461 		err = bt_id_set_adv_random_addr(adv, &rpa);
462 		if (!err) {
463 			atomic_set_bit(adv->flags, BT_ADV_RPA_VALID);
464 		}
465 	}
466 
467 	if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED)) {
468 		le_rpa_timeout_submit();
469 	}
470 
471 	if (err) {
472 		return err;
473 	}
474 
475 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
476 		LOG_INF("RPA: %s", bt_addr_str(&rpa));
477 	}
478 
479 	return 0;
480 }
481 #else
bt_id_set_private_addr(uint8_t id)482 int bt_id_set_private_addr(uint8_t id)
483 {
484 	bt_addr_t nrpa;
485 	int err;
486 
487 	CHECKIF(id >= CONFIG_BT_ID_MAX) {
488 		return -EINVAL;
489 	}
490 
491 	err = bt_rand(nrpa.val, sizeof(nrpa.val));
492 	if (err) {
493 		return err;
494 	}
495 
496 	BT_ADDR_SET_NRPA(&nrpa);
497 
498 	err = set_random_address(&nrpa);
499 	if (err)  {
500 		return err;
501 	}
502 
503 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
504 		LOG_INF("NRPA: %s", bt_addr_str(&nrpa));
505 	}
506 
507 	return 0;
508 }
509 
bt_id_set_adv_private_addr(struct bt_le_ext_adv * adv)510 int bt_id_set_adv_private_addr(struct bt_le_ext_adv *adv)
511 {
512 	bt_addr_t nrpa;
513 	int err;
514 
515 	CHECKIF(adv == NULL) {
516 		return -EINVAL;
517 	}
518 
519 	err = bt_rand(nrpa.val, sizeof(nrpa.val));
520 	if (err) {
521 		return err;
522 	}
523 
524 	BT_ADDR_SET_NRPA(&nrpa);
525 
526 	err = bt_id_set_adv_random_addr(adv, &nrpa);
527 	if (err) {
528 		return err;
529 	}
530 
531 	if (IS_ENABLED(CONFIG_BT_LOG_SNIFFER_INFO)) {
532 		LOG_INF("NRPA: %s", bt_addr_str(&nrpa));
533 	}
534 
535 	return 0;
536 }
537 #endif /* defined(CONFIG_BT_PRIVACY) */
538 
adv_pause_rpa(struct bt_le_ext_adv * adv,void * data)539 static void adv_pause_rpa(struct bt_le_ext_adv *adv, void *data)
540 {
541 	bool *adv_enabled = data;
542 
543 	/* Disable advertising sets to prepare them for RPA update. */
544 	if (atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
545 	    !atomic_test_bit(adv->flags, BT_ADV_LIMITED) &&
546 	    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
547 		int err;
548 
549 		err = bt_le_adv_set_enable_ext(adv, false, NULL);
550 		if (err) {
551 			LOG_ERR("Failed to disable advertising (err %d)", err);
552 		}
553 
554 		atomic_set_bit(adv->flags, BT_ADV_RPA_UPDATE);
555 		*adv_enabled = true;
556 	}
557 }
558 
le_adv_rpa_timeout(void)559 static bool le_adv_rpa_timeout(void)
560 {
561 	bool adv_enabled = false;
562 
563 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
564 		if (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
565 		    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
566 			/* Pause all advertising sets using RPAs */
567 			bt_le_ext_adv_foreach(adv_pause_rpa, &adv_enabled);
568 		} else {
569 			/* Check if advertising set is enabled */
570 			bt_le_ext_adv_foreach(adv_is_private_enabled, &adv_enabled);
571 		}
572 	}
573 
574 	return adv_enabled;
575 }
576 
adv_enable_rpa(struct bt_le_ext_adv * adv,void * data)577 static void adv_enable_rpa(struct bt_le_ext_adv *adv, void *data)
578 {
579 	if (atomic_test_and_clear_bit(adv->flags, BT_ADV_RPA_UPDATE)) {
580 		int err;
581 
582 		err = bt_id_set_adv_private_addr(adv);
583 		if (err) {
584 			LOG_WRN("Failed to update advertiser RPA address (%d)", err);
585 		}
586 
587 		err = bt_le_adv_set_enable_ext(adv, true, NULL);
588 		if (err) {
589 			LOG_ERR("Failed to enable advertising (err %d)", err);
590 		}
591 	}
592 }
593 
le_update_private_addr(void)594 static void le_update_private_addr(void)
595 {
596 	struct bt_le_ext_adv *adv = NULL;
597 	bool adv_enabled = false;
598 	uint8_t id = BT_ID_DEFAULT;
599 	int err;
600 
601 #if defined(CONFIG_BT_OBSERVER)
602 	bool scan_enabled = false;
603 
604 	if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
605 	    !(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
606 	      atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED))) {
607 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
608 		scan_enabled = true;
609 	}
610 #endif
611 	if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
612 	    atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
613 		/* Canceled initiating procedure will be restarted by
614 		 * connection complete event.
615 		 */
616 		bt_le_create_conn_cancel();
617 	}
618 
619 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
620 	    !(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
621 	      BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
622 		adv = bt_le_adv_lookup_legacy();
623 
624 		if (adv &&
625 		    atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
626 		    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
627 			adv_enabled = true;
628 			id = adv->id;
629 			bt_le_adv_set_enable_legacy(adv, false);
630 		}
631 	}
632 
633 	/* If both advertiser and scanner is running then the advertiser
634 	 * ID must be BT_ID_DEFAULT, this will update the RPA address
635 	 * for both roles.
636 	 */
637 	err = bt_id_set_private_addr(id);
638 	if (err) {
639 		LOG_WRN("Failed to update RPA address (%d)", err);
640 		return;
641 	}
642 
643 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
644 	    IS_ENABLED(CONFIG_BT_EXT_ADV) &&
645 	    BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features)) {
646 		bt_le_ext_adv_foreach(adv_enable_rpa, NULL);
647 	}
648 
649 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
650 	    adv && adv_enabled) {
651 		bt_le_adv_set_enable_legacy(adv, true);
652 	}
653 
654 #if defined(CONFIG_BT_OBSERVER)
655 	if (scan_enabled) {
656 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
657 	}
658 #endif
659 }
660 
le_force_rpa_timeout(void)661 static void le_force_rpa_timeout(void)
662 {
663 #if defined(CONFIG_BT_PRIVACY)
664 	struct k_work_sync sync;
665 
666 	k_work_cancel_delayable_sync(&bt_dev.rpa_update, &sync);
667 #endif
668 	(void)le_adv_rpa_timeout();
669 	le_rpa_invalidate();
670 	le_update_private_addr();
671 }
672 
673 #if defined(CONFIG_BT_PRIVACY)
rpa_timeout(struct k_work * work)674 static void rpa_timeout(struct k_work *work)
675 {
676 	bool adv_enabled;
677 
678 	LOG_DBG("");
679 
680 	if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
681 		struct bt_conn *conn =
682 			bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL,
683 						BT_CONN_SCAN_BEFORE_INITIATING);
684 
685 		if (conn) {
686 			bt_conn_unref(conn);
687 			bt_le_create_conn_cancel();
688 		}
689 	}
690 
691 	adv_enabled = le_adv_rpa_timeout();
692 	le_rpa_invalidate();
693 
694 	/* IF no roles using the RPA is running we can stop the RPA timer */
695 	if (IS_ENABLED(CONFIG_BT_CENTRAL)) {
696 		if (!(adv_enabled || atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING) ||
697 		      bt_le_scan_active_scanner_running())) {
698 			return;
699 		}
700 	}
701 
702 	le_update_private_addr();
703 }
704 #endif /* CONFIG_BT_PRIVACY */
705 
bt_id_scan_random_addr_check(void)706 bool bt_id_scan_random_addr_check(void)
707 {
708 	struct bt_le_ext_adv *adv;
709 
710 	if (!IS_ENABLED(CONFIG_BT_BROADCASTER) ||
711 	    (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
712 	     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
713 		/* Advertiser is not enabled or advertiser and scanner are using
714 		 * a different random address.
715 		 */
716 		return true;
717 	}
718 
719 	adv = bt_le_adv_lookup_legacy();
720 	if (!adv) {
721 		return true;
722 	}
723 
724 	/* If the advertiser is not active there is no issue */
725 	if (!atomic_test_bit(adv->flags, BT_ADV_ENABLED)) {
726 		return true;
727 	}
728 
729 	/* When privacy is enabled the random address will not be set
730 	 * immediately before starting the role, because the RPA might still be
731 	 * valid and only updated on RPA timeout.
732 	 */
733 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
734 		/* Cannot start scanner or initiator if the random address is
735 		 * used by the advertiser for an RPA with a different identity
736 		 * or for a random static identity address.
737 		 */
738 		if ((atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
739 		     bt_dev.id_addr[adv->id].type == BT_ADDR_LE_RANDOM) ||
740 		    adv->id != BT_ID_DEFAULT) {
741 			return false;
742 		}
743 	}
744 
745 	/* If privacy is not enabled then the random address will be attempted
746 	 * to be set before enabling the role. If another role is already using
747 	 * the random address then this command will fail, and should return
748 	 * the error code to the application.
749 	 */
750 	return true;
751 }
752 
bt_id_adv_random_addr_check(const struct bt_le_adv_param * param)753 bool bt_id_adv_random_addr_check(const struct bt_le_adv_param *param)
754 {
755 	CHECKIF(param == NULL) {
756 		return false;
757 	}
758 
759 	if (!IS_ENABLED(CONFIG_BT_OBSERVER) ||
760 	    (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
761 	     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
762 		/* If scanner roles are not enabled or advertiser and scanner
763 		 * are using a different random address.
764 		 */
765 		return true;
766 	}
767 
768 	/* If scanner roles are not active there is no issue. */
769 	if (!(atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING) ||
770 	      atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING))) {
771 		return true;
772 	}
773 
774 	/* When privacy is enabled the random address will not be set
775 	 * immediately before starting the role, because the RPA might still be
776 	 * valid and only updated on RPA timeout.
777 	 */
778 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
779 		/* Cannot start an advertiser with random static identity or
780 		 * using an RPA generated for a different identity than scanner
781 		 * roles.
782 		 */
783 		if (((param->options & BT_LE_ADV_OPT_USE_IDENTITY) &&
784 		     bt_dev.id_addr[param->id].type == BT_ADDR_LE_RANDOM) ||
785 		    param->id != BT_ID_DEFAULT) {
786 			return false;
787 		}
788 	} else if (IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
789 		   atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) &&
790 		   bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_RANDOM) {
791 		/* Scanning with random static identity. Stop the advertiser
792 		 * from overwriting the passive scanner identity address.
793 		 * In this case the LE Set Random Address command does not
794 		 * protect us in the case of a passive scanner.
795 		 * Explicitly stop it here.
796 		 */
797 
798 		if (!(param->options & _BT_LE_ADV_OPT_CONNECTABLE) &&
799 		     (param->options & BT_LE_ADV_OPT_USE_IDENTITY)) {
800 			/* Attempt to set non-connectable NRPA */
801 			return false;
802 		} else if (bt_dev.id_addr[param->id].type ==
803 			   BT_ADDR_LE_RANDOM &&
804 			   param->id != BT_ID_DEFAULT) {
805 			/* Attempt to set connectable, or non-connectable with
806 			 * identity different than scanner.
807 			 */
808 			return false;
809 		}
810 	}
811 
812 	/* If privacy is not enabled then the random address will be attempted
813 	 * to be set before enabling the role. If another role is already using
814 	 * the random address then this command will fail, and should return
815 	 * the error code to the application.
816 	 */
817 	return true;
818 }
819 
bt_id_adv_limited_stopped(struct bt_le_ext_adv * adv)820 void bt_id_adv_limited_stopped(struct bt_le_ext_adv *adv)
821 {
822 	adv_rpa_expired(adv, NULL);
823 }
824 
825 #if defined(CONFIG_BT_SMP)
le_set_privacy_mode(const bt_addr_le_t * addr,uint8_t mode)826 static int le_set_privacy_mode(const bt_addr_le_t *addr, uint8_t mode)
827 {
828 	struct bt_hci_cp_le_set_privacy_mode cp;
829 	struct net_buf *buf;
830 	int err;
831 
832 	/* Check if set privacy mode command is supported */
833 	if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
834 		LOG_WRN("Set privacy mode command is not supported");
835 		return 0;
836 	}
837 
838 	LOG_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
839 
840 	bt_addr_le_copy(&cp.id_addr, addr);
841 	cp.mode = mode;
842 
843 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_PRIVACY_MODE, sizeof(cp));
844 	if (!buf) {
845 		return -ENOBUFS;
846 	}
847 
848 	net_buf_add_mem(buf, &cp, sizeof(cp));
849 
850 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
851 	if (err) {
852 		return err;
853 	}
854 
855 	return 0;
856 }
857 
addr_res_enable(uint8_t enable)858 static int addr_res_enable(uint8_t enable)
859 {
860 	struct net_buf *buf;
861 
862 	LOG_DBG("%s", enable ? "enabled" : "disabled");
863 
864 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE, 1);
865 	if (!buf) {
866 		return -ENOBUFS;
867 	}
868 
869 	net_buf_add_u8(buf, enable);
870 
871 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE,
872 				    buf, NULL);
873 }
874 
hci_id_add(uint8_t id,const bt_addr_le_t * addr,uint8_t peer_irk[16])875 static int hci_id_add(uint8_t id, const bt_addr_le_t *addr, uint8_t peer_irk[16])
876 {
877 	struct bt_hci_cp_le_add_dev_to_rl *cp;
878 	struct net_buf *buf;
879 
880 	if (id >= CONFIG_BT_ID_MAX) {
881 		return -EINVAL;
882 	}
883 
884 	LOG_DBG("addr %s", bt_addr_le_str(addr));
885 
886 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_ADD_DEV_TO_RL, sizeof(*cp));
887 	if (!buf) {
888 		return -ENOBUFS;
889 	}
890 
891 	cp = net_buf_add(buf, sizeof(*cp));
892 	bt_addr_le_copy(&cp->peer_id_addr, addr);
893 	memcpy(cp->peer_irk, peer_irk, 16);
894 
895 #if defined(CONFIG_BT_PRIVACY)
896 	(void)memcpy(cp->local_irk, &bt_dev.irk[id], 16);
897 #else
898 	(void)memset(cp->local_irk, 0, 16);
899 #endif
900 
901 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
902 }
903 
pending_id_update(struct bt_keys * keys,void * data)904 static void pending_id_update(struct bt_keys *keys, void *data)
905 {
906 	if (keys->state & BT_KEYS_ID_PENDING_ADD) {
907 		keys->state &= ~BT_KEYS_ID_PENDING_ADD;
908 		bt_id_add(keys);
909 		return;
910 	}
911 
912 	if (keys->state & BT_KEYS_ID_PENDING_DEL) {
913 		keys->state &= ~BT_KEYS_ID_PENDING_DEL;
914 		bt_id_del(keys);
915 		return;
916 	}
917 }
918 
bt_id_pending_keys_update_set(struct bt_keys * keys,uint8_t flag)919 static void bt_id_pending_keys_update_set(struct bt_keys *keys, uint8_t flag)
920 {
921 	atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
922 	keys->state |= flag;
923 }
924 
bt_id_pending_keys_update(void)925 void bt_id_pending_keys_update(void)
926 {
927 	if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
928 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
929 		    IS_ENABLED(CONFIG_BT_PRIVACY)) {
930 			bt_keys_foreach_type(BT_KEYS_ALL, pending_id_update, NULL);
931 		} else {
932 			bt_keys_foreach_type(BT_KEYS_IRK, pending_id_update, NULL);
933 		}
934 	}
935 }
936 
937 struct bt_id_conflict {
938 	struct bt_keys *candidate;
939 	struct bt_keys *found;
940 };
941 
942 /* The Controller Resolve List is constrained by 7.8.38 "LE Add Device To
943  * Resolving List command". The Host is designed with the assumption that all
944  * local bonds can be put in the resolve list if there is room. Therefore we
945  * must refuse bonds that conflict in the resolve list. Notably, this prevents
946  * multiple local identities to bond with the same remote identity.
947  */
find_rl_conflict(struct bt_keys * resident,void * user_data)948 void find_rl_conflict(struct bt_keys *resident, void *user_data)
949 {
950 	struct bt_id_conflict *conflict = user_data;
951 	bool addr_conflict;
952 	bool irk_conflict;
953 
954 	__ASSERT_NO_MSG(conflict != NULL);
955 	__ASSERT_NO_MSG(conflict->candidate != NULL);
956 	__ASSERT_NO_MSG(resident != NULL);
957 	/* Only uncommitted bonds can be in conflict with committed bonds. */
958 	__ASSERT_NO_MSG((conflict->candidate->state & BT_KEYS_ID_ADDED) == 0);
959 
960 	if (conflict->found) {
961 		return;
962 	}
963 
964 	/* Test against committed bonds only. */
965 	if ((resident->state & BT_KEYS_ID_ADDED) == 0) {
966 		return;
967 	}
968 
969 	addr_conflict = bt_addr_le_eq(&conflict->candidate->addr, &resident->addr);
970 
971 	/* All-zero IRK is "no IRK", and does not conflict with other Zero-IRKs. */
972 	irk_conflict = (!bt_irk_eq(&conflict->candidate->irk, &(struct bt_irk){}) &&
973 			bt_irk_eq(&conflict->candidate->irk, &resident->irk));
974 
975 	if (addr_conflict || irk_conflict) {
976 		LOG_DBG("Resident : addr %s and IRK %s", bt_addr_le_str(&resident->addr),
977 			bt_hex(resident->irk.val, sizeof(resident->irk.val)));
978 		LOG_DBG("Candidate: addr %s and IRK %s", bt_addr_le_str(&conflict->candidate->addr),
979 			bt_hex(conflict->candidate->irk.val, sizeof(conflict->candidate->irk.val)));
980 
981 		conflict->found = resident;
982 	}
983 }
984 
bt_id_find_conflict(struct bt_keys * candidate)985 struct bt_keys *bt_id_find_conflict(struct bt_keys *candidate)
986 {
987 	struct bt_id_conflict conflict = {
988 		.candidate = candidate,
989 	};
990 
991 	bt_keys_foreach_type(BT_KEYS_IRK, find_rl_conflict, &conflict);
992 
993 	return conflict.found;
994 }
995 
bt_id_add(struct bt_keys * keys)996 void bt_id_add(struct bt_keys *keys)
997 {
998 	CHECKIF(keys == NULL) {
999 		return;
1000 	}
1001 
1002 	struct bt_conn *conn;
1003 	int err;
1004 
1005 	LOG_DBG("addr %s", bt_addr_le_str(&keys->addr));
1006 
1007 	__ASSERT_NO_MSG(keys != NULL);
1008 	/* We assume (and could assert) !bt_id_find_conflict(keys) here. */
1009 
1010 	/* Nothing to be done if host-side resolving is used */
1011 	if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
1012 		bt_dev.le.rl_entries++;
1013 		keys->state |= BT_KEYS_ID_ADDED;
1014 		return;
1015 	}
1016 
1017 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_INITIATING);
1018 	if (conn) {
1019 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD);
1020 		bt_conn_unref(conn);
1021 		return;
1022 	}
1023 
1024 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
1025 	    IS_ENABLED(CONFIG_BT_EXT_ADV)) {
1026 		bool adv_enabled = false;
1027 
1028 		bt_le_ext_adv_foreach(adv_is_limited_enabled, &adv_enabled);
1029 		if (adv_enabled) {
1030 			bt_id_pending_keys_update_set(keys,
1031 						   BT_KEYS_ID_PENDING_ADD);
1032 			return;
1033 		}
1034 	}
1035 
1036 #if defined(CONFIG_BT_OBSERVER)
1037 	bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
1038 
1039 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled &&
1040 	    atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) {
1041 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD);
1042 	}
1043 #endif
1044 
1045 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1046 		bt_le_ext_adv_foreach(adv_pause_enabled, NULL);
1047 	}
1048 
1049 #if defined(CONFIG_BT_OBSERVER)
1050 	if (scan_enabled) {
1051 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1052 	}
1053 #endif /* CONFIG_BT_OBSERVER */
1054 
1055 	/* If there are any existing entries address resolution will be on */
1056 	if (bt_dev.le.rl_entries) {
1057 		err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
1058 		if (err) {
1059 			LOG_WRN("Failed to disable address resolution");
1060 			goto done;
1061 		}
1062 	}
1063 
1064 	if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
1065 		LOG_WRN("Resolving list size exceeded. Switching to host.");
1066 
1067 		err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
1068 		if (err) {
1069 			LOG_ERR("Failed to clear resolution list");
1070 			goto done;
1071 		}
1072 
1073 		bt_dev.le.rl_entries++;
1074 		keys->state |= BT_KEYS_ID_ADDED;
1075 
1076 		goto done;
1077 	}
1078 
1079 	err = hci_id_add(keys->id, &keys->addr, keys->irk.val);
1080 	if (err) {
1081 		LOG_ERR("Failed to add IRK to controller");
1082 		goto done;
1083 	}
1084 
1085 	bt_dev.le.rl_entries++;
1086 	keys->state |= BT_KEYS_ID_ADDED;
1087 
1088 	/*
1089 	 * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
1090 	 *
1091 	 * By default, network privacy mode is used when private addresses are
1092 	 * resolved and generated by the Controller, so advertising packets from
1093 	 * peer devices that contain private addresses will only be accepted.
1094 	 * By changing to the device privacy mode device is only concerned about
1095 	 * its privacy and will accept advertising packets from peer devices
1096 	 * that contain their identity address as well as ones that contain
1097 	 * a private address, even if the peer device has distributed its IRK in
1098 	 * the past.
1099 	 */
1100 	err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
1101 	if (err) {
1102 		LOG_ERR("Failed to set privacy mode");
1103 		goto done;
1104 	}
1105 
1106 done:
1107 	addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
1108 
1109 #if defined(CONFIG_BT_OBSERVER)
1110 	if (scan_enabled) {
1111 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1112 	}
1113 #endif /* CONFIG_BT_OBSERVER */
1114 
1115 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1116 		bt_le_ext_adv_foreach(adv_unpause_enabled, NULL);
1117 	}
1118 }
1119 
keys_add_id(struct bt_keys * keys,void * data)1120 static void keys_add_id(struct bt_keys *keys, void *data)
1121 {
1122 	if (keys->state & BT_KEYS_ID_ADDED) {
1123 		hci_id_add(keys->id, &keys->addr, keys->irk.val);
1124 	}
1125 }
1126 
hci_id_del(const bt_addr_le_t * addr)1127 static int hci_id_del(const bt_addr_le_t *addr)
1128 {
1129 	struct bt_hci_cp_le_rem_dev_from_rl *cp;
1130 	struct net_buf *buf;
1131 
1132 	LOG_DBG("addr %s", bt_addr_le_str(addr));
1133 
1134 	buf = bt_hci_cmd_create(BT_HCI_OP_LE_REM_DEV_FROM_RL, sizeof(*cp));
1135 	if (!buf) {
1136 		return -ENOBUFS;
1137 	}
1138 
1139 	cp = net_buf_add(buf, sizeof(*cp));
1140 	bt_addr_le_copy(&cp->peer_id_addr, addr);
1141 
1142 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
1143 }
1144 
bt_id_del(struct bt_keys * keys)1145 void bt_id_del(struct bt_keys *keys)
1146 {
1147 	struct bt_conn *conn;
1148 	int err;
1149 
1150 	CHECKIF(keys == NULL) {
1151 		return;
1152 	}
1153 
1154 	LOG_DBG("addr %s", bt_addr_le_str(&keys->addr));
1155 
1156 	if (!bt_dev.le.rl_size ||
1157 	    bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
1158 		__ASSERT_NO_MSG(bt_dev.le.rl_entries > 0);
1159 		if (bt_dev.le.rl_entries > 0) {
1160 			bt_dev.le.rl_entries--;
1161 		}
1162 		keys->state &= ~BT_KEYS_ID_ADDED;
1163 		return;
1164 	}
1165 
1166 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_INITIATING);
1167 	if (conn) {
1168 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1169 		bt_conn_unref(conn);
1170 		return;
1171 	}
1172 
1173 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
1174 	    IS_ENABLED(CONFIG_BT_EXT_ADV)) {
1175 		bool adv_enabled = false;
1176 
1177 		bt_le_ext_adv_foreach(adv_is_limited_enabled, &adv_enabled);
1178 		if (adv_enabled) {
1179 			bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1180 			return;
1181 		}
1182 	}
1183 
1184 #if defined(CONFIG_BT_OBSERVER)
1185 	bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
1186 
1187 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled &&
1188 	    atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) {
1189 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1190 	}
1191 #endif /* CONFIG_BT_OBSERVER */
1192 
1193 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1194 		bt_le_ext_adv_foreach(adv_pause_enabled, NULL);
1195 	}
1196 
1197 #if defined(CONFIG_BT_OBSERVER)
1198 	if (scan_enabled) {
1199 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1200 	}
1201 #endif /* CONFIG_BT_OBSERVER */
1202 
1203 	err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
1204 	if (err) {
1205 		LOG_ERR("Disabling address resolution failed (err %d)", err);
1206 		goto done;
1207 	}
1208 
1209 	/* We checked size + 1 earlier, so here we know we can fit again */
1210 	if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
1211 		bt_dev.le.rl_entries--;
1212 		keys->state &= ~BT_KEYS_ID_ADDED;
1213 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1214 		    IS_ENABLED(CONFIG_BT_PRIVACY)) {
1215 			bt_keys_foreach_type(BT_KEYS_ALL, keys_add_id, NULL);
1216 		} else {
1217 			bt_keys_foreach_type(BT_KEYS_IRK, keys_add_id, NULL);
1218 		}
1219 		goto done;
1220 	}
1221 
1222 	err = hci_id_del(&keys->addr);
1223 	if (err) {
1224 		LOG_ERR("Failed to remove IRK from controller");
1225 		goto done;
1226 	}
1227 
1228 	bt_dev.le.rl_entries--;
1229 	keys->state &= ~BT_KEYS_ID_ADDED;
1230 
1231 done:
1232 	/* Only re-enable if there are entries to do resolving with */
1233 	if (bt_dev.le.rl_entries) {
1234 		addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
1235 	}
1236 
1237 #if defined(CONFIG_BT_OBSERVER)
1238 	if (scan_enabled) {
1239 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1240 	}
1241 #endif /* CONFIG_BT_OBSERVER */
1242 
1243 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1244 		bt_le_ext_adv_foreach(adv_unpause_enabled, NULL);
1245 	}
1246 }
1247 #endif /* defined(CONFIG_BT_SMP) */
1248 
bt_id_get(bt_addr_le_t * addrs,size_t * count)1249 void bt_id_get(bt_addr_le_t *addrs, size_t *count)
1250 {
1251 	if (addrs) {
1252 		size_t to_copy = MIN(*count, bt_dev.id_count);
1253 
1254 		memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
1255 		*count = to_copy;
1256 	} else {
1257 		*count = bt_dev.id_count;
1258 	}
1259 }
1260 
id_find(const bt_addr_le_t * addr)1261 static int id_find(const bt_addr_le_t *addr)
1262 {
1263 	uint8_t id;
1264 
1265 	for (id = 0U; id < bt_dev.id_count; id++) {
1266 		if (bt_addr_le_eq(addr, &bt_dev.id_addr[id])) {
1267 			return id;
1268 		}
1269 	}
1270 
1271 	return -ENOENT;
1272 }
1273 
id_create(uint8_t id,bt_addr_le_t * addr,uint8_t * irk)1274 static int id_create(uint8_t id, bt_addr_le_t *addr, uint8_t *irk)
1275 {
1276 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1277 		bt_addr_le_copy(&bt_dev.id_addr[id], addr);
1278 	} else {
1279 		bt_addr_le_t new_addr;
1280 
1281 		do {
1282 			int err;
1283 
1284 			err = bt_addr_le_create_static(&new_addr);
1285 			if (err) {
1286 				return err;
1287 			}
1288 			/* Make sure we didn't generate a duplicate */
1289 		} while (id_find(&new_addr) >= 0);
1290 
1291 		bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
1292 
1293 		if (addr) {
1294 			bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
1295 		}
1296 	}
1297 
1298 #if defined(CONFIG_BT_PRIVACY)
1299 	{
1300 		uint8_t zero_irk[16] = { 0 };
1301 
1302 		if (irk && memcmp(irk, zero_irk, 16)) {
1303 			memcpy(&bt_dev.irk[id], irk, 16);
1304 		} else {
1305 			int err;
1306 
1307 			err = bt_rand(&bt_dev.irk[id], 16);
1308 			if (err) {
1309 				return err;
1310 			}
1311 
1312 			if (irk) {
1313 				memcpy(irk, &bt_dev.irk[id], 16);
1314 			}
1315 		}
1316 
1317 #if defined(CONFIG_BT_RPA_SHARING)
1318 		bt_addr_copy(&bt_dev.rpa[id], BT_ADDR_NONE);
1319 #endif
1320 	}
1321 #endif
1322 	/* Only store if stack was already initialized. Before initialization
1323 	 * we don't know the flash content, so it's potentially harmful to
1324 	 * try to write anything there.
1325 	 */
1326 	if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
1327 	    atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1328 		(void)bt_settings_store_id();
1329 		(void)bt_settings_store_irk();
1330 	}
1331 
1332 	return 0;
1333 }
1334 
bt_id_create(bt_addr_le_t * addr,uint8_t * irk)1335 int bt_id_create(bt_addr_le_t *addr, uint8_t *irk)
1336 {
1337 	int new_id, err;
1338 
1339 	if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
1340 		return -EINVAL;
1341 	}
1342 
1343 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1344 		if (id_find(addr) >= 0) {
1345 			return -EALREADY;
1346 		}
1347 
1348 		if (addr->type == BT_ADDR_LE_PUBLIC && IS_ENABLED(CONFIG_BT_HCI_SET_PUBLIC_ADDR)) {
1349 			/* set the single public address */
1350 			if (bt_dev.id_count != 0) {
1351 				return -EALREADY;
1352 			}
1353 			bt_addr_le_copy(&bt_dev.id_addr[BT_ID_DEFAULT], addr);
1354 			bt_dev.id_count++;
1355 			return BT_ID_DEFAULT;
1356 		} else if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
1357 			LOG_ERR("Only random static identity address supported");
1358 			return -EINVAL;
1359 		}
1360 	}
1361 
1362 	if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
1363 		return -ENOMEM;
1364 	}
1365 
1366 	/* bt_rand is not available before Bluetooth enable has been called */
1367 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_ENABLE)) {
1368 		uint8_t zero_irk[16] = { 0 };
1369 
1370 		if (!(addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY))) {
1371 			return -EINVAL;
1372 		}
1373 
1374 		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1375 		    !(irk && memcmp(irk, zero_irk, 16))) {
1376 			return -EINVAL;
1377 		}
1378 	}
1379 
1380 	new_id = bt_dev.id_count++;
1381 	err = id_create(new_id, addr, irk);
1382 	if (err) {
1383 		bt_dev.id_count--;
1384 		return err;
1385 	}
1386 
1387 	return new_id;
1388 }
1389 
bt_id_reset(uint8_t id,bt_addr_le_t * addr,uint8_t * irk)1390 int bt_id_reset(uint8_t id, bt_addr_le_t *addr, uint8_t *irk)
1391 {
1392 	int err;
1393 
1394 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1395 		if (addr->type != BT_ADDR_LE_RANDOM ||
1396 		    !BT_ADDR_IS_STATIC(&addr->a)) {
1397 			LOG_ERR("Only static random identity address supported");
1398 			return -EINVAL;
1399 		}
1400 
1401 		if (id_find(addr) >= 0) {
1402 			return -EALREADY;
1403 		}
1404 	}
1405 
1406 	if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
1407 		return -EINVAL;
1408 	}
1409 
1410 	if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
1411 		return -EINVAL;
1412 	}
1413 
1414 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1415 		struct bt_adv_id_check_data check_data = {
1416 			.id = id,
1417 			.adv_enabled = false,
1418 		};
1419 
1420 		bt_le_ext_adv_foreach(adv_id_check_func, &check_data);
1421 		if (check_data.adv_enabled) {
1422 			return -EBUSY;
1423 		}
1424 	}
1425 
1426 	if (IS_ENABLED(CONFIG_BT_SMP) &&
1427 	    !bt_addr_le_eq(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
1428 		err = bt_unpair(id, NULL);
1429 		if (err) {
1430 			return err;
1431 		}
1432 	}
1433 
1434 	err = id_create(id, addr, irk);
1435 	if (err) {
1436 		return err;
1437 	}
1438 
1439 	return id;
1440 }
1441 
bt_id_delete(uint8_t id)1442 int bt_id_delete(uint8_t id)
1443 {
1444 	if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
1445 		return -EINVAL;
1446 	}
1447 
1448 	if (bt_addr_le_eq(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
1449 		return -EALREADY;
1450 	}
1451 
1452 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1453 		struct bt_adv_id_check_data check_data = {
1454 			.id = id,
1455 			.adv_enabled = false,
1456 		};
1457 
1458 		bt_le_ext_adv_foreach(adv_id_check_func, &check_data);
1459 		if (check_data.adv_enabled) {
1460 			return -EBUSY;
1461 		}
1462 	}
1463 
1464 	if (IS_ENABLED(CONFIG_BT_SMP)) {
1465 		int err;
1466 
1467 		err = bt_unpair(id, NULL);
1468 		if (err) {
1469 			return err;
1470 		}
1471 	}
1472 
1473 #if defined(CONFIG_BT_PRIVACY)
1474 	(void)memset(bt_dev.irk[id], 0, 16);
1475 #endif
1476 	bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
1477 
1478 	if (id == bt_dev.id_count - 1) {
1479 		bt_dev.id_count--;
1480 	}
1481 
1482 	if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
1483 	    atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1484 		(void)bt_settings_store_id();
1485 		(void)bt_settings_store_irk();
1486 	}
1487 
1488 	return 0;
1489 }
1490 
1491 #if defined(CONFIG_BT_PRIVACY)
bt_read_identity_root(uint8_t * ir)1492 static void bt_read_identity_root(uint8_t *ir)
1493 {
1494 	/* Invalid IR */
1495 	memset(ir, 0, 16);
1496 
1497 #if defined(CONFIG_BT_HCI_VS)
1498 	struct bt_hci_rp_vs_read_key_hierarchy_roots *rp;
1499 	struct net_buf *rsp;
1500 	int err;
1501 
1502 	if (!BT_VS_CMD_READ_KEY_ROOTS(bt_dev.vs_commands)) {
1503 		return;
1504 	}
1505 
1506 	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS, NULL,
1507 				   &rsp);
1508 	if (err) {
1509 		LOG_WRN("Failed to read identity root");
1510 		return;
1511 	}
1512 
1513 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1514 	    rsp->len != sizeof(struct bt_hci_rp_vs_read_key_hierarchy_roots)) {
1515 		LOG_WRN("Invalid Vendor HCI extensions");
1516 		net_buf_unref(rsp);
1517 		return;
1518 	}
1519 
1520 	rp = (void *)rsp->data;
1521 	memcpy(ir, rp->ir, 16);
1522 
1523 	net_buf_unref(rsp);
1524 #endif /* defined(CONFIG_BT_HCI_VS) */
1525 }
1526 #endif /* defined(CONFIG_BT_PRIVACY) */
1527 
bt_id_read_public_addr(bt_addr_le_t * addr)1528 uint8_t bt_id_read_public_addr(bt_addr_le_t *addr)
1529 {
1530 	struct bt_hci_rp_read_bd_addr *rp;
1531 	struct net_buf *rsp;
1532 	int err;
1533 
1534 	CHECKIF(addr == NULL) {
1535 		LOG_WRN("Invalid input parameters");
1536 		return 0U;
1537 	}
1538 
1539 	/* Read Bluetooth Address */
1540 	err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
1541 	if (err) {
1542 		LOG_WRN("Failed to read public address");
1543 		return 0U;
1544 	}
1545 
1546 	rp = (void *)rsp->data;
1547 
1548 	if (bt_addr_eq(&rp->bdaddr, BT_ADDR_ANY) ||
1549 	    bt_addr_eq(&rp->bdaddr, BT_ADDR_NONE)) {
1550 		LOG_DBG("Controller has no public address");
1551 		net_buf_unref(rsp);
1552 		return 0U;
1553 	}
1554 
1555 	bt_addr_copy(&addr->a, &rp->bdaddr);
1556 	addr->type = BT_ADDR_LE_PUBLIC;
1557 
1558 	net_buf_unref(rsp);
1559 	return 1U;
1560 }
1561 
bt_setup_public_id_addr(void)1562 int bt_setup_public_id_addr(void)
1563 {
1564 	bt_addr_le_t addr;
1565 	uint8_t *irk = NULL;
1566 
1567 	bt_dev.id_count = bt_id_read_public_addr(&addr);
1568 
1569 	if (!bt_dev.id_count) {
1570 		return 0;
1571 	}
1572 
1573 #if defined(CONFIG_BT_PRIVACY)
1574 	uint8_t ir_irk[16];
1575 	uint8_t ir[16];
1576 
1577 	bt_read_identity_root(ir);
1578 
1579 	if (!IS_ENABLED(CONFIG_BT_PRIVACY_RANDOMIZE_IR)) {
1580 		if (!bt_smp_irk_get(ir, ir_irk)) {
1581 			irk = ir_irk;
1582 		}
1583 	}
1584 #endif /* defined(CONFIG_BT_PRIVACY) */
1585 
1586 	/* If true, `id_create` will randomize the IRK. */
1587 	if (!irk && IS_ENABLED(CONFIG_BT_PRIVACY)) {
1588 		/* `id_create` will not store the id when called before BT_DEV_READY.
1589 		 * But since part of the id will be randomized, it needs to be stored.
1590 		 */
1591 		if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1592 			atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1593 		}
1594 	}
1595 
1596 	return id_create(BT_ID_DEFAULT, &addr, irk);
1597 }
1598 
vs_read_static_addr(struct bt_hci_vs_static_addr addrs[],uint8_t size)1599 static uint8_t vs_read_static_addr(struct bt_hci_vs_static_addr addrs[], uint8_t size)
1600 {
1601 #if defined(CONFIG_BT_HCI_VS)
1602 	struct bt_hci_rp_vs_read_static_addrs *rp;
1603 	struct net_buf *rsp;
1604 	int err, i;
1605 	uint8_t cnt;
1606 
1607 	if (!BT_VS_CMD_READ_STATIC_ADDRS(bt_dev.vs_commands)) {
1608 		LOG_WRN("Read Static Addresses command not available");
1609 		return 0;
1610 	}
1611 
1612 	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
1613 	if (err) {
1614 		LOG_WRN("Failed to read static addresses");
1615 		return 0;
1616 	}
1617 
1618 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1619 	    rsp->len < sizeof(struct bt_hci_rp_vs_read_static_addrs)) {
1620 		LOG_WRN("Invalid Vendor HCI extensions");
1621 		net_buf_unref(rsp);
1622 		return 0;
1623 	}
1624 
1625 	rp = (void *)rsp->data;
1626 	cnt = MIN(rp->num_addrs, size);
1627 
1628 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1629 	    rsp->len != (sizeof(struct bt_hci_rp_vs_read_static_addrs) +
1630 			 rp->num_addrs *
1631 			 sizeof(struct bt_hci_vs_static_addr))) {
1632 		LOG_WRN("Invalid Vendor HCI extensions");
1633 		net_buf_unref(rsp);
1634 		return 0;
1635 	}
1636 
1637 	for (i = 0; i < cnt; i++) {
1638 		memcpy(&addrs[i], &rp->a[i], sizeof(struct bt_hci_vs_static_addr));
1639 	}
1640 
1641 	net_buf_unref(rsp);
1642 	if (!cnt) {
1643 		LOG_WRN("No static addresses stored in controller");
1644 	}
1645 
1646 	return cnt;
1647 #else
1648 	return 0;
1649 #endif
1650 }
1651 
bt_setup_random_id_addr(void)1652 int bt_setup_random_id_addr(void)
1653 {
1654 	/* Only read the addresses if the user has not already configured one or
1655 	 * more identities (!bt_dev.id_count).
1656 	 */
1657 	if (IS_ENABLED(CONFIG_BT_HCI_VS) && !bt_dev.id_count) {
1658 		struct bt_hci_vs_static_addr addrs[CONFIG_BT_ID_MAX];
1659 
1660 		bt_dev.id_count = vs_read_static_addr(addrs, CONFIG_BT_ID_MAX);
1661 
1662 		for (uint8_t i = 0; i < bt_dev.id_count; i++) {
1663 			int err;
1664 			bt_addr_le_t addr;
1665 			uint8_t *irk = NULL;
1666 			uint8_t ir_irk[16];
1667 
1668 			if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1669 			    !IS_ENABLED(CONFIG_BT_PRIVACY_RANDOMIZE_IR)) {
1670 				if (!bt_smp_irk_get(addrs[i].ir, ir_irk)) {
1671 					irk = ir_irk;
1672 				}
1673 			}
1674 
1675 			/* If true, `id_create` will randomize the IRK. */
1676 			if (!irk && IS_ENABLED(CONFIG_BT_PRIVACY)) {
1677 				/* `id_create` will not store the id when called before
1678 				 * BT_DEV_READY. But since part of the id will be
1679 				 * randomized, it needs to be stored.
1680 				 */
1681 				if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1682 					atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1683 				}
1684 			}
1685 
1686 			bt_addr_copy(&addr.a, &addrs[i].bdaddr);
1687 			addr.type = BT_ADDR_LE_RANDOM;
1688 
1689 			err = id_create(i, &addr, irk);
1690 			if (err) {
1691 				return err;
1692 			}
1693 		}
1694 
1695 		if (bt_dev.id_count > 0) {
1696 			return 0;
1697 		}
1698 	}
1699 
1700 	if (IS_ENABLED(CONFIG_BT_PRIVACY) && IS_ENABLED(CONFIG_BT_SETTINGS)) {
1701 		atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1702 	}
1703 
1704 	return bt_id_create(NULL, NULL);
1705 }
1706 
1707 #if defined(CONFIG_BT_CENTRAL)
rpa_timeout_valid_check(void)1708 static inline bool rpa_timeout_valid_check(void)
1709 {
1710 #if defined(CONFIG_BT_PRIVACY)
1711 	uint32_t remaining_ms = k_ticks_to_ms_floor32(
1712 		k_work_delayable_remaining_get(&bt_dev.rpa_update));
1713 	/* Check if create conn timeout will happen before RPA timeout. */
1714 	return remaining_ms > (10 * bt_dev.create_param.timeout);
1715 #else
1716 	return true;
1717 #endif
1718 }
1719 
bt_id_set_create_conn_own_addr(bool use_filter,uint8_t * own_addr_type)1720 int bt_id_set_create_conn_own_addr(bool use_filter, uint8_t *own_addr_type)
1721 {
1722 	int err;
1723 
1724 	CHECKIF(own_addr_type == NULL) {
1725 		return -EINVAL;
1726 	}
1727 
1728 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
1729 		if (use_filter || rpa_timeout_valid_check()) {
1730 			err = bt_id_set_private_addr(BT_ID_DEFAULT);
1731 			if (err) {
1732 				return err;
1733 			}
1734 		} else {
1735 			/* Force new RPA timeout so that RPA timeout is not
1736 			 * triggered while direct initiator is active.
1737 			 */
1738 			le_force_rpa_timeout();
1739 		}
1740 
1741 		if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1742 			*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1743 		} else {
1744 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1745 		}
1746 	} else {
1747 		const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
1748 
1749 		/* If Static Random address is used as Identity address we
1750 		 * need to restore it before creating connection. Otherwise
1751 		 * NRPA used for active scan could be used for connection.
1752 		 */
1753 		if (addr->type == BT_ADDR_LE_RANDOM) {
1754 			err = set_random_address(&addr->a);
1755 			if (err) {
1756 				return err;
1757 			}
1758 
1759 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1760 		} else {
1761 			/* If address type is not random, it's public. If it's public then we assume
1762 			 * it's the Controller's public address.
1763 			 */
1764 			*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1765 		}
1766 	}
1767 
1768 	return 0;
1769 }
1770 #endif /* defined(CONFIG_BT_CENTRAL) */
1771 
1772 #if defined(CONFIG_BT_OBSERVER)
is_adv_using_rand_addr(void)1773 static bool is_adv_using_rand_addr(void)
1774 {
1775 	struct bt_le_ext_adv *adv;
1776 
1777 	if (!IS_ENABLED(CONFIG_BT_BROADCASTER) ||
1778 	    (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1779 	     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
1780 		/* When advertising is not enabled or is using extended
1781 		 * advertising HCI commands then only the scanner uses the set
1782 		 * random address command.
1783 		 */
1784 		return false;
1785 	}
1786 
1787 	adv = bt_le_adv_lookup_legacy();
1788 
1789 	return adv && atomic_test_bit(adv->flags, BT_ADV_ENABLED);
1790 }
1791 
bt_id_set_scan_own_addr(bool active_scan,uint8_t * own_addr_type)1792 int bt_id_set_scan_own_addr(bool active_scan, uint8_t *own_addr_type)
1793 {
1794 	int err;
1795 
1796 	CHECKIF(own_addr_type == NULL) {
1797 		return -EINVAL;
1798 	}
1799 
1800 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
1801 
1802 		if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1803 			*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1804 		} else {
1805 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1806 		}
1807 
1808 		err = bt_id_set_private_addr(BT_ID_DEFAULT);
1809 		if (err == -EACCES && (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) ||
1810 				       atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING))) {
1811 			LOG_WRN("Set random addr failure ignored in scan/init state");
1812 
1813 			return 0;
1814 		} else if (err) {
1815 			return err;
1816 		}
1817 	} else {
1818 		/* Use NRPA unless identity has been explicitly requested
1819 		 * (through Kconfig).
1820 		 * Use same RPA as legacy advertiser if advertising.
1821 		 */
1822 		if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
1823 		    !is_adv_using_rand_addr()) {
1824 			err = bt_id_set_private_addr(BT_ID_DEFAULT);
1825 			if (err) {
1826 				if (active_scan || !is_adv_using_rand_addr()) {
1827 					return err;
1828 				}
1829 
1830 				LOG_WRN("Ignoring failure to set address for passive scan (%d)",
1831 					err);
1832 			}
1833 
1834 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1835 		} else if (IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY)) {
1836 			if (bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_RANDOM) {
1837 				/* If scanning with Identity Address we must set the
1838 				 * random identity address for both active and passive
1839 				 * scanner in order to receive adv reports that are
1840 				 * directed towards this identity.
1841 				 */
1842 				err = set_random_address(&bt_dev.id_addr[BT_ID_DEFAULT].a);
1843 				if (err) {
1844 					return err;
1845 				}
1846 
1847 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1848 			} else if (bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_PUBLIC) {
1849 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1850 			}
1851 		}
1852 	}
1853 
1854 	return 0;
1855 }
1856 #endif /* defined(CONFIG_BT_OBSERVER) */
1857 
bt_id_set_adv_own_addr(struct bt_le_ext_adv * adv,uint32_t options,bool dir_adv,uint8_t * own_addr_type)1858 int bt_id_set_adv_own_addr(struct bt_le_ext_adv *adv, uint32_t options,
1859 			   bool dir_adv, uint8_t *own_addr_type)
1860 {
1861 	const bt_addr_le_t *id_addr;
1862 	int err = 0;
1863 
1864 	CHECKIF(adv == NULL || own_addr_type == NULL) {
1865 		return -EINVAL;
1866 	}
1867 
1868 	/* Set which local identity address we're advertising with */
1869 	id_addr = &bt_dev.id_addr[adv->id];
1870 
1871 	/* Short-circuit to force NRPA usage */
1872 	if (options & BT_LE_ADV_OPT_USE_NRPA) {
1873 		if (options & BT_LE_ADV_OPT_USE_IDENTITY) {
1874 			LOG_ERR("Can't set both IDENTITY & NRPA");
1875 
1876 			return -EINVAL;
1877 		}
1878 
1879 		err = bt_id_set_adv_private_addr(adv);
1880 		if (err) {
1881 			return err;
1882 		}
1883 		*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1884 
1885 		return 0;
1886 	}
1887 
1888 	if (options & _BT_LE_ADV_OPT_CONNECTABLE) {
1889 		if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA) &&
1890 		    !BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1891 			return -ENOTSUP;
1892 		}
1893 
1894 		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1895 		    !(options & BT_LE_ADV_OPT_USE_IDENTITY)) {
1896 			err = bt_id_set_adv_private_addr(adv);
1897 			if (err) {
1898 				return err;
1899 			}
1900 
1901 			if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
1902 				*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1903 			} else {
1904 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1905 			}
1906 		} else {
1907 			/*
1908 			 * If Static Random address is used as Identity
1909 			 * address we need to restore it before advertising
1910 			 * is enabled. Otherwise NRPA used for active scan
1911 			 * could be used for advertising.
1912 			 */
1913 			if (id_addr->type == BT_ADDR_LE_RANDOM) {
1914 				err = bt_id_set_adv_random_addr(adv, &id_addr->a);
1915 				if (err) {
1916 					return err;
1917 				}
1918 
1919 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1920 			} else if (id_addr->type == BT_ADDR_LE_PUBLIC) {
1921 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1922 			}
1923 
1924 			if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
1925 				*own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
1926 			}
1927 		}
1928 	} else {
1929 		if (options & BT_LE_ADV_OPT_USE_IDENTITY) {
1930 			if (id_addr->type == BT_ADDR_LE_RANDOM) {
1931 				err = bt_id_set_adv_random_addr(adv, &id_addr->a);
1932 				if (err) {
1933 					return err;
1934 				}
1935 
1936 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1937 			} else if (id_addr->type == BT_ADDR_LE_PUBLIC) {
1938 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1939 			}
1940 
1941 			if (options & BT_LE_ADV_OPT_DIR_ADDR_RPA) {
1942 				*own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
1943 			}
1944 		} else if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1945 			     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
1946 			/* In case advertising set random address is not
1947 			 * available we must handle the shared random address
1948 			 * problem.
1949 			 */
1950 #if defined(CONFIG_BT_OBSERVER)
1951 			bool scan_enabled = false;
1952 
1953 			/* If active scan with NRPA is ongoing refresh NRPA */
1954 			if (!IS_ENABLED(CONFIG_BT_PRIVACY) &&
1955 			    !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
1956 			    atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
1957 				scan_enabled = true;
1958 				bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1959 			}
1960 #endif /* defined(CONFIG_BT_OBSERVER) */
1961 			err = bt_id_set_adv_private_addr(adv);
1962 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1963 
1964 #if defined(CONFIG_BT_OBSERVER)
1965 			if (scan_enabled) {
1966 				bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1967 			}
1968 #endif /* defined(CONFIG_BT_OBSERVER) */
1969 		} else {
1970 			err = bt_id_set_adv_private_addr(adv);
1971 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1972 		}
1973 
1974 		if (err) {
1975 			return err;
1976 		}
1977 	}
1978 
1979 	return 0;
1980 }
1981 
1982 #if defined(CONFIG_BT_CLASSIC)
bt_br_oob_get_local(struct bt_br_oob * oob)1983 int bt_br_oob_get_local(struct bt_br_oob *oob)
1984 {
1985 	CHECKIF(oob == NULL) {
1986 		return -EINVAL;
1987 	}
1988 
1989 	bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
1990 
1991 	return 0;
1992 }
1993 #endif /* CONFIG_BT_CLASSIC */
1994 
bt_le_oob_get_local(uint8_t id,struct bt_le_oob * oob)1995 int bt_le_oob_get_local(uint8_t id, struct bt_le_oob *oob)
1996 {
1997 	struct bt_le_ext_adv *adv = NULL;
1998 	int err;
1999 
2000 	CHECKIF(oob == NULL) {
2001 		return -EINVAL;
2002 	}
2003 
2004 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2005 		return -EAGAIN;
2006 	}
2007 
2008 	if (id >= CONFIG_BT_ID_MAX) {
2009 		return -EINVAL;
2010 	}
2011 
2012 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
2013 		adv = bt_le_adv_lookup_legacy();
2014 	}
2015 
2016 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
2017 	    !(adv && adv->id == id &&
2018 	      atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
2019 	      atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
2020 	      bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) {
2021 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2022 		    atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
2023 			struct bt_conn *conn;
2024 
2025 			conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL,
2026 						       BT_CONN_SCAN_BEFORE_INITIATING);
2027 			if (conn) {
2028 				/* Cannot set new RPA while creating
2029 				 * connections.
2030 				 */
2031 				bt_conn_unref(conn);
2032 				return -EINVAL;
2033 			}
2034 		}
2035 
2036 		if (adv &&
2037 		    atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
2038 		    atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
2039 		    (bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) {
2040 			/* Cannot set a new RPA address while advertising with
2041 			 * random static identity address for a different
2042 			 * identity.
2043 			 */
2044 			return -EINVAL;
2045 		}
2046 
2047 		if (IS_ENABLED(CONFIG_BT_OBSERVER) &&
2048 		    CONFIG_BT_ID_MAX > 1 &&
2049 		    id != BT_ID_DEFAULT &&
2050 		    (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) ||
2051 		     atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING))) {
2052 			/* Cannot switch identity of scanner or initiator */
2053 			return -EINVAL;
2054 		}
2055 
2056 		le_force_rpa_timeout();
2057 
2058 		bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
2059 	} else {
2060 		bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
2061 	}
2062 
2063 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2064 		err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
2065 		if (err && err != -ENOTSUP) {
2066 			return err;
2067 		}
2068 	}
2069 
2070 	return 0;
2071 }
2072 
2073 #if defined(CONFIG_BT_EXT_ADV)
bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv * adv,struct bt_le_oob * oob)2074 int bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv *adv,
2075 				struct bt_le_oob *oob)
2076 {
2077 	int err;
2078 
2079 	CHECKIF(adv == NULL || oob == NULL) {
2080 		return -EINVAL;
2081 	}
2082 
2083 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2084 		return -EAGAIN;
2085 	}
2086 
2087 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
2088 	    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
2089 		/* Don't refresh RPA addresses if the RPA is new.
2090 		 * This allows back to back calls to this function or
2091 		 * bt_le_oob_get_local to not invalidate the previously set
2092 		 * RPAs.
2093 		 */
2094 		if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED) &&
2095 		    !bt_id_rpa_is_new()) {
2096 			if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2097 			    atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
2098 				struct bt_conn *conn;
2099 
2100 				conn = bt_conn_lookup_state_le(
2101 					BT_ID_DEFAULT, NULL,
2102 					BT_CONN_SCAN_BEFORE_INITIATING);
2103 
2104 				if (conn) {
2105 					/* Cannot set new RPA while creating
2106 					 * connections.
2107 					 */
2108 					bt_conn_unref(conn);
2109 					return -EINVAL;
2110 				}
2111 			}
2112 
2113 			le_force_rpa_timeout();
2114 		}
2115 
2116 		bt_addr_le_copy(&oob->addr, &adv->random_addr);
2117 	} else {
2118 		bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[adv->id]);
2119 	}
2120 
2121 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2122 		err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
2123 		if (err && err != -ENOTSUP) {
2124 			return err;
2125 		}
2126 	}
2127 
2128 	return 0;
2129 }
2130 #endif /* defined(CONFIG_BT_EXT_ADV) */
2131 
2132 #if defined(CONFIG_BT_SMP)
2133 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_le_oob_set_legacy_tk(struct bt_conn * conn,const uint8_t * tk)2134 int bt_le_oob_set_legacy_tk(struct bt_conn *conn, const uint8_t *tk)
2135 {
2136 	CHECKIF(conn == NULL || tk == NULL) {
2137 		return -EINVAL;
2138 	}
2139 
2140 	return bt_smp_le_oob_set_tk(conn, tk);
2141 }
2142 #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */
2143 
2144 #if !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY)
bt_le_oob_set_sc_data(struct bt_conn * conn,const struct bt_le_oob_sc_data * oobd_local,const struct bt_le_oob_sc_data * oobd_remote)2145 int bt_le_oob_set_sc_data(struct bt_conn *conn,
2146 			  const struct bt_le_oob_sc_data *oobd_local,
2147 			  const struct bt_le_oob_sc_data *oobd_remote)
2148 {
2149 	CHECKIF(conn == NULL) {
2150 		return -EINVAL;
2151 	}
2152 
2153 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2154 		return -EAGAIN;
2155 	}
2156 
2157 	return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
2158 }
2159 
bt_le_oob_get_sc_data(struct bt_conn * conn,const struct bt_le_oob_sc_data ** oobd_local,const struct bt_le_oob_sc_data ** oobd_remote)2160 int bt_le_oob_get_sc_data(struct bt_conn *conn,
2161 			  const struct bt_le_oob_sc_data **oobd_local,
2162 			  const struct bt_le_oob_sc_data **oobd_remote)
2163 {
2164 	CHECKIF(conn == NULL) {
2165 		return -EINVAL;
2166 	}
2167 
2168 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2169 		return -EAGAIN;
2170 	}
2171 
2172 	return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
2173 }
2174 #endif /* !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) */
2175 #endif /* defined(CONFIG_BT_SMP) */
2176 
bt_id_init(void)2177 int bt_id_init(void)
2178 {
2179 	int err;
2180 
2181 #if defined(CONFIG_BT_PRIVACY)
2182 	k_work_init_delayable(&bt_dev.rpa_update, rpa_timeout);
2183 #if defined(CONFIG_BT_RPA_SHARING)
2184 	for (uint8_t id = 0U; id < ARRAY_SIZE(bt_dev.rpa); id++) {
2185 		bt_addr_copy(&bt_dev.rpa[id], BT_ADDR_NONE);
2186 	}
2187 #endif
2188 #endif
2189 
2190 	if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
2191 		LOG_DBG("No user identity. Trying to set public.");
2192 
2193 		err = bt_setup_public_id_addr();
2194 		if (err) {
2195 			LOG_ERR("Unable to set identity address");
2196 			return err;
2197 		}
2198 	}
2199 
2200 	if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
2201 		LOG_DBG("No public address. Trying to set static random.");
2202 
2203 		err = bt_setup_random_id_addr();
2204 		if (err) {
2205 			LOG_ERR("Unable to set identity address");
2206 			return err;
2207 		}
2208 
2209 		/* The passive scanner just sends a dummy address type in the
2210 		 * command. If the first activity does this, and the dummy type
2211 		 * is a random address, it needs a valid value, even though it's
2212 		 * not actually used.
2213 		 */
2214 		err = set_random_address(&bt_dev.id_addr[0].a);
2215 		if (err) {
2216 			LOG_ERR("Unable to set random address");
2217 			return err;
2218 		}
2219 	}
2220 
2221 	return 0;
2222 }
2223