1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains functions for the Bluetooth Device Manager
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "btm_dev"
26 
27 #include "stack/btm/btm_dev.h"
28 
29 #include <bluetooth/log.h>
30 #include <com_android_bluetooth_flags.h>
31 
32 #include <string>
33 
34 #include "btif/include/btif_storage.h"
35 #include "btm_int_types.h"
36 #include "btm_sec_api.h"
37 #include "btm_sec_cb.h"
38 #include "internal_include/bt_target.h"
39 #include "main/shim/acl_api.h"
40 #include "main/shim/dumpsys.h"
41 #include "osi/include/allocator.h"
42 #include "stack/btm/btm_sec.h"
43 #include "stack/include/acl_api.h"
44 #include "stack/include/bt_octets.h"
45 #include "stack/include/btm_ble_privacy.h"
46 #include "stack/include/btm_client_interface.h"
47 #include "stack/include/btm_log_history.h"
48 #include "stack/include/gatt_api.h"
49 #include "stack/include/l2cap_interface.h"
50 #include "types/raw_address.h"
51 
52 // TODO(b/369381361) Enfore -Wmissing-prototypes
53 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
54 
55 using namespace bluetooth;
56 
57 extern tBTM_CB btm_cb;
58 
59 namespace {
60 
61 constexpr char kBtmLogTag[] = "BOND";
62 
63 }
64 
wipe_secrets_and_remove(tBTM_SEC_DEV_REC * p_dev_rec)65 static void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec) {
66   p_dev_rec->sec_rec.link_key.fill(0);
67   memset(&p_dev_rec->sec_rec.ble_keys, 0, sizeof(tBTM_SEC_BLE_KEYS));
68   list_remove(btm_sec_cb.sec_dev_rec, p_dev_rec);
69 }
70 
71 /*******************************************************************************
72  *
73  * Function         BTM_SecAddDevice
74  *
75  * Description      Add/modify device.  This function will be normally called
76  *                  during host startup to restore all required information
77  *                  stored in the NVRAM.
78  *
79  * Parameters:      bd_addr          - BD address of the peer
80  *                  dev_class        - Device Class
81  *                  link_key         - Connection link key. NULL if unknown.
82  *
83  * Returns          void
84  *
85  ******************************************************************************/
BTM_SecAddDevice(const RawAddress & bd_addr,DEV_CLASS dev_class,LinkKey link_key,uint8_t key_type,uint8_t pin_length)86 void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, LinkKey link_key,
87                       uint8_t key_type, uint8_t pin_length) {
88   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
89 
90   if (!p_dev_rec) {
91     p_dev_rec = btm_sec_allocate_dev_rec();
92     log::info(
93             "Caching new record from config file device: {}, dev_class: {:02x}:{:02x}:{:02x}, "
94             "link_key_type: 0x{:x}",
95             bd_addr, dev_class[0], dev_class[1], dev_class[2], key_type);
96 
97     p_dev_rec->bd_addr = bd_addr;
98     p_dev_rec->hci_handle =
99             get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
100 
101     /* use default value for background connection params */
102     /* update conn params, use default value for background connection params */
103     memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS));
104 
105     if (com::android::bluetooth::flags::name_discovery_for_le_pairing() &&
106         btif_storage_get_stored_remote_name(bd_addr,
107                                             reinterpret_cast<char*>(&p_dev_rec->sec_bd_name))) {
108       p_dev_rec->sec_rec.sec_flags |= BTM_SEC_NAME_KNOWN;
109     }
110   } else {
111     log::info(
112             "Caching existing record from config file device: {},"
113             " dev_class: {:02x}:{:02x}:{:02x}, link_key_type: 0x{:x}",
114             bd_addr, dev_class[0], dev_class[1], dev_class[2], key_type);
115 
116     /* "Bump" timestamp for existing record */
117     p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
118 
119     /* TODO(eisenbach):
120      * Small refactor, but leaving original logic for now.
121      * On the surface, this does not make any sense at all. Why change the
122      * bond state for an existing device here? This logic should be verified
123      * as part of a larger refactor.
124      */
125     p_dev_rec->sec_rec.bond_type = BOND_TYPE_UNKNOWN;
126   }
127 
128   if (dev_class != kDevClassEmpty) {
129     p_dev_rec->dev_class = dev_class;
130   }
131 
132   if (!com::android::bluetooth::flags::name_discovery_for_le_pairing()) {
133     bd_name_clear(p_dev_rec->sec_bd_name);
134   }
135 
136   p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
137   p_dev_rec->sec_rec.link_key = link_key;
138   p_dev_rec->sec_rec.link_key_type = key_type;
139   p_dev_rec->sec_rec.pin_code_length = pin_length;
140 
141   p_dev_rec->sec_rec.bond_type = BOND_TYPE_PERSISTENT;
142 
143   if (pin_length >= 16 || key_type == BTM_LKEY_TYPE_AUTH_COMB ||
144       key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
145     // Set the flag if the link key was made by using either a 16 digit
146     // pin or MITM.
147     p_dev_rec->sec_rec.sec_flags |= BTM_SEC_16_DIGIT_PIN_AUTHED | BTM_SEC_LINK_KEY_AUTHED;
148   }
149 
150   p_dev_rec->sec_rec.rmt_io_caps = BTM_IO_CAP_OUT;
151   p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR;
152 }
153 
154 /** Free resources associated with the device associated with |bd_addr| address.
155  *
156  * *** WARNING ***
157  * tBTM_SEC_DEV_REC associated with bd_addr becomes invalid after this function
158  * is called, also any of it's fields. i.e. if you use p_dev_rec->bd_addr, it is
159  * no longer valid!
160  * *** WARNING ***
161  *
162  * Returns true if removed OK, false if not found or ACL link is active.
163  */
BTM_SecDeleteDevice(const RawAddress & bd_addr)164 bool BTM_SecDeleteDevice(const RawAddress& bd_addr) {
165   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
166   if (p_dev_rec == NULL) {
167     log::warn("Unable to delete link key for unknown device {}", bd_addr);
168     return true;
169   }
170 
171   /* Invalidate bonded status */
172   p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LINK_KEY_KNOWN;
173   p_dev_rec->sec_rec.sec_flags &= ~BTM_SEC_LE_LINK_KEY_KNOWN;
174 
175   if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE) ||
176       get_btm_client_interface().peer.BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_BR_EDR)) {
177     log::warn("FAILED: Cannot Delete when connection to {} is active", bd_addr);
178     return false;
179   }
180 
181   RawAddress bda = p_dev_rec->bd_addr;
182 
183   log::info("Remove device {} from filter accept list before delete record", bd_addr);
184   bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(bda));
185 
186   const auto device_type = p_dev_rec->device_type;
187   const auto bond_type = p_dev_rec->sec_rec.bond_type;
188 
189   /* Clear out any saved BLE keys */
190   btm_sec_clear_ble_keys(p_dev_rec);
191   wipe_secrets_and_remove(p_dev_rec);
192   /* Tell controller to get rid of the link key, if it has one stored */
193   BTM_DeleteStoredLinkKey(&bda, NULL);
194   log::info("{} complete", bd_addr);
195   BTM_LogHistory(
196           kBtmLogTag, bd_addr, "Device removed",
197           base::StringPrintf("device_type:%s bond_type:%s", DeviceTypeText(device_type).c_str(),
198                              bond_type_text(bond_type).c_str()));
199 
200   return true;
201 }
202 
203 /*******************************************************************************
204  *
205  * Function         BTM_SecClearSecurityFlags
206  *
207  * Description      Reset the security flags (mark as not-paired) for a given
208  *                  remove device.
209  *
210  ******************************************************************************/
BTM_SecClearSecurityFlags(const RawAddress & bd_addr)211 void BTM_SecClearSecurityFlags(const RawAddress& bd_addr) {
212   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
213   if (p_dev_rec == NULL) {
214     return;
215   }
216 
217   p_dev_rec->sec_rec.sec_flags = 0;
218   p_dev_rec->sec_rec.le_link = tSECURITY_STATE::IDLE;
219   p_dev_rec->sec_rec.classic_link = tSECURITY_STATE::IDLE;
220   p_dev_rec->sm4 = BTM_SM4_UNKNOWN;
221 }
222 
223 /*******************************************************************************
224  *
225  * Function         BTM_SecReadDevName
226  *
227  * Description      Looks for the device name in the security database for the
228  *                  specified BD address.
229  *
230  * Returns          Pointer to the name or NULL
231  *
232  ******************************************************************************/
BTM_SecReadDevName(const RawAddress & bd_addr)233 const char* BTM_SecReadDevName(const RawAddress& bd_addr) {
234   const char* p_name = NULL;
235   const tBTM_SEC_DEV_REC* p_srec;
236 
237   p_srec = btm_find_dev(bd_addr);
238   if (p_srec != NULL) {
239     p_name = (const char*)p_srec->sec_bd_name;
240   }
241 
242   return p_name;
243 }
244 
245 /*******************************************************************************
246  *
247  * Function         BTM_SecReadDevClass
248  *
249  * Description      Looks for the class of device in the security database for
250  *                  the specified BD address.
251  *
252  * Returns          Class of device or kDevClassEmpty
253  *
254  ******************************************************************************/
BTM_SecReadDevClass(const RawAddress & bd_addr)255 DEV_CLASS BTM_SecReadDevClass(const RawAddress& bd_addr) {
256   tBTM_SEC_DEV_REC* p_srec = btm_find_dev(bd_addr);
257   if (p_srec != nullptr) {
258     return p_srec->dev_class;
259   }
260 
261   return kDevClassEmpty;
262 }
263 
264 /*******************************************************************************
265  *
266  * Function         btm_sec_alloc_dev
267  *
268  * Description      Allocate a security device record with specified address,
269  *                  fill device type and device class from inquiry database or
270  *                  btm_sec_cb (if the address is the connecting device)
271  *
272  * Returns          Pointer to the record or NULL
273  *
274  ******************************************************************************/
btm_sec_alloc_dev(const RawAddress & bd_addr)275 tBTM_SEC_DEV_REC* btm_sec_alloc_dev(const RawAddress& bd_addr) {
276   tBTM_INQ_INFO* p_inq_info;
277 
278   tBTM_SEC_DEV_REC* p_dev_rec = btm_sec_allocate_dev_rec();
279 
280   log::debug("Allocated device record bd_addr:{}", bd_addr);
281 
282   /* Check with the BT manager if details about remote device are known */
283   /* outgoing connection */
284   p_inq_info = BTM_InqDbRead(bd_addr);
285   if (p_inq_info != NULL) {
286     p_dev_rec->dev_class = p_inq_info->results.dev_class;
287 
288     p_dev_rec->device_type = p_inq_info->results.device_type;
289     if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type)) {
290       p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type);
291     } else {
292       log::warn("Please do not update device record from anonymous le advertisement");
293     }
294 
295   } else if (bd_addr == btm_sec_cb.connecting_bda) {
296     p_dev_rec->dev_class = btm_sec_cb.connecting_dc;
297   }
298 
299   /* update conn params, use default value for background connection params */
300   memset(&p_dev_rec->conn_params, 0xff, sizeof(tBTM_LE_CONN_PRAMS));
301 
302   p_dev_rec->bd_addr = bd_addr;
303 
304   p_dev_rec->ble_hci_handle =
305           get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
306   p_dev_rec->hci_handle =
307           get_btm_client_interface().peer.BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
308 
309   return p_dev_rec;
310 }
311 
is_handle_equal(void * data,void * context)312 static bool is_handle_equal(void* data, void* context) {
313   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
314   uint16_t* handle = static_cast<uint16_t*>(context);
315 
316   if (p_dev_rec->hci_handle == *handle || p_dev_rec->ble_hci_handle == *handle) {
317     return false;
318   }
319 
320   return true;
321 }
322 
323 /*******************************************************************************
324  *
325  * Function         btm_find_dev_by_handle
326  *
327  * Description      Look for the record in the device database for the record
328  *                  with specified handle
329  *
330  * Returns          Pointer to the record or NULL
331  *
332  ******************************************************************************/
btm_find_dev_by_handle(uint16_t handle)333 tBTM_SEC_DEV_REC* btm_find_dev_by_handle(uint16_t handle) {
334   if (btm_sec_cb.sec_dev_rec == nullptr) {
335     return nullptr;
336   }
337 
338   list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_handle_equal, &handle);
339   if (n) {
340     return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
341   }
342 
343   return NULL;
344 }
345 
is_not_same_identity_or_pseudo_address(void * data,void * context)346 static bool is_not_same_identity_or_pseudo_address(void* data, void* context) {
347   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
348   const RawAddress* bd_addr = ((RawAddress*)context);
349 
350   if (p_dev_rec->bd_addr == *bd_addr) {
351     return false;
352   }
353   // If a LE random address is looking for device record
354   if (p_dev_rec->ble.pseudo_addr == *bd_addr) {
355     return false;
356   }
357 
358   return true;
359 }
360 
is_rpa_unresolvable(void * data,void * context)361 static bool is_rpa_unresolvable(void* data, void* context) {
362   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
363   const RawAddress* bd_addr = ((RawAddress*)context);
364 
365   if (btm_ble_addr_resolvable(*bd_addr, p_dev_rec)) {
366     return false;
367   }
368   return true;
369 }
370 /*******************************************************************************
371  *
372  * Function         btm_find_dev
373  *
374  * Description      Look for the record in the device database for the record
375  *                  with specified BD address
376  *
377  * Returns          Pointer to the record or NULL
378  *
379  ******************************************************************************/
btm_find_dev(const RawAddress & bd_addr)380 tBTM_SEC_DEV_REC* btm_find_dev(const RawAddress& bd_addr) {
381   if (btm_sec_cb.sec_dev_rec == nullptr) {
382     return nullptr;
383   }
384 
385   // Find by matching identity address or pseudo address.
386   list_node_t* n = list_foreach(btm_sec_cb.sec_dev_rec, is_not_same_identity_or_pseudo_address,
387                                 (void*)&bd_addr);
388   // If not found by matching identity address or pseudo address, find by RPA
389   if (n == nullptr) {
390     n = list_foreach(btm_sec_cb.sec_dev_rec, is_rpa_unresolvable, (void*)&bd_addr);
391   }
392 
393   if (n != nullptr) {
394     return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
395   }
396 
397   return nullptr;
398 }
399 
has_lenc_and_address_is_equal(void * data,void * context)400 static bool has_lenc_and_address_is_equal(void* data, void* context) {
401   tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(data);
402   if (!(p_dev_rec->sec_rec.ble_keys.key_type & BTM_LE_KEY_LENC)) {
403     return true;
404   }
405 
406   return is_not_same_identity_or_pseudo_address(data, context);
407 }
408 
409 /*******************************************************************************
410  *
411  * Function         btm_find_dev_with_lenc
412  *
413  * Description      Look for the record in the device database with LTK and
414  *                  specified BD address
415  *
416  * Returns          Pointer to the record or NULL
417  *
418  ******************************************************************************/
btm_find_dev_with_lenc(const RawAddress & bd_addr)419 tBTM_SEC_DEV_REC* btm_find_dev_with_lenc(const RawAddress& bd_addr) {
420   if (btm_sec_cb.sec_dev_rec == nullptr) {
421     return nullptr;
422   }
423 
424   list_node_t* n =
425           list_foreach(btm_sec_cb.sec_dev_rec, has_lenc_and_address_is_equal, (void*)&bd_addr);
426   if (n) {
427     return static_cast<tBTM_SEC_DEV_REC*>(list_node(n));
428   }
429 
430   return NULL;
431 }
432 /*******************************************************************************
433  *
434  * Function         btm_consolidate_dev
435  *
436  * Description      combine security records if identified as same peer
437  *
438  * Returns          none
439  *
440  ******************************************************************************/
btm_consolidate_dev(tBTM_SEC_DEV_REC * p_target_rec)441 void btm_consolidate_dev(tBTM_SEC_DEV_REC* p_target_rec) {
442   tBTM_SEC_DEV_REC temp_rec = *p_target_rec;
443 
444   log::verbose("");
445 
446   list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
447   list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec);
448   while (node != end) {
449     tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
450 
451     // we do list_remove in some cases, must grab next before removing
452     node = list_next(node);
453 
454     if (p_target_rec == p_dev_rec) {
455       continue;
456     }
457 
458     if (p_dev_rec->bd_addr == p_target_rec->bd_addr) {
459       memcpy(p_target_rec, p_dev_rec, sizeof(tBTM_SEC_DEV_REC));
460       p_target_rec->ble = temp_rec.ble;
461       p_target_rec->sec_rec.ble_keys = temp_rec.sec_rec.ble_keys;
462       p_target_rec->ble_hci_handle = temp_rec.ble_hci_handle;
463       p_target_rec->sec_rec.enc_key_size = temp_rec.sec_rec.enc_key_size;
464       p_target_rec->conn_params = temp_rec.conn_params;
465       p_target_rec->device_type |= temp_rec.device_type;
466       p_target_rec->sec_rec.sec_flags |= temp_rec.sec_rec.sec_flags;
467 
468       p_target_rec->sec_rec.new_encryption_key_is_p256 =
469               temp_rec.sec_rec.new_encryption_key_is_p256;
470       p_target_rec->sec_rec.bond_type = temp_rec.sec_rec.bond_type;
471 
472       /* remove the combined record */
473       wipe_secrets_and_remove(p_dev_rec);
474       // p_dev_rec gets freed in list_remove, we should not  access it further
475       continue;
476     }
477 
478     /* an RPA device entry is a duplicate of the target record */
479     if (btm_ble_addr_resolvable(p_dev_rec->bd_addr, p_target_rec)) {
480       if (p_target_rec->ble.pseudo_addr == p_dev_rec->bd_addr) {
481         p_target_rec->ble.SetAddressType(p_dev_rec->ble.AddressType());
482         p_target_rec->device_type |= p_dev_rec->device_type;
483 
484         /* remove the combined record */
485         wipe_secrets_and_remove(p_dev_rec);
486       }
487     }
488   }
489 }
490 
491 static BTM_CONSOLIDATION_CB* btm_consolidate_cb = nullptr;
492 
BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB * cb)493 void BTM_SetConsolidationCallback(BTM_CONSOLIDATION_CB* cb) { btm_consolidate_cb = cb; }
494 
495 /* combine security records of established LE connections after Classic pairing
496  * succeeded. */
btm_dev_consolidate_existing_connections(const RawAddress & bd_addr)497 void btm_dev_consolidate_existing_connections(const RawAddress& bd_addr) {
498   tBTM_SEC_DEV_REC* p_target_rec = btm_find_dev(bd_addr);
499   if (!p_target_rec) {
500     log::error("No security record for just bonded device!?!?");
501     return;
502   }
503 
504   if (p_target_rec->ble_hci_handle != HCI_INVALID_HANDLE) {
505     log::info("Not consolidating - already have LE connection");
506     return;
507   }
508 
509   log::info("{}", bd_addr);
510 
511   list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
512   list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec);
513   while (node != end) {
514     tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
515 
516     // we do list_remove in some cases, must grab next before removing
517     node = list_next(node);
518 
519     if (p_target_rec == p_dev_rec) {
520       continue;
521     }
522 
523     /* an RPA device entry is a duplicate of the target record */
524     if (btm_ble_addr_resolvable(p_dev_rec->bd_addr, p_target_rec)) {
525       if (p_dev_rec->ble_hci_handle == HCI_INVALID_HANDLE) {
526         log::info("already disconnected - erasing entry {}", p_dev_rec->bd_addr);
527         wipe_secrets_and_remove(p_dev_rec);
528         continue;
529       }
530 
531       log::info(
532               "Found existing LE connection to just bonded device on {} handle "
533               "0x{:04x}",
534               p_dev_rec->bd_addr, p_dev_rec->ble_hci_handle);
535 
536       RawAddress ble_conn_addr = p_dev_rec->bd_addr;
537       p_target_rec->ble_hci_handle = p_dev_rec->ble_hci_handle;
538 
539       /* remove the old LE record */
540       wipe_secrets_and_remove(p_dev_rec);
541 
542       btm_acl_consolidate(bd_addr, ble_conn_addr);
543       stack::l2cap::get_interface().L2CA_Consolidate(bd_addr, ble_conn_addr);
544       gatt_consolidate(bd_addr, ble_conn_addr);
545       if (btm_consolidate_cb) {
546         btm_consolidate_cb(bd_addr, ble_conn_addr);
547       }
548 
549       /* To avoid race conditions between central/peripheral starting encryption
550        * at same time, initiate it just from central. */
551       if (stack::l2cap::get_interface().L2CA_GetBleConnRole(ble_conn_addr) == HCI_ROLE_CENTRAL) {
552         log::info("Will encrypt existing connection");
553         BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, nullptr, nullptr, BTM_BLE_SEC_ENCRYPT);
554       }
555     }
556   }
557 }
558 
559 /*******************************************************************************
560  *
561  * Function         btm_find_or_alloc_dev
562  *
563  * Description      Look for the record in the device database for the record
564  *                  with specified BD address, if not found, allocate a new
565  *                  record
566  *
567  * Returns          Pointer to the record or NULL
568  *
569  ******************************************************************************/
btm_find_or_alloc_dev(const RawAddress & bd_addr)570 tBTM_SEC_DEV_REC* btm_find_or_alloc_dev(const RawAddress& bd_addr) {
571   tBTM_SEC_DEV_REC* p_dev_rec;
572   log::verbose("btm_find_or_alloc_dev");
573   p_dev_rec = btm_find_dev(bd_addr);
574   if (p_dev_rec == NULL) {
575     /* Allocate a new device record or reuse the oldest one */
576     p_dev_rec = btm_sec_alloc_dev(bd_addr);
577   }
578   return p_dev_rec;
579 }
580 
581 /*******************************************************************************
582  *
583  * Function         btm_find_oldest_dev_rec
584  *
585  * Description      Locates the oldest device record in use. It first looks for
586  *                  the oldest non-paired device.  If all devices are paired it
587  *                  returns the oldest paired device.
588  *
589  * Returns          Pointer to the record or NULL
590  *
591  ******************************************************************************/
btm_find_oldest_dev_rec(void)592 static tBTM_SEC_DEV_REC* btm_find_oldest_dev_rec(void) {
593   tBTM_SEC_DEV_REC* p_oldest = NULL;
594   uint32_t ts_oldest = 0xFFFFFFFF;
595   tBTM_SEC_DEV_REC* p_oldest_paired = NULL;
596   uint32_t ts_oldest_paired = 0xFFFFFFFF;
597 
598   list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
599   for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end;
600        node = list_next(node)) {
601     tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
602 
603     if ((p_dev_rec->sec_rec.sec_flags & (BTM_SEC_LINK_KEY_KNOWN | BTM_SEC_LE_LINK_KEY_KNOWN)) ==
604         0) {
605       // Device is not paired
606       if (p_dev_rec->timestamp < ts_oldest) {
607         p_oldest = p_dev_rec;
608         ts_oldest = p_dev_rec->timestamp;
609       }
610     } else {
611       // Paired device
612       if (p_dev_rec->timestamp < ts_oldest_paired) {
613         p_oldest_paired = p_dev_rec;
614         ts_oldest_paired = p_dev_rec->timestamp;
615       }
616     }
617   }
618 
619   // If we did not find any non-paired devices, use the oldest paired one...
620   if (ts_oldest == 0xFFFFFFFF) {
621     p_oldest = p_oldest_paired;
622   }
623 
624   return p_oldest;
625 }
626 
627 /*******************************************************************************
628  *
629  * Function         btm_sec_allocate_dev_rec
630  *
631  * Description      Attempts to allocate a new device record. If we have
632  *                  exceeded the maximum number of allowable records to
633  *                  allocate, the oldest record will be deleted to make room
634  *                  for the new record.
635  *
636  * Returns          Pointer to the newly allocated record
637  *
638  ******************************************************************************/
btm_sec_allocate_dev_rec(void)639 tBTM_SEC_DEV_REC* btm_sec_allocate_dev_rec(void) {
640   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
641 
642   if (btm_sec_cb.sec_dev_rec == nullptr) {
643     log::warn("Unable to allocate device record with destructed device record list");
644     return nullptr;
645   }
646 
647   if (list_length(btm_sec_cb.sec_dev_rec) > BTM_SEC_MAX_DEVICE_RECORDS) {
648     p_dev_rec = btm_find_oldest_dev_rec();
649     wipe_secrets_and_remove(p_dev_rec);
650   }
651 
652   p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(osi_calloc(sizeof(tBTM_SEC_DEV_REC)));
653   list_append(btm_sec_cb.sec_dev_rec, p_dev_rec);
654 
655   // Initialize defaults
656   p_dev_rec->sec_rec.sec_flags = BTM_SEC_IN_USE;
657   p_dev_rec->sec_rec.bond_type = BOND_TYPE_UNKNOWN;
658   p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
659   p_dev_rec->sec_rec.rmt_io_caps = BTM_IO_CAP_UNKNOWN;
660   p_dev_rec->suggested_tx_octets = 0;
661 
662   return p_dev_rec;
663 }
664 
665 /*******************************************************************************
666  *
667  * Function         btm_get_bond_type_dev
668  *
669  * Description      Get the bond type for a device in the device database
670  *                  with specified BD address
671  *
672  * Returns          The device bond type if known, otherwise BOND_TYPE_UNKNOWN
673  *
674  ******************************************************************************/
btm_get_bond_type_dev(const RawAddress & bd_addr)675 tBTM_BOND_TYPE btm_get_bond_type_dev(const RawAddress& bd_addr) {
676   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
677 
678   if (p_dev_rec == NULL) {
679     return BOND_TYPE_UNKNOWN;
680   }
681 
682   return p_dev_rec->sec_rec.bond_type;
683 }
684 
685 /*******************************************************************************
686  *
687  * Function         btm_set_bond_type_dev
688  *
689  * Description      Set the bond type for a device in the device database
690  *                  with specified BD address
691  *
692  * Returns          true on success, otherwise false
693  *
694  ******************************************************************************/
btm_set_bond_type_dev(const RawAddress & bd_addr,tBTM_BOND_TYPE bond_type)695 bool btm_set_bond_type_dev(const RawAddress& bd_addr, tBTM_BOND_TYPE bond_type) {
696   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
697 
698   if (p_dev_rec == NULL) {
699     return false;
700   }
701 
702   p_dev_rec->sec_rec.bond_type = bond_type;
703   return true;
704 }
705 
706 /*******************************************************************************
707  *
708  * Function         btm_get_sec_dev_rec
709  *
710  * Description      Get all security device records
711  *
712  * Returns          A vector containing pointers to all security device records
713  *
714  ******************************************************************************/
btm_get_sec_dev_rec()715 std::vector<tBTM_SEC_DEV_REC*> btm_get_sec_dev_rec() {
716   std::vector<tBTM_SEC_DEV_REC*> result{};
717 
718   if (btm_sec_cb.sec_dev_rec != nullptr) {
719     list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
720     for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end;
721          node = list_next(node)) {
722       tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
723       result.push_back(p_dev_rec);
724     }
725   }
726   return result;
727 }
728 
729 /*******************************************************************************
730  *
731  * Function         BTM_Sec_AddressKnown
732  *
733  * Description      Query the secure device database and check
734  *                  whether the device associated with address has
735  *                  its address resolved
736  *
737  * Returns          True if
738  *                     - the device is unknown, or
739  *                     - the device is classic, or
740  *                     - the device is ble and has a public address
741  *                     - the device is ble with a resolved identity address
742  *                  False, otherwise
743  *
744  ******************************************************************************/
BTM_Sec_AddressKnown(const RawAddress & address)745 bool BTM_Sec_AddressKnown(const RawAddress& address) {
746   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
747 
748   // not a known device, we assume public address
749   if (p_dev_rec == NULL) {
750     log::warn("{}, unknown device", address);
751     return true;
752   }
753   // a classic device, we assume public address
754   if ((p_dev_rec->device_type & BT_DEVICE_TYPE_BLE) == 0) {
755     log::warn("{}, device type not BLE: 0x{:02x}", address, p_dev_rec->device_type);
756     return true;
757   }
758 
759   // bonded device with identity address known
760   if (!p_dev_rec->ble.identity_address_with_type.bda.IsEmpty()) {
761     return true;
762   }
763 
764   // Public address, Random Static, or Random Non-Resolvable Address known
765   if (p_dev_rec->ble.AddressType() == BLE_ADDR_PUBLIC || !BTM_BLE_IS_RESOLVE_BDA(address)) {
766     return true;
767   }
768 
769   log::warn("{}, the address type is 0x{:02x}", address, p_dev_rec->ble.AddressType());
770 
771   // Only Resolvable Private Address (RPA) is known, we don't allow it into
772   // the background connection procedure.
773   return false;
774 }
775 
BTM_Sec_GetAddressWithType(const RawAddress & bd_addr)776 const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) {
777   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
778   if (p_dev_rec == nullptr || !p_dev_rec->is_device_type_has_ble()) {
779     return {
780             .type = BLE_ADDR_PUBLIC,
781             .bda = bd_addr,
782     };
783   }
784 
785   if (p_dev_rec->ble.identity_address_with_type.bda.IsEmpty()) {
786     return {
787             .type = p_dev_rec->ble.AddressType(),
788             .bda = bd_addr,
789     };
790   } else {
791     // Floss doesn't support LL Privacy (yet). To expedite ARC testing, always
792     // connect to the latest LE random address (if available and LL Privacy is
793     // not enabled) rather than redesign.
794     // TODO(b/235218533): Remove when LL Privacy is implemented.
795 #if TARGET_FLOSS
796     if (!p_dev_rec->ble.cur_rand_addr.IsEmpty() &&
797         btm_cb.ble_ctr_cb.privacy_mode < BTM_PRIVACY_1_2) {
798       return {
799               .type = BLE_ADDR_RANDOM,
800               .bda = p_dev_rec->ble.cur_rand_addr,
801       };
802     }
803 #endif
804     return p_dev_rec->ble.identity_address_with_type;
805   }
806 }
807 
808 #define DUMPSYS_TAG "shim::record"
DumpsysRecord(int fd)809 void DumpsysRecord(int fd) {
810   LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
811 
812   if (btm_sec_cb.sec_dev_rec == nullptr) {
813     LOG_DUMPSYS(fd, "Record is empty - no devices");
814     return;
815   }
816 
817   unsigned cnt = 0;
818   list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
819   for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end;
820        node = list_next(node)) {
821     tBTM_SEC_DEV_REC* p_dev_rec = static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
822     // TODO: handle in tBTM_SEC_DEV_REC.ToString
823     LOG_DUMPSYS(fd, "%03u %s", ++cnt, p_dev_rec->ToString().c_str());
824   }
825 }
826 #undef DUMPSYS_TAG
827 
828 namespace bluetooth {
829 namespace testing {
830 namespace legacy {
831 
wipe_secrets_and_remove(tBTM_SEC_DEV_REC * p_dev_rec)832 void wipe_secrets_and_remove(tBTM_SEC_DEV_REC* p_dev_rec) { ::wipe_secrets_and_remove(p_dev_rec); }
833 
834 }  // namespace legacy
835 }  // namespace testing
836 }  // namespace bluetooth
837