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_CONNECTABLE) &&
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 ==
811 			   BT_ADDR_LE_RANDOM &&
812 			   param->id != BT_ID_DEFAULT) {
813 			/* Attempt to set connectable, or non-connectable with
814 			 * identity different than scanner.
815 			 */
816 			return false;
817 		}
818 	}
819 
820 	/* If privacy is not enabled then the random address will be attempted
821 	 * to be set before enabling the role. If another role is already using
822 	 * the random address then this command will fail, and should return
823 	 * the error code to the application.
824 	 */
825 	return true;
826 }
827 
bt_id_adv_limited_stopped(struct bt_le_ext_adv * adv)828 void bt_id_adv_limited_stopped(struct bt_le_ext_adv *adv)
829 {
830 	adv_rpa_expired(adv, NULL);
831 }
832 
833 #if defined(CONFIG_BT_SMP)
le_set_privacy_mode(const bt_addr_le_t * addr,uint8_t mode)834 static int le_set_privacy_mode(const bt_addr_le_t *addr, uint8_t mode)
835 {
836 	struct bt_hci_cp_le_set_privacy_mode cp;
837 	struct net_buf *buf;
838 	int err;
839 
840 	/* Check if set privacy mode command is supported */
841 	if (!BT_CMD_TEST(bt_dev.supported_commands, 39, 2)) {
842 		LOG_WRN("Set privacy mode command is not supported");
843 		return 0;
844 	}
845 
846 	LOG_DBG("addr %s mode 0x%02x", bt_addr_le_str(addr), mode);
847 
848 	bt_addr_le_copy(&cp.id_addr, addr);
849 	cp.mode = mode;
850 
851 	buf = bt_hci_cmd_alloc(K_FOREVER);
852 	if (!buf) {
853 		return -ENOBUFS;
854 	}
855 
856 	net_buf_add_mem(buf, &cp, sizeof(cp));
857 
858 	err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_PRIVACY_MODE, buf, NULL);
859 	if (err) {
860 		return err;
861 	}
862 
863 	return 0;
864 }
865 
addr_res_enable(uint8_t enable)866 static int addr_res_enable(uint8_t enable)
867 {
868 	struct net_buf *buf;
869 
870 	LOG_DBG("%s", enable ? "enabled" : "disabled");
871 
872 	buf = bt_hci_cmd_alloc(K_FOREVER);
873 	if (!buf) {
874 		return -ENOBUFS;
875 	}
876 
877 	net_buf_add_u8(buf, enable);
878 
879 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADDR_RES_ENABLE,
880 				    buf, NULL);
881 }
882 
hci_id_add(uint8_t id,const bt_addr_le_t * addr,uint8_t peer_irk[16])883 static int hci_id_add(uint8_t id, const bt_addr_le_t *addr, uint8_t peer_irk[16])
884 {
885 	struct bt_hci_cp_le_add_dev_to_rl *cp;
886 	struct net_buf *buf;
887 
888 	if (id >= CONFIG_BT_ID_MAX) {
889 		return -EINVAL;
890 	}
891 
892 	LOG_DBG("addr %s", bt_addr_le_str(addr));
893 
894 	buf = bt_hci_cmd_alloc(K_FOREVER);
895 	if (!buf) {
896 		return -ENOBUFS;
897 	}
898 
899 	cp = net_buf_add(buf, sizeof(*cp));
900 	bt_addr_le_copy(&cp->peer_id_addr, addr);
901 	memcpy(cp->peer_irk, peer_irk, 16);
902 
903 #if defined(CONFIG_BT_PRIVACY)
904 	(void)memcpy(cp->local_irk, &bt_dev.irk[id], 16);
905 #else
906 	(void)memset(cp->local_irk, 0, 16);
907 #endif
908 
909 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_ADD_DEV_TO_RL, buf, NULL);
910 }
911 
pending_id_update(struct bt_keys * keys,void * data)912 static void pending_id_update(struct bt_keys *keys, void *data)
913 {
914 	if (keys->state & BT_KEYS_ID_PENDING_ADD) {
915 		keys->state &= ~BT_KEYS_ID_PENDING_ADD;
916 		bt_id_add(keys);
917 		return;
918 	}
919 
920 	if (keys->state & BT_KEYS_ID_PENDING_DEL) {
921 		keys->state &= ~BT_KEYS_ID_PENDING_DEL;
922 		bt_id_del(keys);
923 		return;
924 	}
925 }
926 
bt_id_pending_keys_update_set(struct bt_keys * keys,uint8_t flag)927 void bt_id_pending_keys_update_set(struct bt_keys *keys, uint8_t flag)
928 {
929 	atomic_set_bit(bt_dev.flags, BT_DEV_ID_PENDING);
930 	keys->state |= flag;
931 }
932 
bt_id_pending_keys_update(void)933 void bt_id_pending_keys_update(void)
934 {
935 	if (atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_ID_PENDING)) {
936 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
937 		    IS_ENABLED(CONFIG_BT_PRIVACY)) {
938 			bt_keys_foreach_type(BT_KEYS_ALL, pending_id_update, NULL);
939 		} else {
940 			bt_keys_foreach_type(BT_KEYS_IRK, pending_id_update, NULL);
941 		}
942 	}
943 }
944 
945 struct bt_id_conflict {
946 	struct bt_keys *candidate;
947 	struct bt_keys *found;
948 };
949 
950 /* The Controller Resolve List is constrained by 7.8.38 "LE Add Device To
951  * Resolving List command". The Host is designed with the assumption that all
952  * local bonds can be put in the resolve list if there is room. Therefore we
953  * must refuse bonds that conflict in the resolve list. Notably, this prevents
954  * multiple local identities to bond with the same remote identity.
955  */
find_rl_conflict(struct bt_keys * resident,void * user_data)956 void find_rl_conflict(struct bt_keys *resident, void *user_data)
957 {
958 	struct bt_id_conflict *conflict = user_data;
959 	bool addr_conflict;
960 	bool irk_conflict;
961 
962 	__ASSERT_NO_MSG(conflict != NULL);
963 	__ASSERT_NO_MSG(conflict->candidate != NULL);
964 	__ASSERT_NO_MSG(resident != NULL);
965 	/* Only uncommitted bonds can be in conflict with committed bonds. */
966 	__ASSERT_NO_MSG((conflict->candidate->state & BT_KEYS_ID_ADDED) == 0);
967 
968 	if (conflict->found) {
969 		return;
970 	}
971 
972 	/* Test against committed bonds only. */
973 	if ((resident->state & BT_KEYS_ID_ADDED) == 0) {
974 		return;
975 	}
976 
977 	addr_conflict = bt_addr_le_eq(&conflict->candidate->addr, &resident->addr);
978 
979 	/* All-zero IRK is "no IRK", and does not conflict with other Zero-IRKs. */
980 	irk_conflict = (!bt_irk_eq(&conflict->candidate->irk, &(struct bt_irk){}) &&
981 			bt_irk_eq(&conflict->candidate->irk, &resident->irk));
982 
983 	if (addr_conflict || irk_conflict) {
984 		LOG_DBG("Resident : addr %s and IRK %s, id: %d", bt_addr_le_str(&resident->addr),
985 			bt_hex(resident->irk.val, sizeof(resident->irk.val)), resident->id);
986 		LOG_DBG("Candidate: addr %s and IRK %s, id: %d",
987 			bt_addr_le_str(&conflict->candidate->addr),
988 			bt_hex(conflict->candidate->irk.val, sizeof(conflict->candidate->irk.val)),
989 			conflict->candidate->id);
990 
991 		conflict->found = resident;
992 	}
993 }
994 
bt_id_find_conflict(struct bt_keys * candidate)995 struct bt_keys *bt_id_find_conflict(struct bt_keys *candidate)
996 {
997 	struct bt_id_conflict conflict = {
998 		.candidate = candidate,
999 	};
1000 
1001 	bt_keys_foreach_type(BT_KEYS_IRK, find_rl_conflict, &conflict);
1002 
1003 	return conflict.found;
1004 }
1005 
bt_id_add(struct bt_keys * keys)1006 void bt_id_add(struct bt_keys *keys)
1007 {
1008 	CHECKIF(keys == NULL) {
1009 		return;
1010 	}
1011 
1012 	struct bt_conn *conn;
1013 	int err;
1014 	bool enable_controller_res = true;
1015 
1016 	LOG_DBG("addr %s", bt_addr_le_str(&keys->addr));
1017 
1018 	__ASSERT_NO_MSG(keys != NULL);
1019 	/* We assume (and could assert) !bt_id_find_conflict(keys) here. */
1020 
1021 	/* Nothing to be done if host-side resolving is used */
1022 	if (!bt_dev.le.rl_size || bt_dev.le.rl_entries > bt_dev.le.rl_size) {
1023 		bt_dev.le.rl_entries++;
1024 		keys->state |= BT_KEYS_ID_ADDED;
1025 		return;
1026 	}
1027 
1028 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_INITIATING);
1029 	if (conn) {
1030 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD);
1031 		bt_conn_unref(conn);
1032 		return;
1033 	}
1034 
1035 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
1036 	    IS_ENABLED(CONFIG_BT_EXT_ADV)) {
1037 		bool adv_enabled = false;
1038 
1039 		bt_le_ext_adv_foreach(adv_is_limited_enabled, &adv_enabled);
1040 		if (adv_enabled) {
1041 			bt_id_pending_keys_update_set(keys,
1042 						   BT_KEYS_ID_PENDING_ADD);
1043 			return;
1044 		}
1045 	}
1046 
1047 #if defined(CONFIG_BT_OBSERVER)
1048 	bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
1049 
1050 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled &&
1051 	    atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) {
1052 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD);
1053 	}
1054 #endif
1055 
1056 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1057 		bt_le_ext_adv_foreach(adv_pause_enabled, NULL);
1058 	}
1059 
1060 #if defined(CONFIG_BT_OBSERVER)
1061 	if (scan_enabled) {
1062 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1063 	}
1064 #endif /* CONFIG_BT_OBSERVER */
1065 
1066 	/* If there are any existing entries address resolution will be on */
1067 	if (bt_dev.le.rl_entries) {
1068 		err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
1069 		if (err) {
1070 			LOG_WRN("Failed to disable address resolution");
1071 			/* If it fails to disable, it should already be enabled,
1072 			 * don't need to enable again.
1073 			 */
1074 			enable_controller_res = false;
1075 			goto done;
1076 		}
1077 	}
1078 
1079 	if (bt_dev.le.rl_entries == bt_dev.le.rl_size) {
1080 		LOG_WRN("Resolving list size exceeded. Switching to host.");
1081 
1082 		/* Since the controller resolving list is cleared,
1083 		 * don't need to enable the address resolution.
1084 		 */
1085 		enable_controller_res = false;
1086 		err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_CLEAR_RL, NULL, NULL);
1087 		if (err) {
1088 			LOG_ERR("Failed to clear resolution list");
1089 			goto done;
1090 		}
1091 
1092 		bt_dev.le.rl_entries++;
1093 		keys->state |= BT_KEYS_ID_ADDED;
1094 
1095 		goto done;
1096 	}
1097 
1098 	err = hci_id_add(keys->id, &keys->addr, keys->irk.val);
1099 	if (err) {
1100 		LOG_ERR("Failed to add IRK to controller");
1101 		goto done;
1102 	}
1103 
1104 	bt_dev.le.rl_entries++;
1105 	keys->state |= BT_KEYS_ID_ADDED;
1106 
1107 	/*
1108 	 * According to Core Spec. 5.0 Vol 1, Part A 5.4.5 Privacy Feature
1109 	 *
1110 	 * By default, network privacy mode is used when private addresses are
1111 	 * resolved and generated by the Controller, so advertising packets from
1112 	 * peer devices that contain private addresses will only be accepted.
1113 	 * By changing to the device privacy mode device is only concerned about
1114 	 * its privacy and will accept advertising packets from peer devices
1115 	 * that contain their identity address as well as ones that contain
1116 	 * a private address, even if the peer device has distributed its IRK in
1117 	 * the past.
1118 	 */
1119 	err = le_set_privacy_mode(&keys->addr, BT_HCI_LE_PRIVACY_MODE_DEVICE);
1120 	if (err) {
1121 		LOG_ERR("Failed to set privacy mode");
1122 		goto done;
1123 	}
1124 
1125 done:
1126 	if (enable_controller_res) {
1127 		addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
1128 	}
1129 
1130 #if defined(CONFIG_BT_OBSERVER)
1131 	if (scan_enabled) {
1132 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1133 	}
1134 #endif /* CONFIG_BT_OBSERVER */
1135 
1136 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1137 		bt_le_ext_adv_foreach(adv_unpause_enabled, NULL);
1138 	}
1139 }
1140 
keys_add_id(struct bt_keys * keys,void * data)1141 static void keys_add_id(struct bt_keys *keys, void *data)
1142 {
1143 	if (keys->state & BT_KEYS_ID_ADDED) {
1144 		hci_id_add(keys->id, &keys->addr, keys->irk.val);
1145 	}
1146 }
1147 
hci_id_del(const bt_addr_le_t * addr)1148 static int hci_id_del(const bt_addr_le_t *addr)
1149 {
1150 	struct bt_hci_cp_le_rem_dev_from_rl *cp;
1151 	struct net_buf *buf;
1152 
1153 	LOG_DBG("addr %s", bt_addr_le_str(addr));
1154 
1155 	buf = bt_hci_cmd_alloc(K_FOREVER);
1156 	if (!buf) {
1157 		return -ENOBUFS;
1158 	}
1159 
1160 	cp = net_buf_add(buf, sizeof(*cp));
1161 	bt_addr_le_copy(&cp->peer_id_addr, addr);
1162 
1163 	return bt_hci_cmd_send_sync(BT_HCI_OP_LE_REM_DEV_FROM_RL, buf, NULL);
1164 }
1165 
bt_id_del(struct bt_keys * keys)1166 void bt_id_del(struct bt_keys *keys)
1167 {
1168 	struct bt_conn *conn;
1169 	int err;
1170 
1171 	CHECKIF(keys == NULL) {
1172 		return;
1173 	}
1174 
1175 	LOG_DBG("addr %s", bt_addr_le_str(&keys->addr));
1176 
1177 	if (!bt_dev.le.rl_size ||
1178 	    bt_dev.le.rl_entries > bt_dev.le.rl_size + 1) {
1179 		__ASSERT_NO_MSG(bt_dev.le.rl_entries > 0);
1180 		if (bt_dev.le.rl_entries > 0) {
1181 			bt_dev.le.rl_entries--;
1182 		}
1183 		keys->state &= ~BT_KEYS_ID_ADDED;
1184 		return;
1185 	}
1186 
1187 	conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL, BT_CONN_INITIATING);
1188 	if (conn) {
1189 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1190 		bt_conn_unref(conn);
1191 		return;
1192 	}
1193 
1194 	if (IS_ENABLED(CONFIG_BT_BROADCASTER) &&
1195 	    IS_ENABLED(CONFIG_BT_EXT_ADV)) {
1196 		bool adv_enabled = false;
1197 
1198 		bt_le_ext_adv_foreach(adv_is_limited_enabled, &adv_enabled);
1199 		if (adv_enabled) {
1200 			bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1201 			return;
1202 		}
1203 	}
1204 
1205 #if defined(CONFIG_BT_OBSERVER)
1206 	bool scan_enabled = atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING);
1207 
1208 	if (IS_ENABLED(CONFIG_BT_EXT_ADV) && scan_enabled &&
1209 	    atomic_test_bit(bt_dev.flags, BT_DEV_SCAN_LIMITED)) {
1210 		bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_DEL);
1211 	}
1212 #endif /* CONFIG_BT_OBSERVER */
1213 
1214 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1215 		bt_le_ext_adv_foreach(adv_pause_enabled, NULL);
1216 	}
1217 
1218 #if defined(CONFIG_BT_OBSERVER)
1219 	if (scan_enabled) {
1220 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
1221 	}
1222 #endif /* CONFIG_BT_OBSERVER */
1223 
1224 	err = addr_res_enable(BT_HCI_ADDR_RES_DISABLE);
1225 	if (err) {
1226 		LOG_ERR("Disabling address resolution failed (err %d)", err);
1227 		goto done;
1228 	}
1229 
1230 	/* We checked size + 1 earlier, so here we know we can fit again */
1231 	if (bt_dev.le.rl_entries > bt_dev.le.rl_size) {
1232 		bt_dev.le.rl_entries--;
1233 		keys->state &= ~BT_KEYS_ID_ADDED;
1234 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
1235 		    IS_ENABLED(CONFIG_BT_PRIVACY)) {
1236 			bt_keys_foreach_type(BT_KEYS_ALL, keys_add_id, NULL);
1237 		} else {
1238 			bt_keys_foreach_type(BT_KEYS_IRK, keys_add_id, NULL);
1239 		}
1240 		goto done;
1241 	}
1242 
1243 	err = hci_id_del(&keys->addr);
1244 	if (err) {
1245 		LOG_ERR("Failed to remove IRK from controller");
1246 		goto done;
1247 	}
1248 
1249 	bt_dev.le.rl_entries--;
1250 	keys->state &= ~BT_KEYS_ID_ADDED;
1251 
1252 done:
1253 	/* Only re-enable if there are entries to do resolving with */
1254 	if (bt_dev.le.rl_entries) {
1255 		addr_res_enable(BT_HCI_ADDR_RES_ENABLE);
1256 	}
1257 
1258 #if defined(CONFIG_BT_OBSERVER)
1259 	if (scan_enabled) {
1260 		bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
1261 	}
1262 #endif /* CONFIG_BT_OBSERVER */
1263 
1264 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1265 		bt_le_ext_adv_foreach(adv_unpause_enabled, NULL);
1266 	}
1267 }
1268 #endif /* defined(CONFIG_BT_SMP) */
1269 
bt_id_get(bt_addr_le_t * addrs,size_t * count)1270 void bt_id_get(bt_addr_le_t *addrs, size_t *count)
1271 {
1272 	if (addrs) {
1273 		size_t to_copy = MIN(*count, bt_dev.id_count);
1274 
1275 		memcpy(addrs, bt_dev.id_addr, to_copy * sizeof(bt_addr_le_t));
1276 		*count = to_copy;
1277 	} else {
1278 		*count = bt_dev.id_count;
1279 	}
1280 }
1281 
id_find(const bt_addr_le_t * addr)1282 static int id_find(const bt_addr_le_t *addr)
1283 {
1284 	uint8_t id;
1285 
1286 	for (id = 0U; id < bt_dev.id_count; id++) {
1287 		if (bt_addr_le_eq(addr, &bt_dev.id_addr[id])) {
1288 			return id;
1289 		}
1290 	}
1291 
1292 	return -ENOENT;
1293 }
1294 
id_create(uint8_t id,bt_addr_le_t * addr,uint8_t * irk)1295 static int id_create(uint8_t id, bt_addr_le_t *addr, uint8_t *irk)
1296 {
1297 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1298 		bt_addr_le_copy(&bt_dev.id_addr[id], addr);
1299 	} else {
1300 		bt_addr_le_t new_addr;
1301 
1302 		do {
1303 			int err;
1304 
1305 			err = bt_addr_le_create_static(&new_addr);
1306 			if (err) {
1307 				return err;
1308 			}
1309 			/* Make sure we didn't generate a duplicate */
1310 		} while (id_find(&new_addr) >= 0);
1311 
1312 		bt_addr_le_copy(&bt_dev.id_addr[id], &new_addr);
1313 
1314 		if (addr) {
1315 			bt_addr_le_copy(addr, &bt_dev.id_addr[id]);
1316 		}
1317 	}
1318 
1319 #if defined(CONFIG_BT_PRIVACY)
1320 	{
1321 		uint8_t zero_irk[16] = { 0 };
1322 
1323 		if (irk && memcmp(irk, zero_irk, 16)) {
1324 			memcpy(&bt_dev.irk[id], irk, 16);
1325 		} else {
1326 			int err;
1327 
1328 			err = bt_rand(&bt_dev.irk[id], 16);
1329 			if (err) {
1330 				return err;
1331 			}
1332 
1333 			if (irk) {
1334 				memcpy(irk, &bt_dev.irk[id], 16);
1335 			}
1336 		}
1337 
1338 #if defined(CONFIG_BT_RPA_SHARING)
1339 		bt_addr_copy(&bt_dev.rpa[id], BT_ADDR_NONE);
1340 #endif
1341 	}
1342 #endif
1343 	/* Only store if stack was already initialized. Before initialization
1344 	 * we don't know the flash content, so it's potentially harmful to
1345 	 * try to write anything there.
1346 	 */
1347 	if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
1348 	    atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1349 		(void)bt_settings_store_id();
1350 		(void)bt_settings_store_irk();
1351 	}
1352 
1353 	return 0;
1354 }
1355 
bt_id_create(bt_addr_le_t * addr,uint8_t * irk)1356 int bt_id_create(bt_addr_le_t *addr, uint8_t *irk)
1357 {
1358 	int new_id, err;
1359 
1360 	if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
1361 		return -EINVAL;
1362 	}
1363 
1364 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1365 		if (id_find(addr) >= 0) {
1366 			return -EALREADY;
1367 		}
1368 
1369 		if (addr->type == BT_ADDR_LE_PUBLIC && IS_ENABLED(CONFIG_BT_HCI_SET_PUBLIC_ADDR)) {
1370 			/* set the single public address */
1371 			if (bt_dev.id_count != 0) {
1372 				return -EALREADY;
1373 			}
1374 			bt_addr_le_copy(&bt_dev.id_addr[BT_ID_DEFAULT], addr);
1375 			bt_dev.id_count++;
1376 			return BT_ID_DEFAULT;
1377 		} else if (addr->type != BT_ADDR_LE_RANDOM || !BT_ADDR_IS_STATIC(&addr->a)) {
1378 			LOG_ERR("Only random static identity address supported");
1379 			return -EINVAL;
1380 		}
1381 	}
1382 
1383 	if (bt_dev.id_count == ARRAY_SIZE(bt_dev.id_addr)) {
1384 		return -ENOMEM;
1385 	}
1386 
1387 	/* bt_rand is not available before Bluetooth enable has been called */
1388 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_ENABLE)) {
1389 		uint8_t zero_irk[16] = { 0 };
1390 
1391 		if (!(addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY))) {
1392 			return -EINVAL;
1393 		}
1394 
1395 		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1396 		    !(irk && memcmp(irk, zero_irk, 16))) {
1397 			return -EINVAL;
1398 		}
1399 	}
1400 
1401 	new_id = bt_dev.id_count++;
1402 	err = id_create(new_id, addr, irk);
1403 	if (err) {
1404 		bt_dev.id_count--;
1405 		return err;
1406 	}
1407 
1408 	return new_id;
1409 }
1410 
bt_id_reset(uint8_t id,bt_addr_le_t * addr,uint8_t * irk)1411 int bt_id_reset(uint8_t id, bt_addr_le_t *addr, uint8_t *irk)
1412 {
1413 	int err;
1414 
1415 	if (addr && !bt_addr_le_eq(addr, BT_ADDR_LE_ANY)) {
1416 		if (addr->type != BT_ADDR_LE_RANDOM ||
1417 		    !BT_ADDR_IS_STATIC(&addr->a)) {
1418 			LOG_ERR("Only static random identity address supported");
1419 			return -EINVAL;
1420 		}
1421 
1422 		if (id_find(addr) >= 0) {
1423 			return -EALREADY;
1424 		}
1425 	}
1426 
1427 	if (!IS_ENABLED(CONFIG_BT_PRIVACY) && irk) {
1428 		return -EINVAL;
1429 	}
1430 
1431 	if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
1432 		return -EINVAL;
1433 	}
1434 
1435 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1436 		struct bt_adv_id_check_data check_data = {
1437 			.id = id,
1438 			.adv_enabled = false,
1439 		};
1440 
1441 		bt_le_ext_adv_foreach(adv_id_check_func, &check_data);
1442 		if (check_data.adv_enabled) {
1443 			return -EBUSY;
1444 		}
1445 	}
1446 
1447 	if (IS_ENABLED(CONFIG_BT_SMP) &&
1448 	    !bt_addr_le_eq(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
1449 		err = bt_unpair(id, NULL);
1450 		if (err) {
1451 			return err;
1452 		}
1453 	}
1454 
1455 	err = id_create(id, addr, irk);
1456 	if (err) {
1457 		return err;
1458 	}
1459 
1460 	return id;
1461 }
1462 
bt_id_delete(uint8_t id)1463 int bt_id_delete(uint8_t id)
1464 {
1465 	if (id == BT_ID_DEFAULT || id >= bt_dev.id_count) {
1466 		return -EINVAL;
1467 	}
1468 
1469 	if (bt_addr_le_eq(&bt_dev.id_addr[id], BT_ADDR_LE_ANY)) {
1470 		return -EALREADY;
1471 	}
1472 
1473 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
1474 		struct bt_adv_id_check_data check_data = {
1475 			.id = id,
1476 			.adv_enabled = false,
1477 		};
1478 
1479 		bt_le_ext_adv_foreach(adv_id_check_func, &check_data);
1480 		if (check_data.adv_enabled) {
1481 			return -EBUSY;
1482 		}
1483 	}
1484 
1485 	if (IS_ENABLED(CONFIG_BT_SMP)) {
1486 		int err;
1487 
1488 		err = bt_unpair(id, NULL);
1489 		if (err) {
1490 			return err;
1491 		}
1492 	}
1493 
1494 #if defined(CONFIG_BT_PRIVACY)
1495 	(void)memset(bt_dev.irk[id], 0, 16);
1496 #endif
1497 	bt_addr_le_copy(&bt_dev.id_addr[id], BT_ADDR_LE_ANY);
1498 
1499 	if (id == bt_dev.id_count - 1) {
1500 		bt_dev.id_count--;
1501 	}
1502 
1503 	if (IS_ENABLED(CONFIG_BT_SETTINGS) &&
1504 	    atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
1505 		(void)bt_settings_store_id();
1506 		(void)bt_settings_store_irk();
1507 	}
1508 
1509 	return 0;
1510 }
1511 
1512 #if defined(CONFIG_BT_PRIVACY)
bt_read_identity_root(uint8_t * ir)1513 static void bt_read_identity_root(uint8_t *ir)
1514 {
1515 	/* Invalid IR */
1516 	memset(ir, 0, 16);
1517 
1518 #if defined(CONFIG_BT_HCI_VS)
1519 	struct bt_hci_rp_vs_read_key_hierarchy_roots *rp;
1520 	struct net_buf *rsp;
1521 	int err;
1522 
1523 	if (!BT_VS_CMD_READ_KEY_ROOTS(bt_dev.vs_commands)) {
1524 		return;
1525 	}
1526 
1527 	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS, NULL,
1528 				   &rsp);
1529 	if (err) {
1530 		LOG_WRN("Failed to read identity root");
1531 		return;
1532 	}
1533 
1534 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1535 	    rsp->len != sizeof(struct bt_hci_rp_vs_read_key_hierarchy_roots)) {
1536 		LOG_WRN("Invalid Vendor HCI extensions");
1537 		net_buf_unref(rsp);
1538 		return;
1539 	}
1540 
1541 	rp = (void *)rsp->data;
1542 	memcpy(ir, rp->ir, 16);
1543 
1544 	net_buf_unref(rsp);
1545 #endif /* defined(CONFIG_BT_HCI_VS) */
1546 }
1547 #endif /* defined(CONFIG_BT_PRIVACY) */
1548 
bt_id_read_public_addr(bt_addr_le_t * addr)1549 uint8_t bt_id_read_public_addr(bt_addr_le_t *addr)
1550 {
1551 	struct bt_hci_rp_read_bd_addr *rp;
1552 	struct net_buf *rsp;
1553 	int err;
1554 
1555 	CHECKIF(addr == NULL) {
1556 		LOG_WRN("Invalid input parameters");
1557 		return 0U;
1558 	}
1559 
1560 	/* Read Bluetooth Address */
1561 	err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_BD_ADDR, NULL, &rsp);
1562 	if (err) {
1563 		LOG_WRN("Failed to read public address");
1564 		return 0U;
1565 	}
1566 
1567 	rp = (void *)rsp->data;
1568 
1569 	if (bt_addr_eq(&rp->bdaddr, BT_ADDR_ANY) ||
1570 	    bt_addr_eq(&rp->bdaddr, BT_ADDR_NONE)) {
1571 		LOG_DBG("Controller has no public address");
1572 		net_buf_unref(rsp);
1573 		return 0U;
1574 	}
1575 
1576 	bt_addr_copy(&addr->a, &rp->bdaddr);
1577 	addr->type = BT_ADDR_LE_PUBLIC;
1578 
1579 	net_buf_unref(rsp);
1580 	return 1U;
1581 }
1582 
bt_setup_public_id_addr(void)1583 int bt_setup_public_id_addr(void)
1584 {
1585 	bt_addr_le_t addr;
1586 	uint8_t *irk = NULL;
1587 
1588 	bt_dev.id_count = bt_id_read_public_addr(&addr);
1589 
1590 	if (!bt_dev.id_count) {
1591 		return 0;
1592 	}
1593 
1594 #if defined(CONFIG_BT_PRIVACY)
1595 	uint8_t ir_irk[16];
1596 	uint8_t ir[16];
1597 
1598 	bt_read_identity_root(ir);
1599 
1600 	if (!IS_ENABLED(CONFIG_BT_PRIVACY_RANDOMIZE_IR)) {
1601 		if (!bt_smp_irk_get(ir, ir_irk)) {
1602 			irk = ir_irk;
1603 		}
1604 	}
1605 #endif /* defined(CONFIG_BT_PRIVACY) */
1606 
1607 	/* If true, `id_create` will randomize the IRK. */
1608 	if (!irk && IS_ENABLED(CONFIG_BT_PRIVACY)) {
1609 		/* `id_create` will not store the id when called before BT_DEV_READY.
1610 		 * But since part of the id will be randomized, it needs to be stored.
1611 		 */
1612 		if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1613 			atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1614 		}
1615 	}
1616 
1617 	return id_create(BT_ID_DEFAULT, &addr, irk);
1618 }
1619 
vs_read_static_addr(struct bt_hci_vs_static_addr addrs[],uint8_t size)1620 static uint8_t vs_read_static_addr(struct bt_hci_vs_static_addr addrs[], uint8_t size)
1621 {
1622 #if defined(CONFIG_BT_HCI_VS)
1623 	struct bt_hci_rp_vs_read_static_addrs *rp;
1624 	struct net_buf *rsp;
1625 	int err, i;
1626 	uint8_t cnt;
1627 
1628 	if (!BT_VS_CMD_READ_STATIC_ADDRS(bt_dev.vs_commands)) {
1629 		LOG_WRN("Read Static Addresses command not available");
1630 		return 0;
1631 	}
1632 
1633 	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_STATIC_ADDRS, NULL, &rsp);
1634 	if (err) {
1635 		LOG_WRN("Failed to read static addresses");
1636 		return 0;
1637 	}
1638 
1639 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1640 	    rsp->len < sizeof(struct bt_hci_rp_vs_read_static_addrs)) {
1641 		LOG_WRN("Invalid Vendor HCI extensions");
1642 		net_buf_unref(rsp);
1643 		return 0;
1644 	}
1645 
1646 	rp = (void *)rsp->data;
1647 	cnt = MIN(rp->num_addrs, size);
1648 
1649 	if (IS_ENABLED(CONFIG_BT_HCI_VS_EXT_DETECT) &&
1650 	    rsp->len != (sizeof(struct bt_hci_rp_vs_read_static_addrs) +
1651 			 rp->num_addrs *
1652 			 sizeof(struct bt_hci_vs_static_addr))) {
1653 		LOG_WRN("Invalid Vendor HCI extensions");
1654 		net_buf_unref(rsp);
1655 		return 0;
1656 	}
1657 
1658 	for (i = 0; i < cnt; i++) {
1659 		memcpy(&addrs[i], &rp->a[i], sizeof(struct bt_hci_vs_static_addr));
1660 	}
1661 
1662 	net_buf_unref(rsp);
1663 	if (!cnt) {
1664 		LOG_WRN("No static addresses stored in controller");
1665 	}
1666 
1667 	return cnt;
1668 #else
1669 	return 0;
1670 #endif
1671 }
1672 
bt_setup_random_id_addr(void)1673 int bt_setup_random_id_addr(void)
1674 {
1675 	/* Only read the addresses if the user has not already configured one or
1676 	 * more identities (!bt_dev.id_count).
1677 	 */
1678 	if (IS_ENABLED(CONFIG_BT_HCI_VS) && !bt_dev.id_count) {
1679 		struct bt_hci_vs_static_addr addrs[CONFIG_BT_ID_MAX];
1680 
1681 		bt_dev.id_count = vs_read_static_addr(addrs, CONFIG_BT_ID_MAX);
1682 
1683 		for (uint8_t i = 0; i < bt_dev.id_count; i++) {
1684 			int err;
1685 			bt_addr_le_t addr;
1686 			uint8_t *irk = NULL;
1687 			uint8_t ir_irk[16];
1688 
1689 			if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1690 			    !IS_ENABLED(CONFIG_BT_PRIVACY_RANDOMIZE_IR)) {
1691 				if (!bt_smp_irk_get(addrs[i].ir, ir_irk)) {
1692 					irk = ir_irk;
1693 				}
1694 			}
1695 
1696 			/* If true, `id_create` will randomize the IRK. */
1697 			if (!irk && IS_ENABLED(CONFIG_BT_PRIVACY)) {
1698 				/* `id_create` will not store the id when called before
1699 				 * BT_DEV_READY. But since part of the id will be
1700 				 * randomized, it needs to be stored.
1701 				 */
1702 				if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
1703 					atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1704 				}
1705 			}
1706 
1707 			bt_addr_copy(&addr.a, &addrs[i].bdaddr);
1708 			addr.type = BT_ADDR_LE_RANDOM;
1709 
1710 			err = id_create(i, &addr, irk);
1711 			if (err) {
1712 				return err;
1713 			}
1714 		}
1715 
1716 		if (bt_dev.id_count > 0) {
1717 			return 0;
1718 		}
1719 	}
1720 
1721 	if (IS_ENABLED(CONFIG_BT_PRIVACY) && IS_ENABLED(CONFIG_BT_SETTINGS)) {
1722 		atomic_set_bit(bt_dev.flags, BT_DEV_STORE_ID);
1723 	}
1724 
1725 	return bt_id_create(NULL, NULL);
1726 }
1727 
1728 #if defined(CONFIG_BT_CENTRAL)
rpa_timeout_valid_check(void)1729 static inline bool rpa_timeout_valid_check(void)
1730 {
1731 #if defined(CONFIG_BT_PRIVACY)
1732 	uint32_t remaining_ms = k_ticks_to_ms_floor32(
1733 		k_work_delayable_remaining_get(&bt_dev.rpa_update));
1734 	/* Check if create conn timeout will happen before RPA timeout. */
1735 	return remaining_ms > (10 * bt_dev.create_param.timeout);
1736 #else
1737 	return true;
1738 #endif
1739 }
1740 
bt_id_set_create_conn_own_addr(bool use_filter,uint8_t * own_addr_type)1741 int bt_id_set_create_conn_own_addr(bool use_filter, uint8_t *own_addr_type)
1742 {
1743 	int err;
1744 
1745 	CHECKIF(own_addr_type == NULL) {
1746 		return -EINVAL;
1747 	}
1748 
1749 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
1750 		if (use_filter || rpa_timeout_valid_check()) {
1751 			err = bt_id_set_private_addr(BT_ID_DEFAULT);
1752 			if (err) {
1753 				return err;
1754 			}
1755 		} else {
1756 			/* Force new RPA timeout so that RPA timeout is not
1757 			 * triggered while direct initiator is active.
1758 			 */
1759 			le_force_rpa_timeout();
1760 		}
1761 
1762 		if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1763 			*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1764 		} else {
1765 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1766 		}
1767 	} else {
1768 		const bt_addr_le_t *addr = &bt_dev.id_addr[BT_ID_DEFAULT];
1769 
1770 		/* If Static Random address is used as Identity address we
1771 		 * need to restore it before creating connection. Otherwise
1772 		 * NRPA used for active scan could be used for connection.
1773 		 */
1774 		if (addr->type == BT_ADDR_LE_RANDOM) {
1775 			err = set_random_address(&addr->a);
1776 			if (err) {
1777 				return err;
1778 			}
1779 
1780 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1781 		} else {
1782 			/* If address type is not random, it's public. If it's public then we assume
1783 			 * it's the Controller's public address.
1784 			 */
1785 			*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1786 		}
1787 	}
1788 
1789 	return 0;
1790 }
1791 #endif /* defined(CONFIG_BT_CENTRAL) */
1792 
1793 #if defined(CONFIG_BT_OBSERVER)
is_legacy_adv_enabled(void)1794 static bool is_legacy_adv_enabled(void)
1795 {
1796 	struct bt_le_ext_adv *adv;
1797 
1798 	if (!IS_ENABLED(CONFIG_BT_BROADCASTER) ||
1799 	    (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1800 	     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
1801 		/* When advertising is not enabled or is using extended
1802 		 * advertising HCI commands then only the scanner uses the set
1803 		 * random address command.
1804 		 */
1805 		return false;
1806 	}
1807 
1808 	adv = bt_le_adv_lookup_legacy();
1809 
1810 	return adv != NULL && atomic_test_bit(adv->flags, BT_ADV_ENABLED);
1811 }
1812 
is_legacy_adv_using_id_addr(void)1813 static bool is_legacy_adv_using_id_addr(void)
1814 {
1815 	struct bt_le_ext_adv *adv;
1816 
1817 	if (!IS_ENABLED(CONFIG_BT_BROADCASTER) ||
1818 	    (IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1819 	     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
1820 		/* When advertising is not enabled or is using extended
1821 		 * advertising HCI commands then only the scanner uses the set
1822 		 * random address command.
1823 		 */
1824 		return false;
1825 	}
1826 
1827 	adv = bt_le_adv_lookup_legacy();
1828 
1829 	return adv != NULL && atomic_test_bit(adv->flags, BT_ADV_ENABLED)
1830 			   && atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY);
1831 }
1832 
bt_id_set_scan_own_addr(bool active_scan,uint8_t * own_addr_type)1833 int bt_id_set_scan_own_addr(bool active_scan, uint8_t *own_addr_type)
1834 {
1835 	int err;
1836 
1837 	CHECKIF(own_addr_type == NULL) {
1838 		return -EINVAL;
1839 	}
1840 
1841 	if (IS_ENABLED(CONFIG_BT_PRIVACY)) {
1842 
1843 		if (BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1844 			*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1845 		} else {
1846 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1847 		}
1848 
1849 		err = bt_id_set_private_addr(BT_ID_DEFAULT);
1850 		if (err == -EACCES && (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) ||
1851 				       atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING))) {
1852 			LOG_WRN("Set random addr failure ignored in scan/init state");
1853 
1854 			return 0;
1855 		} else if (err) {
1856 			return err;
1857 		}
1858 	} else {
1859 		/* Use NRPA unless identity has been explicitly requested
1860 		 * (through Kconfig).
1861 		 * Use same RPA as legacy advertiser if advertising.
1862 		 */
1863 		if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY)) {
1864 			/* When using legacy advertising commands, the scanner and advertiser
1865 			 * share the same address, so we cannot change it.
1866 			 * When using extended advertising commands, however, the advertising
1867 			 * sets have their own addresses, so we can always change the scanner
1868 			 * address here.
1869 			 */
1870 			if (is_legacy_adv_using_id_addr()) {
1871 				if (bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_RANDOM) {
1872 					*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1873 				} else {
1874 					*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1875 				}
1876 			} else if (is_legacy_adv_enabled()) {
1877 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1878 			} else {
1879 				err = bt_id_set_private_addr(BT_ID_DEFAULT);
1880 				if (err) {
1881 					return err;
1882 				}
1883 
1884 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1885 			}
1886 		} else {
1887 			if (bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_RANDOM) {
1888 				/* If scanning with Identity Address we must set the
1889 				 * random identity address for both active and passive
1890 				 * scanner in order to receive adv reports that are
1891 				 * directed towards this identity.
1892 				 */
1893 				err = set_random_address(&bt_dev.id_addr[BT_ID_DEFAULT].a);
1894 				if (err) {
1895 					return err;
1896 				}
1897 
1898 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1899 			} else if (bt_dev.id_addr[BT_ID_DEFAULT].type == BT_ADDR_LE_PUBLIC) {
1900 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1901 			}
1902 		}
1903 	}
1904 
1905 	return 0;
1906 }
1907 #endif /* defined(CONFIG_BT_OBSERVER) */
1908 
bt_id_set_adv_own_addr(struct bt_le_ext_adv * adv,uint32_t options,bool dir_adv,uint8_t * own_addr_type)1909 int bt_id_set_adv_own_addr(struct bt_le_ext_adv *adv, uint32_t options,
1910 			   bool dir_adv, uint8_t *own_addr_type)
1911 {
1912 	const bt_addr_le_t *id_addr;
1913 	int err = 0;
1914 
1915 	CHECKIF(adv == NULL || own_addr_type == NULL) {
1916 		return -EINVAL;
1917 	}
1918 
1919 	/* Set which local identity address we're advertising with */
1920 	id_addr = &bt_dev.id_addr[adv->id];
1921 
1922 	/* Short-circuit to force NRPA usage */
1923 	if (options & BT_LE_ADV_OPT_USE_NRPA) {
1924 		if (options & BT_LE_ADV_OPT_USE_IDENTITY) {
1925 			LOG_ERR("Can't set both IDENTITY & NRPA");
1926 
1927 			return -EINVAL;
1928 		}
1929 
1930 		err = bt_id_set_adv_private_addr(adv);
1931 		if (err) {
1932 			return err;
1933 		}
1934 		*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1935 
1936 		return 0;
1937 	}
1938 
1939 	if (options & _BT_LE_ADV_OPT_CONNECTABLE) {
1940 		if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA) &&
1941 		    !BT_FEAT_LE_PRIVACY(bt_dev.le.features)) {
1942 			return -ENOTSUP;
1943 		}
1944 
1945 		if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
1946 		    !(options & BT_LE_ADV_OPT_USE_IDENTITY)) {
1947 			err = bt_id_set_adv_private_addr(adv);
1948 			if (err) {
1949 				return err;
1950 			}
1951 
1952 			if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
1953 				*own_addr_type = BT_HCI_OWN_ADDR_RPA_OR_RANDOM;
1954 			} else {
1955 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1956 			}
1957 		} else {
1958 			/*
1959 			 * If Static Random address is used as Identity
1960 			 * address we need to restore it before advertising
1961 			 * is enabled. Otherwise NRPA used for active scan
1962 			 * could be used for advertising.
1963 			 */
1964 			if (id_addr->type == BT_ADDR_LE_RANDOM) {
1965 				err = bt_id_set_adv_random_addr(adv, &id_addr->a);
1966 				if (err) {
1967 					return err;
1968 				}
1969 
1970 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1971 			} else if (id_addr->type == BT_ADDR_LE_PUBLIC) {
1972 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1973 			}
1974 
1975 			if (dir_adv && (options & BT_LE_ADV_OPT_DIR_ADDR_RPA)) {
1976 				*own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
1977 			}
1978 		}
1979 	} else {
1980 		if (options & BT_LE_ADV_OPT_USE_IDENTITY) {
1981 			if (id_addr->type == BT_ADDR_LE_RANDOM) {
1982 				err = bt_id_set_adv_random_addr(adv, &id_addr->a);
1983 				if (err) {
1984 					return err;
1985 				}
1986 
1987 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
1988 			} else if (id_addr->type == BT_ADDR_LE_PUBLIC) {
1989 				*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
1990 			}
1991 
1992 			if (options & BT_LE_ADV_OPT_DIR_ADDR_RPA) {
1993 				*own_addr_type |= BT_HCI_OWN_ADDR_RPA_MASK;
1994 			}
1995 		} else if (!(IS_ENABLED(CONFIG_BT_EXT_ADV) &&
1996 			     BT_DEV_FEAT_LE_EXT_ADV(bt_dev.le.features))) {
1997 			/* In case advertising set random address is not
1998 			 * available we must handle the shared random address
1999 			 * problem.
2000 			 */
2001 #if defined(CONFIG_BT_OBSERVER)
2002 			bool scan_disabled = false;
2003 			bool dev_scanning = atomic_test_bit(bt_dev.flags,
2004 							    BT_DEV_SCANNING);
2005 
2006 			/* If active scan with NRPA is ongoing refresh NRPA */
2007 			if (!IS_ENABLED(CONFIG_BT_PRIVACY) &&
2008 			    !IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) &&
2009 			    dev_scanning) {
2010 				err = bt_le_scan_set_enable(BT_HCI_LE_SCAN_DISABLE);
2011 				scan_disabled = err == 0;
2012 			}
2013 
2014 			/* If we are scanning with the identity address, it does
2015 			 * not make sense to set an NRPA.
2016 			 */
2017 			if (!IS_ENABLED(CONFIG_BT_SCAN_WITH_IDENTITY) ||
2018 			    !dev_scanning) {
2019 				err = bt_id_set_adv_private_addr(adv);
2020 				*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
2021 			} else {
2022 				if (id_addr->type == BT_ADDR_LE_RANDOM) {
2023 					*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
2024 				} else if (id_addr->type == BT_ADDR_LE_PUBLIC) {
2025 					*own_addr_type = BT_HCI_OWN_ADDR_PUBLIC;
2026 				}
2027 			}
2028 
2029 			if (scan_disabled) {
2030 				bt_le_scan_set_enable(BT_HCI_LE_SCAN_ENABLE);
2031 			}
2032 #else
2033 			err = bt_id_set_adv_private_addr(adv);
2034 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
2035 #endif /* defined(CONFIG_BT_OBSERVER) */
2036 		} else {
2037 			err = bt_id_set_adv_private_addr(adv);
2038 			*own_addr_type = BT_HCI_OWN_ADDR_RANDOM;
2039 		}
2040 
2041 		if (err) {
2042 			return err;
2043 		}
2044 	}
2045 
2046 	return 0;
2047 }
2048 
2049 #if defined(CONFIG_BT_CLASSIC)
bt_br_oob_get_local(struct bt_br_oob * oob)2050 int bt_br_oob_get_local(struct bt_br_oob *oob)
2051 {
2052 	CHECKIF(oob == NULL) {
2053 		return -EINVAL;
2054 	}
2055 
2056 	bt_addr_copy(&oob->addr, &bt_dev.id_addr[0].a);
2057 
2058 	return 0;
2059 }
2060 #endif /* CONFIG_BT_CLASSIC */
2061 
bt_le_oob_get_local(uint8_t id,struct bt_le_oob * oob)2062 int bt_le_oob_get_local(uint8_t id, struct bt_le_oob *oob)
2063 {
2064 	struct bt_le_ext_adv *adv = NULL;
2065 	int err;
2066 
2067 	CHECKIF(oob == NULL) {
2068 		return -EINVAL;
2069 	}
2070 
2071 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2072 		return -EAGAIN;
2073 	}
2074 
2075 	if (id >= CONFIG_BT_ID_MAX) {
2076 		return -EINVAL;
2077 	}
2078 
2079 	if (IS_ENABLED(CONFIG_BT_BROADCASTER)) {
2080 		adv = bt_le_adv_lookup_legacy();
2081 	}
2082 
2083 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
2084 	    !(adv && adv->id == id &&
2085 	      atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
2086 	      atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
2087 	      bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) {
2088 		if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2089 		    atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
2090 			struct bt_conn *conn;
2091 
2092 			conn = bt_conn_lookup_state_le(BT_ID_DEFAULT, NULL,
2093 						       BT_CONN_SCAN_BEFORE_INITIATING);
2094 			if (conn) {
2095 				/* Cannot set new RPA while creating
2096 				 * connections.
2097 				 */
2098 				bt_conn_unref(conn);
2099 				return -EINVAL;
2100 			}
2101 		}
2102 
2103 		if (adv &&
2104 		    atomic_test_bit(adv->flags, BT_ADV_ENABLED) &&
2105 		    atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY) &&
2106 		    (bt_dev.id_addr[id].type == BT_ADDR_LE_RANDOM)) {
2107 			/* Cannot set a new RPA address while advertising with
2108 			 * random static identity address for a different
2109 			 * identity.
2110 			 */
2111 			return -EINVAL;
2112 		}
2113 
2114 		if (IS_ENABLED(CONFIG_BT_OBSERVER) &&
2115 		    CONFIG_BT_ID_MAX > 1 &&
2116 		    id != BT_ID_DEFAULT &&
2117 		    (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING) ||
2118 		     atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING))) {
2119 			/* Cannot switch identity of scanner or initiator */
2120 			return -EINVAL;
2121 		}
2122 
2123 		le_force_rpa_timeout();
2124 
2125 		bt_addr_le_copy(&oob->addr, &bt_dev.random_addr);
2126 	} else {
2127 		bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[id]);
2128 	}
2129 
2130 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2131 		err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
2132 		if (err && err != -ENOTSUP) {
2133 			return err;
2134 		}
2135 	}
2136 
2137 	return 0;
2138 }
2139 
2140 #if defined(CONFIG_BT_EXT_ADV)
bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv * adv,struct bt_le_oob * oob)2141 int bt_le_ext_adv_oob_get_local(struct bt_le_ext_adv *adv,
2142 				struct bt_le_oob *oob)
2143 {
2144 	int err;
2145 
2146 	CHECKIF(adv == NULL || oob == NULL) {
2147 		return -EINVAL;
2148 	}
2149 
2150 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2151 		return -EAGAIN;
2152 	}
2153 
2154 	if (IS_ENABLED(CONFIG_BT_PRIVACY) &&
2155 	    !atomic_test_bit(adv->flags, BT_ADV_USE_IDENTITY)) {
2156 		/* Don't refresh RPA addresses if the RPA is new.
2157 		 * This allows back to back calls to this function or
2158 		 * bt_le_oob_get_local to not invalidate the previously set
2159 		 * RPAs.
2160 		 */
2161 		if (!atomic_test_bit(adv->flags, BT_ADV_LIMITED) &&
2162 		    !bt_id_rpa_is_new()) {
2163 			if (IS_ENABLED(CONFIG_BT_CENTRAL) &&
2164 			    atomic_test_bit(bt_dev.flags, BT_DEV_INITIATING)) {
2165 				struct bt_conn *conn;
2166 
2167 				conn = bt_conn_lookup_state_le(
2168 					BT_ID_DEFAULT, NULL,
2169 					BT_CONN_SCAN_BEFORE_INITIATING);
2170 
2171 				if (conn) {
2172 					/* Cannot set new RPA while creating
2173 					 * connections.
2174 					 */
2175 					bt_conn_unref(conn);
2176 					return -EINVAL;
2177 				}
2178 			}
2179 
2180 			le_force_rpa_timeout();
2181 		}
2182 
2183 		bt_addr_le_copy(&oob->addr, &adv->random_addr);
2184 	} else {
2185 		bt_addr_le_copy(&oob->addr, &bt_dev.id_addr[adv->id]);
2186 	}
2187 
2188 	if (IS_ENABLED(CONFIG_BT_SMP)) {
2189 		err = bt_smp_le_oob_generate_sc_data(&oob->le_sc_data);
2190 		if (err && err != -ENOTSUP) {
2191 			return err;
2192 		}
2193 	}
2194 
2195 	return 0;
2196 }
2197 #endif /* defined(CONFIG_BT_EXT_ADV) */
2198 
2199 #if defined(CONFIG_BT_SMP)
2200 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
bt_le_oob_set_legacy_tk(struct bt_conn * conn,const uint8_t * tk)2201 int bt_le_oob_set_legacy_tk(struct bt_conn *conn, const uint8_t *tk)
2202 {
2203 	if (!bt_conn_is_type(conn, BT_CONN_TYPE_LE)) {
2204 		LOG_DBG("Invalid connection type: %u for %p", conn->type, conn);
2205 		return -EINVAL;
2206 	}
2207 
2208 	CHECKIF(tk == NULL) {
2209 		return -EINVAL;
2210 	}
2211 
2212 	return bt_smp_le_oob_set_tk(conn, tk);
2213 }
2214 #endif /* !defined(CONFIG_BT_SMP_SC_PAIR_ONLY) */
2215 
2216 #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)2217 int bt_le_oob_set_sc_data(struct bt_conn *conn,
2218 			  const struct bt_le_oob_sc_data *oobd_local,
2219 			  const struct bt_le_oob_sc_data *oobd_remote)
2220 {
2221 	if (!bt_conn_is_type(conn, BT_CONN_TYPE_LE)) {
2222 		LOG_DBG("Invalid connection type: %u for %p", conn->type, conn);
2223 		return -EINVAL;
2224 	}
2225 
2226 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2227 		return -EAGAIN;
2228 	}
2229 
2230 	return bt_smp_le_oob_set_sc_data(conn, oobd_local, oobd_remote);
2231 }
2232 
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)2233 int bt_le_oob_get_sc_data(struct bt_conn *conn,
2234 			  const struct bt_le_oob_sc_data **oobd_local,
2235 			  const struct bt_le_oob_sc_data **oobd_remote)
2236 {
2237 	if (!bt_conn_is_type(conn, BT_CONN_TYPE_LE)) {
2238 		LOG_ERR("Invalid connection: %p", conn);
2239 		LOG_ERR("Invalid connection type: %u for %p", conn->handle, conn);
2240 		return -EINVAL;
2241 	}
2242 
2243 	if (!atomic_test_bit(bt_dev.flags, BT_DEV_READY)) {
2244 		return -EAGAIN;
2245 	}
2246 
2247 	return bt_smp_le_oob_get_sc_data(conn, oobd_local, oobd_remote);
2248 }
2249 #endif /* !defined(CONFIG_BT_SMP_OOB_LEGACY_PAIR_ONLY) */
2250 #endif /* defined(CONFIG_BT_SMP) */
2251 
bt_id_init(void)2252 int bt_id_init(void)
2253 {
2254 	int err;
2255 
2256 #if defined(CONFIG_BT_PRIVACY)
2257 	k_work_init_delayable(&bt_dev.rpa_update, rpa_timeout);
2258 #if defined(CONFIG_BT_RPA_SHARING)
2259 	for (uint8_t id = 0U; id < ARRAY_SIZE(bt_dev.rpa); id++) {
2260 		bt_addr_copy(&bt_dev.rpa[id], BT_ADDR_NONE);
2261 	}
2262 #endif
2263 #endif
2264 
2265 	if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
2266 		LOG_DBG("No user identity. Trying to set public.");
2267 
2268 		err = bt_setup_public_id_addr();
2269 		if (err) {
2270 			LOG_ERR("Unable to set identity address");
2271 			return err;
2272 		}
2273 	}
2274 
2275 	if (!IS_ENABLED(CONFIG_BT_SETTINGS) && !bt_dev.id_count) {
2276 		LOG_DBG("No public address. Trying to set static random.");
2277 
2278 		err = bt_setup_random_id_addr();
2279 		if (err) {
2280 			LOG_ERR("Unable to set identity address");
2281 			return err;
2282 		}
2283 
2284 		/* The passive scanner just sends a dummy address type in the
2285 		 * command. If the first activity does this, and the dummy type
2286 		 * is a random address, it needs a valid value, even though it's
2287 		 * not actually used.
2288 		 */
2289 		err = set_random_address(&bt_dev.id_addr[0].a);
2290 		if (err) {
2291 			LOG_ERR("Unable to set random address");
2292 			return err;
2293 		}
2294 	}
2295 
2296 	return 0;
2297 }
2298