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