1 /* keys.c - Bluetooth key handling */
2 
3 /*
4  * Copyright (c) 2015-2016 Intel Corporation
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 #include <errno.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11 #include <stdint.h>
12 #include <string.h>
13 
14 #include <zephyr/bluetooth/addr.h>
15 #include <zephyr/bluetooth/bluetooth.h>
16 #include <zephyr/bluetooth/buf.h>
17 #include <zephyr/bluetooth/conn.h>
18 #include <zephyr/bluetooth/hci.h>
19 #include <zephyr/kernel.h>
20 #include <zephyr/logging/log.h>
21 #include <zephyr/settings/settings.h>
22 #include <zephyr/sys/__assert.h>
23 #include <zephyr/sys/atomic.h>
24 #include <zephyr/sys/util.h>
25 #include <zephyr/sys/byteorder.h>
26 #include <zephyr/sys/util_macro.h>
27 
28 #include "common/bt_str.h"
29 #include "common/rpa.h"
30 #include "conn_internal.h"
31 #include "gatt_internal.h"
32 #include "hci_core.h"
33 #include "id.h"
34 #include "keys.h"
35 #include "settings.h"
36 #include "smp.h"
37 #include "sys/types.h"
38 
39 #define LOG_LEVEL CONFIG_BT_KEYS_LOG_LEVEL
40 LOG_MODULE_REGISTER(bt_keys);
41 
42 static struct bt_keys key_pool[CONFIG_BT_MAX_PAIRED];
43 
44 #define BT_KEYS_STORAGE_LEN_COMPAT (BT_KEYS_STORAGE_LEN - sizeof(uint32_t))
45 
46 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
47 static uint32_t aging_counter_val;
48 static struct bt_keys *last_keys_updated;
49 
50 struct key_data {
51 	bool in_use;
52 	uint8_t id;
53 };
54 
find_key_in_use(struct bt_conn * conn,void * data)55 static void find_key_in_use(struct bt_conn *conn, void *data)
56 {
57 	struct key_data *kdata = data;
58 	struct bt_keys *key;
59 
60 	__ASSERT_NO_MSG(conn != NULL);
61 	__ASSERT_NO_MSG(data != NULL);
62 
63 	if (conn->state == BT_CONN_CONNECTED) {
64 		key = bt_keys_find_addr(conn->id, bt_conn_get_dst(conn));
65 		if (key == NULL) {
66 			return;
67 		}
68 
69 		/* Ensure that the reference returned matches the current pool item */
70 		if (key == &key_pool[kdata->id]) {
71 			kdata->in_use = true;
72 			LOG_DBG("Connected device %s is using key_pool[%d]",
73 				bt_addr_le_str(bt_conn_get_dst(conn)), kdata->id);
74 		}
75 	}
76 }
77 
key_is_in_use(uint8_t id)78 static bool key_is_in_use(uint8_t id)
79 {
80 	struct key_data kdata = { false, id };
81 
82 	bt_conn_foreach(BT_CONN_TYPE_LE, find_key_in_use, &kdata);
83 
84 	return kdata.in_use;
85 }
86 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
87 
bt_keys_reset(void)88 void bt_keys_reset(void)
89 {
90 	memset(key_pool, 0, sizeof(key_pool));
91 }
92 
bt_keys_get_addr(uint8_t id,const bt_addr_le_t * addr)93 struct bt_keys *bt_keys_get_addr(uint8_t id, const bt_addr_le_t *addr)
94 {
95 	struct bt_keys *keys;
96 	int i;
97 	size_t first_free_slot = ARRAY_SIZE(key_pool);
98 
99 	__ASSERT_NO_MSG(addr != NULL);
100 
101 	LOG_DBG("%s", bt_addr_le_str(addr));
102 
103 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
104 		keys = &key_pool[i];
105 
106 		if (keys->id == id && bt_addr_le_eq(&keys->addr, addr)) {
107 			return keys;
108 		}
109 		if (first_free_slot == ARRAY_SIZE(key_pool) &&
110 		    bt_addr_le_eq(&keys->addr, BT_ADDR_LE_ANY)) {
111 			first_free_slot = i;
112 		}
113 	}
114 
115 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
116 	if (first_free_slot == ARRAY_SIZE(key_pool)) {
117 		struct bt_keys *oldest = NULL;
118 		bt_addr_le_t oldest_addr;
119 
120 		for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
121 			struct bt_keys *current = &key_pool[i];
122 			bool key_in_use = key_is_in_use(i);
123 
124 			if (key_in_use) {
125 				continue;
126 			}
127 
128 			if ((oldest == NULL) || (current->aging_counter < oldest->aging_counter)) {
129 				oldest = current;
130 			}
131 		}
132 
133 		if (oldest == NULL) {
134 			LOG_DBG("unable to create keys for %s", bt_addr_le_str(addr));
135 			return NULL;
136 		}
137 
138 		/* Use a copy as bt_unpair will clear the oldest key. */
139 		bt_addr_le_copy(&oldest_addr, &oldest->addr);
140 		bt_unpair(oldest->id, &oldest_addr);
141 		if (bt_addr_le_eq(&oldest->addr, BT_ADDR_LE_ANY)) {
142 			first_free_slot = oldest - &key_pool[0];
143 		}
144 	}
145 
146 #endif  /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
147 	if (first_free_slot < ARRAY_SIZE(key_pool)) {
148 		keys = &key_pool[first_free_slot];
149 		keys->id = id;
150 		bt_addr_le_copy(&keys->addr, addr);
151 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
152 		keys->aging_counter = ++aging_counter_val;
153 		last_keys_updated = keys;
154 #endif  /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
155 		LOG_DBG("created %p for %s", keys, bt_addr_le_str(addr));
156 		return keys;
157 	}
158 
159 	LOG_DBG("unable to create keys for %s", bt_addr_le_str(addr));
160 
161 	return NULL;
162 }
163 
bt_foreach_bond(uint8_t id,void (* func)(const struct bt_bond_info * info,void * user_data),void * user_data)164 void bt_foreach_bond(uint8_t id, void (*func)(const struct bt_bond_info *info,
165 					   void *user_data),
166 		     void *user_data)
167 {
168 	int i;
169 
170 	__ASSERT_NO_MSG(func != NULL);
171 
172 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
173 		struct bt_keys *keys = &key_pool[i];
174 
175 		if (keys->keys && keys->id == id) {
176 			struct bt_bond_info info;
177 
178 			bt_addr_le_copy(&info.addr, &keys->addr);
179 			func(&info, user_data);
180 		}
181 	}
182 }
183 
bt_keys_foreach_type(enum bt_keys_type type,void (* func)(struct bt_keys * keys,void * data),void * data)184 void bt_keys_foreach_type(enum bt_keys_type type, void (*func)(struct bt_keys *keys, void *data),
185 			  void *data)
186 {
187 	int i;
188 
189 	__ASSERT_NO_MSG(func != NULL);
190 
191 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
192 		if ((key_pool[i].keys & type)) {
193 			func(&key_pool[i], data);
194 		}
195 	}
196 }
197 
bt_keys_find(enum bt_keys_type type,uint8_t id,const bt_addr_le_t * addr)198 struct bt_keys *bt_keys_find(enum bt_keys_type type, uint8_t id, const bt_addr_le_t *addr)
199 {
200 	int i;
201 
202 	__ASSERT_NO_MSG(addr != NULL);
203 
204 	LOG_DBG("type %d %s", type, bt_addr_le_str(addr));
205 
206 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
207 		if ((key_pool[i].keys & type) && key_pool[i].id == id &&
208 		    bt_addr_le_eq(&key_pool[i].addr, addr)) {
209 			return &key_pool[i];
210 		}
211 	}
212 
213 	return NULL;
214 }
215 
bt_keys_get_type(enum bt_keys_type type,uint8_t id,const bt_addr_le_t * addr)216 struct bt_keys *bt_keys_get_type(enum bt_keys_type type, uint8_t id, const bt_addr_le_t *addr)
217 {
218 	struct bt_keys *keys;
219 
220 	__ASSERT_NO_MSG(addr != NULL);
221 
222 	LOG_DBG("type %d %s", type, bt_addr_le_str(addr));
223 
224 	keys = bt_keys_find(type, id, addr);
225 	if (keys) {
226 		return keys;
227 	}
228 
229 	keys = bt_keys_get_addr(id, addr);
230 	if (!keys) {
231 		return NULL;
232 	}
233 
234 	bt_keys_add_type(keys, type);
235 
236 	return keys;
237 }
238 
bt_keys_find_irk(uint8_t id,const bt_addr_le_t * addr)239 struct bt_keys *bt_keys_find_irk(uint8_t id, const bt_addr_le_t *addr)
240 {
241 	int i;
242 
243 	__ASSERT_NO_MSG(addr != NULL);
244 
245 	LOG_DBG("%s", bt_addr_le_str(addr));
246 
247 	if (!bt_addr_le_is_rpa(addr)) {
248 		return NULL;
249 	}
250 
251 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
252 		if (!(key_pool[i].keys & BT_KEYS_IRK)) {
253 			continue;
254 		}
255 
256 		if (key_pool[i].id == id &&
257 		    bt_addr_eq(&addr->a, &key_pool[i].irk.rpa)) {
258 			LOG_DBG("cached RPA %s for %s", bt_addr_str(&key_pool[i].irk.rpa),
259 				bt_addr_le_str(&key_pool[i].addr));
260 			return &key_pool[i];
261 		}
262 	}
263 
264 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
265 		if (!(key_pool[i].keys & BT_KEYS_IRK)) {
266 			continue;
267 		}
268 
269 		if (key_pool[i].id != id) {
270 			continue;
271 		}
272 
273 		if (bt_rpa_irk_matches(key_pool[i].irk.val, &addr->a)) {
274 			LOG_DBG("RPA %s matches %s", bt_addr_str(&key_pool[i].irk.rpa),
275 				bt_addr_le_str(&key_pool[i].addr));
276 
277 			bt_addr_copy(&key_pool[i].irk.rpa, &addr->a);
278 
279 			return &key_pool[i];
280 		}
281 	}
282 
283 	LOG_DBG("No IRK for %s", bt_addr_le_str(addr));
284 
285 	return NULL;
286 }
287 
bt_keys_find_addr(uint8_t id,const bt_addr_le_t * addr)288 struct bt_keys *bt_keys_find_addr(uint8_t id, const bt_addr_le_t *addr)
289 {
290 	int i;
291 
292 	__ASSERT_NO_MSG(addr != NULL);
293 
294 	LOG_DBG("%s", bt_addr_le_str(addr));
295 
296 	for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
297 		if (key_pool[i].id == id &&
298 		    bt_addr_le_eq(&key_pool[i].addr, addr)) {
299 			return &key_pool[i];
300 		}
301 	}
302 
303 	return NULL;
304 }
305 
bt_keys_add_type(struct bt_keys * keys,enum bt_keys_type type)306 void bt_keys_add_type(struct bt_keys *keys, enum bt_keys_type type)
307 {
308 	__ASSERT_NO_MSG(keys != NULL);
309 
310 	keys->keys |= type;
311 }
312 
bt_keys_clear(struct bt_keys * keys)313 void bt_keys_clear(struct bt_keys *keys)
314 {
315 	__ASSERT_NO_MSG(keys != NULL);
316 
317 	LOG_DBG("%s (keys 0x%04x)", bt_addr_le_str(&keys->addr), keys->keys);
318 
319 	if (keys->state & BT_KEYS_ID_ADDED) {
320 		bt_id_del(keys);
321 	}
322 
323 	if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
324 		/* Delete stored keys from flash */
325 		bt_settings_delete_keys(keys->id, &keys->addr);
326 	}
327 
328 	(void)memset(keys, 0, sizeof(*keys));
329 }
330 
331 #if defined(CONFIG_BT_SETTINGS)
bt_keys_store(struct bt_keys * keys)332 int bt_keys_store(struct bt_keys *keys)
333 {
334 	int err;
335 
336 	__ASSERT_NO_MSG(keys != NULL);
337 
338 	err = bt_settings_store_keys(keys->id, &keys->addr, keys->storage_start,
339 				     BT_KEYS_STORAGE_LEN);
340 	if (err) {
341 		LOG_ERR("Failed to save keys (err %d)", err);
342 		return err;
343 	}
344 
345 	LOG_DBG("Stored keys for %s", bt_addr_le_str(&keys->addr));
346 
347 	return 0;
348 }
349 
keys_set(const char * name,size_t len_rd,settings_read_cb read_cb,void * cb_arg)350 static int keys_set(const char *name, size_t len_rd, settings_read_cb read_cb,
351 		    void *cb_arg)
352 {
353 	struct bt_keys *keys;
354 	bt_addr_le_t addr;
355 	uint8_t id;
356 	ssize_t len;
357 	int err;
358 	char val[BT_KEYS_STORAGE_LEN];
359 	const char *next;
360 
361 	if (!name) {
362 		LOG_ERR("Insufficient number of arguments");
363 		return -EINVAL;
364 	}
365 
366 	len = read_cb(cb_arg, val, sizeof(val));
367 	if (len < 0) {
368 		LOG_ERR("Failed to read value (err %zd)", len);
369 		return -EINVAL;
370 	}
371 
372 	LOG_DBG("name %s val %s", name, (len) ? bt_hex(val, sizeof(val)) : "(null)");
373 
374 	err = bt_settings_decode_key(name, &addr);
375 	if (err) {
376 		LOG_ERR("Unable to decode address %s", name);
377 		return -EINVAL;
378 	}
379 
380 	settings_name_next(name, &next);
381 
382 	if (!next) {
383 		id = BT_ID_DEFAULT;
384 	} else {
385 		unsigned long next_id = strtoul(next, NULL, 10);
386 
387 		if (next_id >= CONFIG_BT_ID_MAX) {
388 			LOG_ERR("Invalid local identity %lu", next_id);
389 			return -EINVAL;
390 		}
391 
392 		id = (uint8_t)next_id;
393 	}
394 
395 	if (!len) {
396 		keys = bt_keys_find(BT_KEYS_ALL, id, &addr);
397 		if (keys) {
398 			(void)memset(keys, 0, sizeof(*keys));
399 			LOG_DBG("Cleared keys for %s", bt_addr_le_str(&addr));
400 		} else {
401 			LOG_WRN("Unable to find deleted keys for %s", bt_addr_le_str(&addr));
402 		}
403 
404 		return 0;
405 	}
406 
407 	keys = bt_keys_get_addr(id, &addr);
408 	if (!keys) {
409 		LOG_ERR("Failed to allocate keys for %s", bt_addr_le_str(&addr));
410 		return -ENOMEM;
411 	}
412 	if (len != BT_KEYS_STORAGE_LEN) {
413 		if (IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST) &&
414 		    len == BT_KEYS_STORAGE_LEN_COMPAT) {
415 			/* Load shorter structure for compatibility with old
416 			 * records format with no counter.
417 			 */
418 			LOG_WRN("Keys for %s have no aging counter", bt_addr_le_str(&addr));
419 			memcpy(keys->storage_start, val, len);
420 		} else {
421 			LOG_ERR("Invalid key length %zd != %zu", len, BT_KEYS_STORAGE_LEN);
422 			bt_keys_clear(keys);
423 
424 			return -EINVAL;
425 		}
426 	} else {
427 		memcpy(keys->storage_start, val, len);
428 	}
429 
430 	LOG_DBG("Successfully restored keys for %s", bt_addr_le_str(&addr));
431 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
432 	if (aging_counter_val < keys->aging_counter) {
433 		aging_counter_val = keys->aging_counter;
434 	}
435 #endif  /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
436 	return 0;
437 }
438 
add_id_cb(struct k_work * work)439 static void add_id_cb(struct k_work *work)
440 {
441 	bt_id_pending_keys_update();
442 }
443 
444 static K_WORK_DEFINE(add_id_work, add_id_cb);
445 
id_add(struct bt_keys * keys,void * user_data)446 static void id_add(struct bt_keys *keys, void *user_data)
447 {
448 	__ASSERT_NO_MSG(keys != NULL);
449 
450 	bt_id_pending_keys_update_set(keys, BT_KEYS_ID_PENDING_ADD);
451 	k_work_submit(&add_id_work);
452 }
453 
keys_commit(void)454 static int keys_commit(void)
455 {
456 	/* We do this in commit() rather than add() since add() may get
457 	 * called multiple times for the same address, especially if
458 	 * the keys were already removed.
459 	 */
460 	if (IS_ENABLED(CONFIG_BT_CENTRAL) && IS_ENABLED(CONFIG_BT_PRIVACY)) {
461 		bt_keys_foreach_type(BT_KEYS_ALL, id_add, NULL);
462 	} else {
463 		bt_keys_foreach_type(BT_KEYS_IRK, id_add, NULL);
464 	}
465 
466 	return 0;
467 }
468 
469 BT_SETTINGS_DEFINE(keys, "keys", keys_set, keys_commit);
470 
471 #endif /* CONFIG_BT_SETTINGS */
472 
473 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
bt_keys_update_usage(uint8_t id,const bt_addr_le_t * addr)474 void bt_keys_update_usage(uint8_t id, const bt_addr_le_t *addr)
475 {
476 	__ASSERT_NO_MSG(addr != NULL);
477 
478 	struct bt_keys *keys = bt_keys_find_addr(id, addr);
479 
480 	if (!keys) {
481 		return;
482 	}
483 
484 	if (last_keys_updated == keys) {
485 		return;
486 	}
487 
488 	keys->aging_counter = ++aging_counter_val;
489 	last_keys_updated = keys;
490 
491 	LOG_DBG("Aging counter for %s is set to %u", bt_addr_le_str(addr), keys->aging_counter);
492 
493 	if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
494 		bt_keys_store(keys);
495 	}
496 }
497 
498 #endif  /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
499 
500 #if defined(CONFIG_BT_LOG_SNIFFER_INFO)
bt_keys_show_sniffer_info(struct bt_keys * keys,void * data)501 void bt_keys_show_sniffer_info(struct bt_keys *keys, void *data)
502 {
503 	uint8_t ltk[16];
504 
505 	__ASSERT_NO_MSG(keys != NULL);
506 
507 	if (keys->keys & BT_KEYS_LTK_P256) {
508 		sys_memcpy_swap(ltk, keys->ltk.val, keys->enc_size);
509 		LOG_INF("SC LTK: 0x%s", bt_hex(ltk, keys->enc_size));
510 	}
511 
512 #if !defined(CONFIG_BT_SMP_SC_PAIR_ONLY)
513 	if (keys->keys & BT_KEYS_PERIPH_LTK) {
514 		sys_memcpy_swap(ltk, keys->periph_ltk.val, keys->enc_size);
515 		LOG_INF("Legacy LTK: 0x%s (peripheral)", bt_hex(ltk, keys->enc_size));
516 	}
517 #endif /* !CONFIG_BT_SMP_SC_PAIR_ONLY */
518 
519 	if (keys->keys & BT_KEYS_LTK) {
520 		sys_memcpy_swap(ltk, keys->ltk.val, keys->enc_size);
521 		LOG_INF("Legacy LTK: 0x%s (central)", bt_hex(ltk, keys->enc_size));
522 	}
523 }
524 #endif /* defined(CONFIG_BT_LOG_SNIFFER_INFO) */
525 
526 #ifdef ZTEST_UNITTEST
bt_keys_get_key_pool(void)527 struct bt_keys *bt_keys_get_key_pool(void)
528 {
529 	return key_pool;
530 }
531 
532 #if defined(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
bt_keys_get_aging_counter_val(void)533 uint32_t bt_keys_get_aging_counter_val(void)
534 {
535 	return aging_counter_val;
536 }
537 
bt_keys_get_last_keys_updated(void)538 struct bt_keys *bt_keys_get_last_keys_updated(void)
539 {
540 	return last_keys_updated;
541 }
542 #endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
543 #endif /* ZTEST_UNITTEST */
544