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