keys.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // SPDX-License-Identifier: LGPL-2.1-or-later
  2. /*
  3. *
  4. * BlueZ - Bluetooth protocol stack for Linux
  5. *
  6. * Copyright (C) 2011-2014 Intel Corporation
  7. * Copyright (C) 2002-2010 Marcel Holtmann <marcel@holtmann.org>
  8. *
  9. *
  10. */
  11. #ifdef HAVE_CONFIG_H
  12. #include <config.h>
  13. #endif
  14. #include <string.h>
  15. #include "src/shared/util.h"
  16. #include "src/shared/queue.h"
  17. #include "src/shared/crypto.h"
  18. #include "keys.h"
  19. static const uint8_t empty_key[16] = { 0x00, };
  20. static const uint8_t empty_addr[6] = { 0x00, };
  21. static struct bt_crypto *crypto;
  22. struct irk_data {
  23. uint8_t key[16];
  24. uint8_t addr[6];
  25. uint8_t addr_type;
  26. };
  27. static struct queue *irk_list;
  28. void keys_setup(void)
  29. {
  30. crypto = bt_crypto_new();
  31. irk_list = queue_new();
  32. }
  33. void keys_cleanup(void)
  34. {
  35. bt_crypto_unref(crypto);
  36. queue_destroy(irk_list, free);
  37. }
  38. void keys_update_identity_key(const uint8_t key[16])
  39. {
  40. struct irk_data *irk;
  41. irk = queue_peek_tail(irk_list);
  42. if (irk && !memcmp(irk->key, empty_key, 16)) {
  43. memcpy(irk->key, key, 16);
  44. return;
  45. }
  46. irk = new0(struct irk_data, 1);
  47. if (irk) {
  48. memcpy(irk->key, key, 16);
  49. if (!queue_push_tail(irk_list, irk))
  50. free(irk);
  51. }
  52. }
  53. void keys_update_identity_addr(const uint8_t addr[6], uint8_t addr_type)
  54. {
  55. struct irk_data *irk;
  56. irk = queue_peek_tail(irk_list);
  57. if (irk && !memcmp(irk->addr, empty_addr, 6)) {
  58. memcpy(irk->addr, addr, 6);
  59. irk->addr_type = addr_type;
  60. return;
  61. }
  62. irk = new0(struct irk_data, 1);
  63. if (irk) {
  64. memcpy(irk->addr, addr, 6);
  65. irk->addr_type = addr_type;
  66. if (!queue_push_tail(irk_list, irk))
  67. free(irk);
  68. }
  69. }
  70. static bool match_resolve_irk(const void *data, const void *match_data)
  71. {
  72. const struct irk_data *irk = data;
  73. const uint8_t *addr = match_data;
  74. uint8_t local_hash[3];
  75. bt_crypto_ah(crypto, irk->key, addr + 3, local_hash);
  76. return !memcmp(addr, local_hash, 3);
  77. }
  78. bool keys_resolve_identity(const uint8_t addr[6], uint8_t ident[6],
  79. uint8_t *ident_type)
  80. {
  81. struct irk_data *irk;
  82. irk = queue_find(irk_list, match_resolve_irk, addr);
  83. if (irk) {
  84. memcpy(ident, irk->addr, 6);
  85. *ident_type = irk->addr_type;
  86. return true;
  87. }
  88. return false;
  89. }