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