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