• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 BLE device control utilities, and LE
22  *  security functions.
23  *
24  ******************************************************************************/
25 
26 #define LOG_TAG "bt_btm_ble"
27 
28 #include <base/logging.h>
29 #include <base/strings/stringprintf.h>
30 
31 #include <cstdint>
32 
33 #include "btif/include/btif_storage.h"
34 #include "device/include/controller.h"
35 #include "main/shim/btm_api.h"
36 #include "main/shim/l2c_api.h"
37 #include "main/shim/shim.h"
38 #include "openssl/mem.h"
39 #include "osi/include/allocator.h"
40 #include "osi/include/properties.h"
41 #include "stack/btm/btm_dev.h"
42 #include "stack/btm/btm_int_types.h"
43 #include "stack/btm/security_device_record.h"
44 #include "stack/crypto_toolbox/crypto_toolbox.h"
45 #include "stack/eatt/eatt.h"
46 #include "stack/include/acl_api.h"
47 #include "stack/include/bt_octets.h"
48 #include "stack/include/bt_types.h"
49 #include "stack/include/btm_api.h"
50 #include "stack/include/btm_log_history.h"
51 #include "stack/include/btu.h"
52 #include "stack/include/gatt_api.h"
53 #include "stack/include/l2cap_security_interface.h"
54 #include "stack/include/l2cdefs.h"
55 #include "stack/include/smp_api.h"
56 #include "stack/include/smp_api_types.h"
57 #include "types/raw_address.h"
58 
59 extern tBTM_CB btm_cb;
60 
61 bool btm_ble_init_pseudo_addr(tBTM_SEC_DEV_REC* p_dev_rec,
62                               const RawAddress& new_pseudo_addr);
63 void gatt_notify_phy_updated(tGATT_STATUS status, uint16_t handle,
64                              uint8_t tx_phy, uint8_t rx_phy);
65 
66 #ifndef PROPERTY_BLE_PRIVACY_ENABLED
67 #define PROPERTY_BLE_PRIVACY_ENABLED "bluetooth.core.gap.le.privacy.enabled"
68 #endif
69 
70 namespace {
71 constexpr char kBtmLogTag[] = "SEC";
72 }
73 
74 // Pairing parameters defined in Vol 3, Part H, Chapter 3.5.1 - 3.5.2
75 // All present in the exact decimal values, not hex
76 // Ex: bluetooth.core.smp.le.ctkd.initiator_key_distribution 15(0x0f)
77 static const char kPropertyCtkdAuthRequest[] =
78     "bluetooth.core.smp.le.ctkd.auth_request";
79 static const char kPropertyCtkdIoCapabilities[] =
80     "bluetooth.core.smp.le.ctkd.io_capabilities";
81 // Vol 3, Part H, Chapter 3.6.1, Figure 3.11
82 // |EncKey(1)|IdKey(1)|SignKey(1)|LinkKey(1)|Reserved(4)|
83 static const char kPropertyCtkdInitiatorKeyDistribution[] =
84     "bluetooth.core.smp.le.ctkd.initiator_key_distribution";
85 static const char kPropertyCtkdResponderKeyDistribution[] =
86     "bluetooth.core.smp.le.ctkd.responder_key_distribution";
87 static const char kPropertyCtkdMaxKeySize[] =
88     "bluetooth.core.smp.le.ctkd.max_key_size";
89 
90 /******************************************************************************/
91 /* External Function to be called by other modules                            */
92 /******************************************************************************/
BTM_SecAddBleDevice(const RawAddress & bd_addr,tBT_DEVICE_TYPE dev_type,tBLE_ADDR_TYPE addr_type)93 void BTM_SecAddBleDevice(const RawAddress& bd_addr, tBT_DEVICE_TYPE dev_type,
94                          tBLE_ADDR_TYPE addr_type) {
95   LOG_DEBUG("dev_type=0x%x", dev_type);
96 
97   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
98   if (!p_dev_rec) {
99     p_dev_rec = btm_sec_allocate_dev_rec();
100 
101     p_dev_rec->bd_addr = bd_addr;
102     p_dev_rec->hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
103     p_dev_rec->ble_hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
104 
105     /* update conn params, use default value for background connection params */
106     p_dev_rec->conn_params.min_conn_int = BTM_BLE_CONN_PARAM_UNDEF;
107     p_dev_rec->conn_params.max_conn_int = BTM_BLE_CONN_PARAM_UNDEF;
108     p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_PARAM_UNDEF;
109     p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PARAM_UNDEF;
110 
111     LOG_DEBUG("Device added, handle=0x%x, p_dev_rec=%p, bd_addr=%s",
112               p_dev_rec->ble_hci_handle, p_dev_rec, ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
113   }
114 
115   memset(p_dev_rec->sec_bd_name, 0, sizeof(tBTM_BD_NAME));
116 
117   p_dev_rec->device_type |= dev_type;
118   if (is_ble_addr_type_known(addr_type)) {
119     p_dev_rec->ble.SetAddressType(addr_type);
120   } else {
121     LOG_WARN(
122         "Please do not update device record from anonymous le advertisement");
123   }
124 
125   /* sync up with the Inq Data base*/
126   tBTM_INQ_INFO* p_info = BTM_InqDbRead(bd_addr);
127   if (p_info) {
128     p_info->results.ble_addr_type = p_dev_rec->ble.AddressType();
129     p_dev_rec->device_type |= p_info->results.device_type;
130     LOG_DEBUG("InqDb device_type =0x%x addr_type=0x%x", p_dev_rec->device_type,
131               p_info->results.ble_addr_type);
132     p_info->results.device_type = p_dev_rec->device_type;
133   }
134 }
135 
136 /*******************************************************************************
137  *
138  * Function         BTM_GetRemoteDeviceName
139  *
140  * Description      This function is called to get the dev name of remote device
141  *                  from NV
142  *
143  * Returns          TRUE if success; otherwise failed.
144  *
145  ******************************************************************************/
BTM_GetRemoteDeviceName(const RawAddress & bd_addr,BD_NAME bd_name)146 bool BTM_GetRemoteDeviceName(const RawAddress& bd_addr, BD_NAME bd_name) {
147   BTM_TRACE_DEBUG("%s", __func__);
148   bool ret = FALSE;
149   bt_bdname_t bdname;
150   bt_property_t prop_name;
151   BTIF_STORAGE_FILL_PROPERTY(&prop_name, BT_PROPERTY_BDNAME,
152                              sizeof(bt_bdname_t), &bdname);
153 
154   if (btif_storage_get_remote_device_property(&bd_addr, &prop_name) ==
155       BT_STATUS_SUCCESS) {
156     APPL_TRACE_DEBUG("%s, NV name = %s", __func__, bdname.name);
157     strncpy((char*)bd_name, (char*)bdname.name, BD_NAME_LEN + 1);
158     ret = TRUE;
159   }
160   return ret;
161 }
162 
163 /*******************************************************************************
164  *
165  * Function         BTM_SecAddBleKey
166  *
167  * Description      Add/modify LE device information.  This function will be
168  *                  normally called during host startup to restore all required
169  *                  information stored in the NVRAM.
170  *
171  * Parameters:      bd_addr          - BD address of the peer
172  *                  p_le_key         - LE key values.
173  *                  key_type         - LE SMP key type.
174 *
175  * Returns          true if added OK, else false
176  *
177  ******************************************************************************/
BTM_SecAddBleKey(const RawAddress & bd_addr,tBTM_LE_KEY_VALUE * p_le_key,tBTM_LE_KEY_TYPE key_type)178 void BTM_SecAddBleKey(const RawAddress& bd_addr, tBTM_LE_KEY_VALUE* p_le_key,
179                       tBTM_LE_KEY_TYPE key_type) {
180   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
181   if (!p_dev_rec || !p_le_key ||
182       (key_type != BTM_LE_KEY_PENC && key_type != BTM_LE_KEY_PID &&
183        key_type != BTM_LE_KEY_PCSRK && key_type != BTM_LE_KEY_LENC &&
184        key_type != BTM_LE_KEY_LCSRK && key_type != BTM_LE_KEY_LID)) {
185     LOG(WARNING) << __func__
186                  << " Wrong Type, or No Device record for bdaddr: " << bd_addr
187                  << ", Type: " << key_type;
188     return;
189   }
190 
191   LOG_DEBUG("Adding BLE key device:%s key_type:%hhu", ADDRESS_TO_LOGGABLE_CSTR(bd_addr),
192             key_type);
193 
194   btm_sec_save_le_key(bd_addr, key_type, p_le_key, false);
195   // Only set peer irk. Local irk is always the same.
196   if (key_type == BTM_LE_KEY_PID) {
197     btm_ble_resolving_list_load_dev(*p_dev_rec);
198   }
199 }
200 
201 /*******************************************************************************
202  *
203  * Function         BTM_BleLoadLocalKeys
204  *
205  * Description      Local local identity key, encryption root or sign counter.
206  *
207  * Parameters:      key_type: type of key, can be BTM_BLE_KEY_TYPE_ID,
208  *                                                BTM_BLE_KEY_TYPE_ER
209  *                                             or BTM_BLE_KEY_TYPE_COUNTER.
210  *                  p_key: pointer to the key.
211  *
212  * Returns          non2.
213  *
214  ******************************************************************************/
BTM_BleLoadLocalKeys(uint8_t key_type,tBTM_BLE_LOCAL_KEYS * p_key)215 void BTM_BleLoadLocalKeys(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) {
216   tBTM_DEVCB* p_devcb = &btm_cb.devcb;
217   BTM_TRACE_DEBUG("%s", __func__);
218   if (p_key != NULL) {
219     switch (key_type) {
220       case BTM_BLE_KEY_TYPE_ID:
221         memcpy(&p_devcb->id_keys, &p_key->id_keys,
222                sizeof(tBTM_BLE_LOCAL_ID_KEYS));
223         break;
224 
225       case BTM_BLE_KEY_TYPE_ER:
226         p_devcb->ble_encryption_key_value = p_key->er;
227         break;
228 
229       default:
230         BTM_TRACE_ERROR("unknow local key type: %d", key_type);
231         break;
232     }
233   }
234 }
235 
236 /** Returns local device encryption root (ER) */
BTM_GetDeviceEncRoot()237 const Octet16& BTM_GetDeviceEncRoot() {
238   return btm_cb.devcb.ble_encryption_key_value;
239 }
240 
241 /** Returns local device identity root (IR). */
BTM_GetDeviceIDRoot()242 const Octet16& BTM_GetDeviceIDRoot() { return btm_cb.devcb.id_keys.irk; }
243 
244 /** Return local device DHK. */
BTM_GetDeviceDHK()245 const Octet16& BTM_GetDeviceDHK() { return btm_cb.devcb.id_keys.dhk; }
246 
247 /*******************************************************************************
248  *
249  * Function         BTM_SecurityGrant
250  *
251  * Description      This function is called to grant security process.
252  *
253  * Parameters       bd_addr - peer device bd address.
254  *                  res     - result of the operation BTM_SUCCESS if success.
255  *                            Otherwise, BTM_REPEATED_ATTEMPTS if too many
256  *                            attempts.
257  *
258  * Returns          None
259  *
260  ******************************************************************************/
BTM_SecurityGrant(const RawAddress & bd_addr,uint8_t res)261 void BTM_SecurityGrant(const RawAddress& bd_addr, uint8_t res) {
262   const tSMP_STATUS res_smp =
263       (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_REPEATED_ATTEMPTS;
264   BTM_LogHistory(kBtmLogTag, bd_addr, "Granted",
265                  base::StringPrintf("passkey_status:%s",
266                                     smp_status_text(res_smp).c_str()));
267 
268   BTM_TRACE_DEBUG("BTM_SecurityGrant");
269   SMP_SecurityGrant(bd_addr, res_smp);
270 }
271 
272 /*******************************************************************************
273  *
274  * Function         BTM_BlePasskeyReply
275  *
276  * Description      This function is called after Security Manager submitted
277  *                  passkey request to the application.
278  *
279  * Parameters:      bd_addr - Address of the device for which passkey was
280  *                            requested
281  *                  res     - result of the operation BTM_SUCCESS if success
282  *                  key_len - length in bytes of the Passkey
283  *                  p_passkey    - pointer to array with the passkey
284  *
285  ******************************************************************************/
BTM_BlePasskeyReply(const RawAddress & bd_addr,uint8_t res,uint32_t passkey)286 void BTM_BlePasskeyReply(const RawAddress& bd_addr, uint8_t res,
287                          uint32_t passkey) {
288   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
289   if (p_dev_rec == NULL) {
290     BTM_TRACE_ERROR("Passkey reply to Unknown device");
291     return;
292   }
293 
294   const tSMP_STATUS res_smp =
295       (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
296   BTM_LogHistory(kBtmLogTag, bd_addr, "Passkey reply",
297                  base::StringPrintf("transport:%s authenticate_status:%s",
298                                     bt_transport_text(BT_TRANSPORT_LE).c_str(),
299                                     smp_status_text(res_smp).c_str()));
300 
301   p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
302   BTM_TRACE_DEBUG("BTM_BlePasskeyReply");
303   SMP_PasskeyReply(bd_addr, res_smp, passkey);
304 }
305 
306 /*******************************************************************************
307  *
308  * Function         BTM_BleConfirmReply
309  *
310  * Description      This function is called after Security Manager submitted
311  *                  numeric comparison request to the application.
312  *
313  * Parameters:      bd_addr      - Address of the device with which numeric
314  *                                 comparison was requested
315  *                  res          - comparison result BTM_SUCCESS if success
316  *
317  ******************************************************************************/
BTM_BleConfirmReply(const RawAddress & bd_addr,uint8_t res)318 void BTM_BleConfirmReply(const RawAddress& bd_addr, uint8_t res) {
319   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
320   if (p_dev_rec == NULL) {
321     BTM_TRACE_ERROR("Passkey reply to Unknown device");
322     return;
323   }
324   const tSMP_STATUS res_smp =
325       (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_PASSKEY_ENTRY_FAIL;
326 
327   BTM_LogHistory(kBtmLogTag, bd_addr, "Confirm reply",
328                  base::StringPrintf(
329                      "transport:%s numeric_comparison_authenticate_status:%s",
330                      bt_transport_text(BT_TRANSPORT_LE).c_str(),
331                      smp_status_text(res_smp).c_str()));
332 
333   p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
334   BTM_TRACE_DEBUG("%s", __func__);
335   SMP_ConfirmReply(bd_addr, res_smp);
336 }
337 
338 /*******************************************************************************
339  *
340  * Function         BTM_BleOobDataReply
341  *
342  * Description      This function is called to provide the OOB data for
343  *                  SMP in response to BTM_LE_OOB_REQ_EVT
344  *
345  * Parameters:      bd_addr     - Address of the peer device
346  *                  res         - result of the operation SMP_SUCCESS if success
347  *                  p_data      - oob data, depending on transport and
348  *                                capabilities.
349  *                                Might be "Simple Pairing Randomizer", or
350  *                                "Security Manager TK Value".
351  *
352  ******************************************************************************/
BTM_BleOobDataReply(const RawAddress & bd_addr,uint8_t res,uint8_t len,uint8_t * p_data)353 void BTM_BleOobDataReply(const RawAddress& bd_addr, uint8_t res, uint8_t len,
354                          uint8_t* p_data) {
355   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
356   if (p_dev_rec == NULL) {
357     BTM_TRACE_ERROR("%s: Unknown device", __func__);
358     return;
359   }
360 
361   const tSMP_STATUS res_smp = (res == BTM_SUCCESS) ? SMP_SUCCESS : SMP_OOB_FAIL;
362   BTM_LogHistory(kBtmLogTag, bd_addr, "Oob data reply",
363                  base::StringPrintf("transport:%s authenticate_status:%s",
364                                     bt_transport_text(BT_TRANSPORT_LE).c_str(),
365                                     smp_status_text(res_smp).c_str()));
366 
367   p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
368   SMP_OobDataReply(bd_addr, res_smp, len, p_data);
369 }
370 
371 /*******************************************************************************
372  *
373  * Function         BTM_BleSecureConnectionOobDataReply
374  *
375  * Description      This function is called to provide the OOB data for
376  *                  SMP in response to BTM_LE_OOB_REQ_EVT when secure connection
377  *                  data is available
378  *
379  * Parameters:      bd_addr     - Address of the peer device
380  *                  p_c         - pointer to Confirmation.
381  *                  p_r         - pointer to Randomizer
382  *
383  ******************************************************************************/
BTM_BleSecureConnectionOobDataReply(const RawAddress & bd_addr,uint8_t * p_c,uint8_t * p_r)384 void BTM_BleSecureConnectionOobDataReply(const RawAddress& bd_addr,
385                                          uint8_t* p_c, uint8_t* p_r) {
386   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
387   if (p_dev_rec == NULL) {
388     BTM_TRACE_ERROR("%s: Unknown device", __func__);
389     return;
390   }
391 
392   BTM_LogHistory(
393       kBtmLogTag, bd_addr, "Oob data reply",
394       base::StringPrintf("transport:%s",
395                          bt_transport_text(BT_TRANSPORT_LE).c_str()));
396 
397   p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
398 
399   tSMP_SC_OOB_DATA oob;
400   memset(&oob, 0, sizeof(tSMP_SC_OOB_DATA));
401 
402   oob.peer_oob_data.present = true;
403   memcpy(&oob.peer_oob_data.randomizer, p_r, OCTET16_LEN);
404   memcpy(&oob.peer_oob_data.commitment, p_c, OCTET16_LEN);
405   oob.peer_oob_data.addr_rcvd_from.type = p_dev_rec->ble.AddressType();
406   oob.peer_oob_data.addr_rcvd_from.bda = bd_addr;
407 
408   SMP_SecureConnectionOobDataReply((uint8_t*)&oob);
409 }
410 
411 /********************************************************
412  *
413  * Function         BTM_BleSetPrefConnParams
414  *
415  * Description      Set a peripheral's preferred connection parameters
416  *
417  * Parameters:      bd_addr          - BD address of the peripheral
418  *                  scan_interval: scan interval
419  *                  scan_window: scan window
420  *                  min_conn_int     - minimum preferred connection interval
421  *                  max_conn_int     - maximum preferred connection interval
422  *                  peripheral_latency    - preferred peripheral latency
423  *                  supervision_tout - preferred supervision timeout
424  *
425  * Returns          void
426  *
427  ******************************************************************************/
BTM_BleSetPrefConnParams(const RawAddress & bd_addr,uint16_t min_conn_int,uint16_t max_conn_int,uint16_t peripheral_latency,uint16_t supervision_tout)428 void BTM_BleSetPrefConnParams(const RawAddress& bd_addr, uint16_t min_conn_int,
429                               uint16_t max_conn_int,
430                               uint16_t peripheral_latency,
431                               uint16_t supervision_tout) {
432   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
433 
434   BTM_TRACE_API(
435       "BTM_BleSetPrefConnParams min: %u  max: %u  latency: %u  \
436                     tout: %u",
437       min_conn_int, max_conn_int, peripheral_latency, supervision_tout);
438 
439   if (BTM_BLE_ISVALID_PARAM(min_conn_int, BTM_BLE_CONN_INT_MIN,
440                             BTM_BLE_CONN_INT_MAX) &&
441       BTM_BLE_ISVALID_PARAM(max_conn_int, BTM_BLE_CONN_INT_MIN,
442                             BTM_BLE_CONN_INT_MAX) &&
443       BTM_BLE_ISVALID_PARAM(supervision_tout, BTM_BLE_CONN_SUP_TOUT_MIN,
444                             BTM_BLE_CONN_SUP_TOUT_MAX) &&
445       (peripheral_latency <= BTM_BLE_CONN_LATENCY_MAX ||
446        peripheral_latency == BTM_BLE_CONN_PARAM_UNDEF)) {
447     if (p_dev_rec) {
448       /* expect conn int and stout and peripheral latency to be updated all
449        * together
450        */
451       if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF ||
452           max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) {
453         if (min_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
454           p_dev_rec->conn_params.min_conn_int = min_conn_int;
455         else
456           p_dev_rec->conn_params.min_conn_int = max_conn_int;
457 
458         if (max_conn_int != BTM_BLE_CONN_PARAM_UNDEF)
459           p_dev_rec->conn_params.max_conn_int = max_conn_int;
460         else
461           p_dev_rec->conn_params.max_conn_int = min_conn_int;
462 
463         if (peripheral_latency != BTM_BLE_CONN_PARAM_UNDEF)
464           p_dev_rec->conn_params.peripheral_latency = peripheral_latency;
465         else
466           p_dev_rec->conn_params.peripheral_latency =
467               BTM_BLE_CONN_PERIPHERAL_LATENCY_DEF;
468 
469         if (supervision_tout != BTM_BLE_CONN_PARAM_UNDEF)
470           p_dev_rec->conn_params.supervision_tout = supervision_tout;
471         else
472           p_dev_rec->conn_params.supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF;
473       }
474 
475     } else {
476       BTM_TRACE_ERROR("Unknown Device, setting rejected");
477     }
478   } else {
479     BTM_TRACE_ERROR("Illegal Connection Parameters");
480   }
481 }
482 
483 /*******************************************************************************
484  *
485  * Function         BTM_ReadDevInfo
486  *
487  * Description      This function is called to read the device/address type
488  *                  of BD address.
489  *
490  * Parameter        remote_bda: remote device address
491  *                  p_dev_type: output parameter to read the device type.
492  *                  p_addr_type: output parameter to read the address type.
493  *
494  ******************************************************************************/
BTM_ReadDevInfo(const RawAddress & remote_bda,tBT_DEVICE_TYPE * p_dev_type,tBLE_ADDR_TYPE * p_addr_type)495 void BTM_ReadDevInfo(const RawAddress& remote_bda, tBT_DEVICE_TYPE* p_dev_type,
496                      tBLE_ADDR_TYPE* p_addr_type) {
497   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(remote_bda);
498   tBTM_INQ_INFO* p_inq_info = BTM_InqDbRead(remote_bda);
499 
500   *p_addr_type = BLE_ADDR_PUBLIC;
501 
502   if (!p_dev_rec) {
503     *p_dev_type = BT_DEVICE_TYPE_BREDR;
504     /* Check with the BT manager if details about remote device are known */
505     if (p_inq_info != NULL) {
506       *p_dev_type = p_inq_info->results.device_type;
507       *p_addr_type = p_inq_info->results.ble_addr_type;
508     } else {
509       /* unknown device, assume BR/EDR */
510       BTM_TRACE_DEBUG("btm_find_dev_type - unknown device, BR/EDR assumed");
511     }
512   } else /* there is a security device record exisitng */
513   {
514     /* new inquiry result, merge device type in security device record */
515     if (p_inq_info) {
516       p_dev_rec->device_type |= p_inq_info->results.device_type;
517       if (is_ble_addr_type_known(p_inq_info->results.ble_addr_type))
518         p_dev_rec->ble.SetAddressType(p_inq_info->results.ble_addr_type);
519       else
520         LOG_WARN(
521             "Please do not update device record from anonymous le "
522             "advertisement");
523     }
524 
525     if (p_dev_rec->bd_addr == remote_bda &&
526         p_dev_rec->ble.pseudo_addr == remote_bda) {
527       *p_dev_type = p_dev_rec->device_type;
528       *p_addr_type = p_dev_rec->ble.AddressType();
529     } else if (p_dev_rec->ble.pseudo_addr == remote_bda) {
530       *p_dev_type = BT_DEVICE_TYPE_BLE;
531       *p_addr_type = p_dev_rec->ble.AddressType();
532     } else /* matching static adddress only */ {
533       if (p_dev_rec->device_type != BT_DEVICE_TYPE_UNKNOWN) {
534         *p_dev_type = p_dev_rec->device_type;
535       } else {
536         LOG_WARN("device_type not set; assuming BR/EDR");
537         *p_dev_type = BT_DEVICE_TYPE_BREDR;
538       }
539       *p_addr_type = BLE_ADDR_PUBLIC;
540     }
541   }
542   LOG_DEBUG("Determining device_type:%s addr_type:%s",
543             DeviceTypeText(*p_dev_type).c_str(),
544             AddressTypeText(*p_addr_type).c_str());
545 }
546 
547 /*******************************************************************************
548  *
549  * Function         BTM_ReadConnectedTransportAddress
550  *
551  * Description      This function is called to read the paired device/address
552  *                  type of other device paired corresponding to the BD_address
553  *
554  * Parameter        remote_bda: remote device address, carry out the transport
555  *                              address
556  *                  transport: active transport
557  *
558  * Return           true if an active link is identified; false otherwise
559  *
560  ******************************************************************************/
BTM_ReadConnectedTransportAddress(RawAddress * remote_bda,tBT_TRANSPORT transport)561 bool BTM_ReadConnectedTransportAddress(RawAddress* remote_bda,
562                                        tBT_TRANSPORT transport) {
563   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(*remote_bda);
564 
565   /* if no device can be located, return */
566   if (p_dev_rec == NULL) return false;
567 
568   if (transport == BT_TRANSPORT_BR_EDR) {
569     if (BTM_IsAclConnectionUp(p_dev_rec->bd_addr, transport)) {
570       *remote_bda = p_dev_rec->bd_addr;
571       return true;
572     } else if (p_dev_rec->device_type & BT_DEVICE_TYPE_BREDR) {
573       *remote_bda = p_dev_rec->bd_addr;
574     } else
575       *remote_bda = RawAddress::kEmpty;
576     return false;
577   }
578 
579   if (transport == BT_TRANSPORT_LE) {
580     *remote_bda = p_dev_rec->ble.pseudo_addr;
581     if (BTM_IsAclConnectionUp(p_dev_rec->ble.pseudo_addr, transport))
582       return true;
583     else
584       return false;
585   }
586 
587   return false;
588 }
589 
590 /*******************************************************************************
591  *
592  * Function         BTM_UseLeLink
593  *
594  * Description      This function is to select the underlying physical link to
595  *                  use.
596  *
597  * Returns          true to use LE, false use BR/EDR.
598  *
599  ******************************************************************************/
BTM_UseLeLink(const RawAddress & bd_addr)600 bool BTM_UseLeLink(const RawAddress& bd_addr) {
601   if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_BR_EDR)) {
602     return false;
603   } else if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
604     return true;
605   }
606 
607   tBT_DEVICE_TYPE dev_type;
608   tBLE_ADDR_TYPE addr_type;
609   BTM_ReadDevInfo(bd_addr, &dev_type, &addr_type);
610   return (dev_type == BT_DEVICE_TYPE_BLE);
611 }
612 
BTM_SetBleDataLength(const RawAddress & bd_addr,uint16_t tx_pdu_length)613 tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr,
614                                  uint16_t tx_pdu_length) {
615   if (!controller_get_interface()->supports_ble_packet_extension()) {
616     LOG_INFO("Local controller unable to support le packet extension");
617     return BTM_ILLEGAL_VALUE;
618   }
619 
620   LOG_INFO("%s, %d", ADDRESS_TO_LOGGABLE_CSTR(bd_addr), tx_pdu_length);
621 
622   auto p_dev_rec = btm_find_dev(bd_addr);
623   if (p_dev_rec == NULL) {
624     LOG_ERROR("Device %s not found", ADDRESS_TO_LOGGABLE_CSTR(bd_addr));
625     return BTM_UNKNOWN_ADDR;
626   }
627 
628   if (tx_pdu_length > BTM_BLE_DATA_SIZE_MAX)
629     tx_pdu_length = BTM_BLE_DATA_SIZE_MAX;
630   else if (tx_pdu_length < BTM_BLE_DATA_SIZE_MIN)
631     tx_pdu_length = BTM_BLE_DATA_SIZE_MIN;
632 
633   if (p_dev_rec->get_suggested_tx_octets() >= tx_pdu_length) {
634     LOG_INFO(" Suggested TX octect already set to controller %d >= %d",
635              p_dev_rec->get_suggested_tx_octets(), tx_pdu_length);
636     return BTM_SUCCESS;
637   }
638 
639   uint16_t tx_time = BTM_BLE_DATA_TX_TIME_MAX_LEGACY;
640 
641   if (controller_get_interface()->get_bt_version()->hci_version >=
642       HCI_PROTO_VERSION_5_0)
643     tx_time = BTM_BLE_DATA_TX_TIME_MAX;
644 
645   if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
646     LOG_INFO(
647         "Unable to set data length because no le acl link connected to device");
648     return BTM_WRONG_MODE;
649   }
650 
651   if (bluetooth::shim::is_gd_l2cap_enabled()) {
652     uint16_t handle = bluetooth::shim::L2CA_GetLeHandle(bd_addr);
653     btsnd_hcic_ble_set_data_length(handle, tx_pdu_length, tx_time);
654     p_dev_rec->set_suggested_tx_octect(tx_pdu_length);
655     return BTM_SUCCESS;
656   }
657 
658   uint16_t hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
659 
660   if (!acl_peer_supports_ble_packet_extension(hci_handle)) {
661     LOG_INFO("Remote device unable to support le packet extension");
662     return BTM_ILLEGAL_VALUE;
663   }
664 
665   tx_pdu_length = std::min<uint16_t>(
666       tx_pdu_length,
667       controller_get_interface()->get_ble_maximum_tx_data_length());
668   tx_time = std::min<uint16_t>(
669       tx_time, controller_get_interface()->get_ble_maximum_tx_time());
670 
671   btsnd_hcic_ble_set_data_length(hci_handle, tx_pdu_length, tx_time);
672   p_dev_rec->set_suggested_tx_octect(tx_pdu_length);
673 
674   return BTM_SUCCESS;
675 }
676 
read_phy_cb(base::Callback<void (uint8_t tx_phy,uint8_t rx_phy,uint8_t status)> cb,uint8_t * data,uint16_t len)677 void read_phy_cb(
678     base::Callback<void(uint8_t tx_phy, uint8_t rx_phy, uint8_t status)> cb,
679     uint8_t* data, uint16_t len) {
680   uint8_t status, tx_phy, rx_phy;
681   uint16_t handle;
682 
683   LOG_ASSERT(len == 5) << "Received bad response length: " << len;
684   uint8_t* pp = data;
685   STREAM_TO_UINT8(status, pp);
686   STREAM_TO_UINT16(handle, pp);
687   handle = handle & 0x0FFF;
688   STREAM_TO_UINT8(tx_phy, pp);
689   STREAM_TO_UINT8(rx_phy, pp);
690 
691   DVLOG(1) << __func__ << " Received read_phy_cb";
692   cb.Run(tx_phy, rx_phy, status);
693 }
694 
695 /*******************************************************************************
696  *
697  * Function         BTM_BleReadPhy
698  *
699  * Description      To read the current PHYs for specified LE connection
700  *
701  *
702  * Returns          BTM_SUCCESS if command successfully sent to controller,
703  *                  BTM_MODE_UNSUPPORTED if local controller doesn't support LE
704  *                  2M or LE Coded PHY,
705  *                  BTM_WRONG_MODE if Device in wrong mode for request.
706  *
707  ******************************************************************************/
BTM_BleReadPhy(const RawAddress & bd_addr,base::Callback<void (uint8_t tx_phy,uint8_t rx_phy,uint8_t status)> cb)708 void BTM_BleReadPhy(
709     const RawAddress& bd_addr,
710     base::Callback<void(uint8_t tx_phy, uint8_t rx_phy, uint8_t status)> cb) {
711   BTM_TRACE_DEBUG("%s", __func__);
712 
713   if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
714     BTM_TRACE_ERROR("%s: Wrong mode: no LE link exist or LE not supported",
715                     __func__);
716     cb.Run(0, 0, HCI_ERR_NO_CONNECTION);
717     return;
718   }
719 
720   // checking if local controller supports it!
721   if (!controller_get_interface()->supports_ble_2m_phy() &&
722       !controller_get_interface()->supports_ble_coded_phy()) {
723     BTM_TRACE_ERROR("%s failed, request not supported in local controller!",
724                     __func__);
725     cb.Run(0, 0, GATT_REQ_NOT_SUPPORTED);
726     return;
727   }
728 
729   uint16_t handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
730 
731   const uint8_t len = HCIC_PARAM_SIZE_BLE_READ_PHY;
732   uint8_t data[len];
733   uint8_t* pp = data;
734   UINT16_TO_STREAM(pp, handle);
735   btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_READ_PHY, data, len,
736                             base::Bind(&read_phy_cb, std::move(cb)));
737   return;
738 }
739 
doNothing(uint8_t * data,uint16_t len)740 void doNothing(uint8_t* data, uint16_t len) {}
741 
BTM_BleSetPhy(const RawAddress & bd_addr,uint8_t tx_phys,uint8_t rx_phys,uint16_t phy_options)742 void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys,
743                    uint16_t phy_options) {
744   if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
745     LOG_INFO(
746         "Unable to set phy preferences because no le acl is connected to "
747         "device");
748     return;
749   }
750 
751   uint8_t all_phys = 0;
752   if (tx_phys == 0) all_phys &= 0x01;
753   if (rx_phys == 0) all_phys &= 0x02;
754 
755   uint16_t handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_LE);
756 
757   // checking if local controller supports it!
758   if (!controller_get_interface()->supports_ble_2m_phy() &&
759       !controller_get_interface()->supports_ble_coded_phy()) {
760     LOG_INFO("Local controller unable to support setting of le phy parameters");
761     gatt_notify_phy_updated(GATT_REQ_NOT_SUPPORTED, handle, tx_phys, rx_phys);
762     return;
763   }
764 
765   if (!acl_peer_supports_ble_2m_phy(handle) &&
766       !acl_peer_supports_ble_coded_phy(handle)) {
767     LOG_INFO("Remote device unable to support setting of le phy parameter");
768     gatt_notify_phy_updated(GATT_REQ_NOT_SUPPORTED, handle, tx_phys, rx_phys);
769     return;
770   }
771 
772   const uint8_t len = HCIC_PARAM_SIZE_BLE_SET_PHY;
773   uint8_t data[len];
774   uint8_t* pp = data;
775   UINT16_TO_STREAM(pp, handle);
776   UINT8_TO_STREAM(pp, all_phys);
777   UINT8_TO_STREAM(pp, tx_phys);
778   UINT8_TO_STREAM(pp, rx_phys);
779   UINT16_TO_STREAM(pp, phy_options);
780   btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_SET_PHY, data, len,
781                             base::Bind(doNothing));
782 }
783 
784 /*******************************************************************************
785  *
786  * Function         btm_ble_determine_security_act
787  *
788  * Description      This function checks the security of current LE link
789  *                  and returns the appropriate action that needs to be
790  *                  taken to achieve the required security.
791  *
792  * Parameter        is_originator - True if outgoing connection
793  *                  bdaddr: remote device address
794  *                  security_required: Security required for the service.
795  *
796  * Returns          The appropriate security action required.
797  *
798  ******************************************************************************/
btm_ble_determine_security_act(bool is_originator,const RawAddress & bdaddr,uint16_t security_required)799 tBTM_SEC_ACTION btm_ble_determine_security_act(bool is_originator,
800                                                const RawAddress& bdaddr,
801                                                uint16_t security_required) {
802   tBTM_LE_AUTH_REQ auth_req = 0x00;
803 
804   if (is_originator) {
805     if ((security_required & BTM_SEC_OUT_FLAGS) == 0 &&
806         (security_required & BTM_SEC_OUT_MITM) == 0) {
807       BTM_TRACE_DEBUG("%s No security required for outgoing connection",
808                       __func__);
809       return BTM_SEC_OK;
810     }
811 
812     if (security_required & BTM_SEC_OUT_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM;
813   } else {
814     if ((security_required & BTM_SEC_IN_FLAGS) == 0 &&
815         (security_required & BTM_SEC_IN_MITM) == 0) {
816       BTM_TRACE_DEBUG("%s No security required for incoming connection",
817                       __func__);
818       return BTM_SEC_OK;
819     }
820 
821     if (security_required & BTM_SEC_IN_MITM) auth_req |= BTM_LE_AUTH_REQ_MITM;
822   }
823 
824   tBTM_BLE_SEC_REQ_ACT ble_sec_act = { BTM_BLE_SEC_REQ_ACT_NONE };
825   btm_ble_link_sec_check(bdaddr, auth_req, &ble_sec_act);
826 
827   BTM_TRACE_DEBUG("%s ble_sec_act %d", __func__, ble_sec_act);
828 
829   if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD) return BTM_SEC_ENC_PENDING;
830 
831   if (ble_sec_act == BTM_BLE_SEC_REQ_ACT_NONE) return BTM_SEC_OK;
832 
833   bool is_link_encrypted = BTM_IsEncrypted(bdaddr, BT_TRANSPORT_LE);
834   bool is_key_mitm = BTM_IsLinkKeyAuthed(bdaddr, BT_TRANSPORT_LE);
835 
836   if (auth_req & BTM_LE_AUTH_REQ_MITM) {
837     if (!is_key_mitm) {
838       return BTM_SEC_ENCRYPT_MITM;
839     } else {
840       if (is_link_encrypted)
841         return BTM_SEC_OK;
842       else
843         return BTM_SEC_ENCRYPT;
844     }
845   } else {
846     if (is_link_encrypted)
847       return BTM_SEC_OK;
848     else
849       return BTM_SEC_ENCRYPT_NO_MITM;
850   }
851 
852   return BTM_SEC_OK;
853 }
854 
855 /*******************************************************************************
856  *
857  * Function         btm_ble_start_sec_check
858  *
859  * Description      This function is to check and set the security required for
860  *                  LE link for LE COC.
861  *
862  * Parameter        bdaddr: remote device address.
863  *                  psm : PSM of the LE COC sevice.
864  *                  is_originator: true if outgoing connection.
865  *                  p_callback : Pointer to the callback function.
866  *                  p_ref_data : Pointer to be returned along with the callback.
867  *
868  * Returns          Returns  - L2CAP LE Connection Response Result Code.
869  *
870  ******************************************************************************/
btm_ble_start_sec_check(const RawAddress & bd_addr,uint16_t psm,bool is_originator,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)871 tL2CAP_LE_RESULT_CODE btm_ble_start_sec_check(const RawAddress& bd_addr,
872                                               uint16_t psm, bool is_originator,
873                                               tBTM_SEC_CALLBACK* p_callback,
874                                               void* p_ref_data) {
875   /* Find the service record for the PSM */
876   tBTM_SEC_SERV_REC* p_serv_rec = btm_sec_find_first_serv(is_originator, psm);
877 
878   /* If there is no application registered with this PSM do not allow connection
879    */
880   if (!p_serv_rec) {
881     LOG_WARN("PSM: %d no application registered", psm);
882     (*p_callback)(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_MODE_UNSUPPORTED);
883     return L2CAP_LE_RESULT_NO_PSM;
884   }
885 
886   bool is_encrypted = BTM_IsEncrypted(bd_addr, BT_TRANSPORT_LE);
887   bool is_link_key_authed = BTM_IsLinkKeyAuthed(bd_addr, BT_TRANSPORT_LE);
888   bool is_authenticated = BTM_IsAuthenticated(bd_addr, BT_TRANSPORT_LE);
889 
890   if (!is_originator) {
891     if ((p_serv_rec->security_flags & BTM_SEC_IN_ENCRYPT) && !is_encrypted) {
892       LOG_ERROR(
893           "L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP. service "
894           "security_flags=0x%x, ",
895           p_serv_rec->security_flags);
896       return L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP;
897     } else if ((p_serv_rec->security_flags & BTM_SEC_IN_AUTHENTICATE) &&
898                !(is_link_key_authed || is_authenticated)) {
899       LOG_ERROR(
900           "L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION. service "
901           "security_flags=0x%x, ",
902           p_serv_rec->security_flags);
903       return L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION;
904     }
905     /* TODO: When security is required, then must check that the key size of our
906        service is equal or smaller than the incoming connection key size. */
907   }
908 
909   tBTM_SEC_ACTION sec_act = btm_ble_determine_security_act(
910       is_originator, bd_addr, p_serv_rec->security_flags);
911 
912   tBTM_BLE_SEC_ACT ble_sec_act = BTM_BLE_SEC_NONE;
913   tL2CAP_LE_RESULT_CODE result = L2CAP_LE_RESULT_CONN_OK;
914 
915   switch (sec_act) {
916     case BTM_SEC_OK:
917       LOG_DEBUG("Security met");
918       p_callback(&bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_SUCCESS);
919       result = L2CAP_LE_RESULT_CONN_OK;
920       break;
921 
922     case BTM_SEC_ENCRYPT:
923       LOG_DEBUG("Encryption needs to be done");
924       ble_sec_act = BTM_BLE_SEC_ENCRYPT;
925       break;
926 
927     case BTM_SEC_ENCRYPT_MITM:
928       LOG_DEBUG("Pairing with MITM needs to be done");
929       ble_sec_act = BTM_BLE_SEC_ENCRYPT_MITM;
930       break;
931 
932     case BTM_SEC_ENCRYPT_NO_MITM:
933       LOG_DEBUG("Pairing with No MITM needs to be done");
934       ble_sec_act = BTM_BLE_SEC_ENCRYPT_NO_MITM;
935       break;
936 
937     case BTM_SEC_ENC_PENDING:
938       LOG_DEBUG("Ecryption pending");
939       break;
940   }
941 
942   if (ble_sec_act == BTM_BLE_SEC_NONE) {
943     if (bluetooth::common::init_flags::queue_l2cap_coc_while_encrypting_is_enabled()) {
944       if (sec_act != BTM_SEC_ENC_PENDING) {
945         return result;
946       }
947     } else {
948       return result;
949     }
950   } else {
951     l2cble_update_sec_act(bd_addr, sec_act);
952   }
953 
954   BTM_SetEncryption(bd_addr, BT_TRANSPORT_LE, p_callback, p_ref_data,
955                     ble_sec_act);
956 
957   return L2CAP_LE_RESULT_CONN_OK;
958 }
959 
960 /*******************************************************************************
961  *
962  * Function         btm_ble_rand_enc_complete
963  *
964  * Description      This function is the callback functions for HCI_Rand command
965  *                  and HCI_Encrypt command is completed.
966  *                  This message is received from the HCI.
967  *
968  * Returns          void
969  *
970  ******************************************************************************/
btm_ble_rand_enc_complete(uint8_t * p,uint16_t evt_len,uint16_t op_code,tBTM_RAND_ENC_CB * p_enc_cplt_cback)971 void btm_ble_rand_enc_complete(uint8_t* p, uint16_t evt_len,
972                                uint16_t op_code,
973                                tBTM_RAND_ENC_CB* p_enc_cplt_cback) {
974   tBTM_RAND_ENC params;
975   uint8_t* p_dest = params.param_buf;
976 
977   BTM_TRACE_DEBUG("btm_ble_rand_enc_complete");
978 
979   memset(&params, 0, sizeof(tBTM_RAND_ENC));
980 
981   /* If there was a callback address for vcs complete, call it */
982   if (p_enc_cplt_cback && p) {
983 
984     if (evt_len < 1) {
985       goto err_out;
986     }
987 
988     /* Pass paramters to the callback function */
989     STREAM_TO_UINT8(params.status, p); /* command status */
990 
991     if (params.status == HCI_SUCCESS) {
992       params.opcode = op_code;
993 
994       if (op_code == HCI_BLE_RAND)
995         params.param_len = BT_OCTET8_LEN;
996       else
997         params.param_len = OCTET16_LEN;
998 
999       if (evt_len < 1 + params.param_len) {
1000         goto err_out;
1001       }
1002 
1003       /* Fetch return info from HCI event message */
1004       memcpy(p_dest, p, params.param_len);
1005     }
1006     if (p_enc_cplt_cback) /* Call the Encryption complete callback function */
1007       (*p_enc_cplt_cback)(&params);
1008   }
1009 
1010   return;
1011 
1012 err_out:
1013   BTM_TRACE_ERROR("%s malformatted event packet, too short", __func__);
1014 }
1015 
1016 /*******************************************************************************
1017  *
1018  * Function         btm_ble_get_enc_key_type
1019  *
1020  * Description      This function is to increment local sign counter
1021  * Returns         None
1022  *
1023  ******************************************************************************/
btm_ble_increment_sign_ctr(const RawAddress & bd_addr,bool is_local)1024 void btm_ble_increment_sign_ctr(const RawAddress& bd_addr, bool is_local) {
1025   tBTM_SEC_DEV_REC* p_dev_rec;
1026 
1027   BTM_TRACE_DEBUG("btm_ble_increment_sign_ctr is_local=%d", is_local);
1028 
1029   p_dev_rec = btm_find_dev(bd_addr);
1030   if (p_dev_rec != NULL) {
1031     if (is_local)
1032       p_dev_rec->ble.keys.local_counter++;
1033     else
1034       p_dev_rec->ble.keys.counter++;
1035     BTM_TRACE_DEBUG("is_local=%d local sign counter=%d peer sign counter=%d",
1036                     is_local, p_dev_rec->ble.keys.local_counter,
1037                     p_dev_rec->ble.keys.counter);
1038   }
1039 }
1040 
1041 /*******************************************************************************
1042  *
1043  * Function         btm_ble_get_enc_key_type
1044  *
1045  * Description      This function is to get the BLE key type that has been
1046  *                  exchanged betweem the local device and the peer device.
1047  *
1048  * Returns          p_key_type: output parameter to carry the key type value.
1049  *
1050  ******************************************************************************/
btm_ble_get_enc_key_type(const RawAddress & bd_addr,uint8_t * p_key_types)1051 bool btm_ble_get_enc_key_type(const RawAddress& bd_addr, uint8_t* p_key_types) {
1052   tBTM_SEC_DEV_REC* p_dev_rec;
1053 
1054   BTM_TRACE_DEBUG("btm_ble_get_enc_key_type");
1055 
1056   p_dev_rec = btm_find_dev(bd_addr);
1057   if (p_dev_rec != NULL) {
1058     *p_key_types = p_dev_rec->ble.key_type;
1059     return true;
1060   }
1061   return false;
1062 }
1063 
1064 /*******************************************************************************
1065  *
1066  * Function         btm_get_local_div
1067  *
1068  * Description      This function is called to read the local DIV
1069  *
1070  * Returns          TURE - if a valid DIV is availavle
1071  ******************************************************************************/
btm_get_local_div(const RawAddress & bd_addr,uint16_t * p_div)1072 bool btm_get_local_div(const RawAddress& bd_addr, uint16_t* p_div) {
1073   tBTM_SEC_DEV_REC* p_dev_rec;
1074   bool status = false;
1075   VLOG(1) << __func__ << " bd_addr: " << bd_addr;
1076 
1077   *p_div = 0;
1078   p_dev_rec = btm_find_dev(bd_addr);
1079 
1080   if (p_dev_rec && p_dev_rec->ble.keys.div) {
1081     status = true;
1082     *p_div = p_dev_rec->ble.keys.div;
1083   }
1084   BTM_TRACE_DEBUG("btm_get_local_div status=%d (1-OK) DIV=0x%x", status,
1085                   *p_div);
1086   return status;
1087 }
1088 
1089 /*******************************************************************************
1090  *
1091  * Function         btm_sec_save_le_key
1092  *
1093  * Description      This function is called by the SMP to update
1094  *                  an  BLE key.  SMP is internal, whereas all the keys shall
1095  *                  be sent to the application.  The function is also called
1096  *                  when application passes ble key stored in NVRAM to the
1097  *                  btm_sec.
1098  *                  pass_to_application parameter is false in this case.
1099  *
1100  * Returns          void
1101  *
1102  ******************************************************************************/
btm_sec_save_le_key(const RawAddress & bd_addr,tBTM_LE_KEY_TYPE key_type,tBTM_LE_KEY_VALUE * p_keys,bool pass_to_application)1103 void btm_sec_save_le_key(const RawAddress& bd_addr, tBTM_LE_KEY_TYPE key_type,
1104                          tBTM_LE_KEY_VALUE* p_keys, bool pass_to_application) {
1105   tBTM_SEC_DEV_REC* p_rec;
1106   tBTM_LE_EVT_DATA cb_data;
1107 
1108   BTM_TRACE_DEBUG("btm_sec_save_le_key key_type=0x%x pass_to_application=%d",
1109                   key_type, pass_to_application);
1110   /* Store the updated key in the device database */
1111 
1112   VLOG(1) << "bd_addr:" << bd_addr;
1113 
1114   if ((p_rec = btm_find_dev(bd_addr)) != NULL &&
1115       (p_keys || key_type == BTM_LE_KEY_LID)) {
1116     btm_ble_init_pseudo_addr(p_rec, bd_addr);
1117 
1118     switch (key_type) {
1119       case BTM_LE_KEY_PENC:
1120         p_rec->ble.keys.pltk = p_keys->penc_key.ltk;
1121         memcpy(p_rec->ble.keys.rand, p_keys->penc_key.rand, BT_OCTET8_LEN);
1122         p_rec->ble.keys.sec_level = p_keys->penc_key.sec_level;
1123         p_rec->ble.keys.ediv = p_keys->penc_key.ediv;
1124         p_rec->ble.keys.key_size = p_keys->penc_key.key_size;
1125         p_rec->ble.key_type |= BTM_LE_KEY_PENC;
1126         p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN;
1127         if (p_keys->penc_key.sec_level == SMP_SEC_AUTHENTICATED)
1128           p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
1129         else
1130           p_rec->sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
1131         BTM_TRACE_DEBUG(
1132             "BTM_LE_KEY_PENC key_type=0x%x sec_flags=0x%x sec_leve=0x%x",
1133             p_rec->ble.key_type, p_rec->sec_flags, p_rec->ble.keys.sec_level);
1134         break;
1135 
1136       case BTM_LE_KEY_PID:
1137         p_rec->ble.keys.irk = p_keys->pid_key.irk;
1138         p_rec->ble.identity_address_with_type.bda =
1139             p_keys->pid_key.identity_addr;
1140         p_rec->ble.identity_address_with_type.type =
1141             p_keys->pid_key.identity_addr_type;
1142         p_rec->ble.key_type |= BTM_LE_KEY_PID;
1143         BTM_TRACE_DEBUG(
1144             "%s: BTM_LE_KEY_PID key_type=0x%x save peer IRK, change bd_addr=%s "
1145             "to id_addr=%s id_addr_type=0x%x",
1146             __func__, p_rec->ble.key_type,
1147             ADDRESS_TO_LOGGABLE_CSTR(p_rec->bd_addr),
1148             ADDRESS_TO_LOGGABLE_CSTR(p_keys->pid_key.identity_addr),
1149             p_keys->pid_key.identity_addr_type);
1150         /* update device record address as identity address */
1151         p_rec->bd_addr = p_keys->pid_key.identity_addr;
1152         /* combine DUMO device security record if needed */
1153         btm_consolidate_dev(p_rec);
1154         break;
1155 
1156       case BTM_LE_KEY_PCSRK:
1157         p_rec->ble.keys.pcsrk = p_keys->pcsrk_key.csrk;
1158         p_rec->ble.keys.srk_sec_level = p_keys->pcsrk_key.sec_level;
1159         p_rec->ble.keys.counter = p_keys->pcsrk_key.counter;
1160         p_rec->ble.key_type |= BTM_LE_KEY_PCSRK;
1161         p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_KNOWN;
1162         if (p_keys->pcsrk_key.sec_level == SMP_SEC_AUTHENTICATED)
1163           p_rec->sec_flags |= BTM_SEC_LE_LINK_KEY_AUTHED;
1164         else
1165           p_rec->sec_flags &= ~BTM_SEC_LE_LINK_KEY_AUTHED;
1166 
1167         BTM_TRACE_DEBUG(
1168             "BTM_LE_KEY_PCSRK key_type=0x%x sec_flags=0x%x sec_level=0x%x "
1169             "peer_counter=%d",
1170             p_rec->ble.key_type, p_rec->sec_flags,
1171             p_rec->ble.keys.srk_sec_level, p_rec->ble.keys.counter);
1172         break;
1173 
1174       case BTM_LE_KEY_LENC:
1175         p_rec->ble.keys.lltk = p_keys->lenc_key.ltk;
1176         p_rec->ble.keys.div = p_keys->lenc_key.div; /* update DIV */
1177         p_rec->ble.keys.sec_level = p_keys->lenc_key.sec_level;
1178         p_rec->ble.keys.key_size = p_keys->lenc_key.key_size;
1179         p_rec->ble.key_type |= BTM_LE_KEY_LENC;
1180 
1181         BTM_TRACE_DEBUG(
1182             "BTM_LE_KEY_LENC key_type=0x%x DIV=0x%x key_size=0x%x "
1183             "sec_level=0x%x",
1184             p_rec->ble.key_type, p_rec->ble.keys.div, p_rec->ble.keys.key_size,
1185             p_rec->ble.keys.sec_level);
1186         break;
1187 
1188       case BTM_LE_KEY_LCSRK: /* local CSRK has been delivered */
1189         p_rec->ble.keys.lcsrk = p_keys->lcsrk_key.csrk;
1190         p_rec->ble.keys.div = p_keys->lcsrk_key.div; /* update DIV */
1191         p_rec->ble.keys.local_csrk_sec_level = p_keys->lcsrk_key.sec_level;
1192         p_rec->ble.keys.local_counter = p_keys->lcsrk_key.counter;
1193         p_rec->ble.key_type |= BTM_LE_KEY_LCSRK;
1194         BTM_TRACE_DEBUG(
1195             "BTM_LE_KEY_LCSRK key_type=0x%x DIV=0x%x scrk_sec_level=0x%x "
1196             "local_counter=%d",
1197             p_rec->ble.key_type, p_rec->ble.keys.div,
1198             p_rec->ble.keys.local_csrk_sec_level,
1199             p_rec->ble.keys.local_counter);
1200         break;
1201 
1202       case BTM_LE_KEY_LID:
1203         p_rec->ble.key_type |= BTM_LE_KEY_LID;
1204         break;
1205       default:
1206         BTM_TRACE_WARNING("btm_sec_save_le_key (Bad key_type 0x%02x)",
1207                           key_type);
1208         return;
1209     }
1210 
1211     VLOG(1) << "BLE key type 0x" << loghex(key_type)
1212             << " updated for BDA: " << bd_addr << " (btm_sec_save_le_key)";
1213 
1214     /* Notify the application that one of the BLE keys has been updated
1215        If link key is in progress, it will get sent later.*/
1216     if (pass_to_application && btm_cb.api.p_le_callback) {
1217       cb_data.key.p_key_value = p_keys;
1218       cb_data.key.key_type = key_type;
1219 
1220       (*btm_cb.api.p_le_callback)(BTM_LE_KEY_EVT, bd_addr, &cb_data);
1221     }
1222     return;
1223   }
1224 
1225   LOG(WARNING) << "BLE key type 0x" << loghex(key_type)
1226                << " called for Unknown BDA or type: " << bd_addr
1227                << "(btm_sec_save_le_key)";
1228 
1229   if (p_rec) {
1230     BTM_TRACE_DEBUG("sec_flags=0x%x", p_rec->sec_flags);
1231   }
1232 }
1233 
1234 /*******************************************************************************
1235  *
1236  * Function         btm_ble_update_sec_key_size
1237  *
1238  * Description      update the current lin kencryption key size
1239  *
1240  * Returns          void
1241  *
1242  ******************************************************************************/
btm_ble_update_sec_key_size(const RawAddress & bd_addr,uint8_t enc_key_size)1243 void btm_ble_update_sec_key_size(const RawAddress& bd_addr,
1244                                  uint8_t enc_key_size) {
1245   tBTM_SEC_DEV_REC* p_rec;
1246 
1247   BTM_TRACE_DEBUG("btm_ble_update_sec_key_size enc_key_size = %d",
1248                   enc_key_size);
1249 
1250   p_rec = btm_find_dev(bd_addr);
1251   if (p_rec != NULL) {
1252     p_rec->enc_key_size = enc_key_size;
1253   }
1254 }
1255 
1256 /*******************************************************************************
1257  *
1258  * Function         btm_ble_read_sec_key_size
1259  *
1260  * Description      update the current lin kencryption key size
1261  *
1262  * Returns          void
1263  *
1264  ******************************************************************************/
btm_ble_read_sec_key_size(const RawAddress & bd_addr)1265 uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr) {
1266   tBTM_SEC_DEV_REC* p_rec;
1267 
1268   p_rec = btm_find_dev(bd_addr);
1269   if (p_rec != NULL) {
1270     return p_rec->enc_key_size;
1271   } else
1272     return 0;
1273 }
1274 
1275 /*******************************************************************************
1276  *
1277  * Function         btm_ble_link_sec_check
1278  *
1279  * Description      Check BLE link security level match.
1280  *
1281  * Returns          true: check is OK and the *p_sec_req_act contain the action
1282  *
1283  ******************************************************************************/
btm_ble_link_sec_check(const RawAddress & bd_addr,tBTM_LE_AUTH_REQ auth_req,tBTM_BLE_SEC_REQ_ACT * p_sec_req_act)1284 void btm_ble_link_sec_check(const RawAddress& bd_addr,
1285                             tBTM_LE_AUTH_REQ auth_req,
1286                             tBTM_BLE_SEC_REQ_ACT* p_sec_req_act) {
1287   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1288   uint8_t req_sec_level = SMP_SEC_NONE, cur_sec_level = SMP_SEC_NONE;
1289 
1290   BTM_TRACE_DEBUG("btm_ble_link_sec_check auth_req =0x%x", auth_req);
1291 
1292   if (p_dev_rec == NULL) {
1293     BTM_TRACE_ERROR("btm_ble_link_sec_check received for unknown device");
1294     return;
1295   }
1296 
1297   if (p_dev_rec->is_security_state_encrypting() ||
1298       p_dev_rec->sec_state == BTM_SEC_STATE_AUTHENTICATING) {
1299     /* race condition: discard the security request while central is encrypting
1300      * the link */
1301     *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_DISCARD;
1302   } else {
1303     req_sec_level = SMP_SEC_UNAUTHENTICATE;
1304     if (auth_req & BTM_LE_AUTH_REQ_MITM) {
1305       req_sec_level = SMP_SEC_AUTHENTICATED;
1306     }
1307 
1308     BTM_TRACE_DEBUG("dev_rec sec_flags=0x%x", p_dev_rec->sec_flags);
1309 
1310     /* currently encrpted  */
1311     if (p_dev_rec->sec_flags & BTM_SEC_LE_ENCRYPTED) {
1312       if (p_dev_rec->sec_flags & BTM_SEC_LE_AUTHENTICATED)
1313         cur_sec_level = SMP_SEC_AUTHENTICATED;
1314       else
1315         cur_sec_level = SMP_SEC_UNAUTHENTICATE;
1316     } else /* unencrypted link */
1317     {
1318       /* if bonded, get the key security level */
1319       if (p_dev_rec->ble.key_type & BTM_LE_KEY_PENC)
1320         cur_sec_level = p_dev_rec->ble.keys.sec_level;
1321       else
1322         cur_sec_level = SMP_SEC_NONE;
1323     }
1324 
1325     if (cur_sec_level >= req_sec_level) {
1326       /* To avoid re-encryption on an encrypted link for an equal condition
1327        * encryption */
1328       *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_ENCRYPT;
1329     } else {
1330       /* start the pariring process to upgrade the keys*/
1331       *p_sec_req_act = BTM_BLE_SEC_REQ_ACT_PAIR;
1332     }
1333   }
1334 
1335   BTM_TRACE_DEBUG("cur_sec_level=%d req_sec_level=%d sec_req_act=%d",
1336                   cur_sec_level, req_sec_level, *p_sec_req_act);
1337 }
1338 
1339 /*******************************************************************************
1340  *
1341  * Function         btm_ble_set_encryption
1342  *
1343  * Description      This function is called to ensure that LE connection is
1344  *                  encrypted.  Should be called only on an open connection.
1345  *                  Typically only needed for connections that first want to
1346  *                  bring up unencrypted links, then later encrypt them.
1347  *
1348  * Returns          void
1349  *                  the local device ER is copied into er
1350  *
1351  ******************************************************************************/
btm_ble_set_encryption(const RawAddress & bd_addr,tBTM_BLE_SEC_ACT sec_act,uint8_t link_role)1352 tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr,
1353                                    tBTM_BLE_SEC_ACT sec_act,
1354                                    uint8_t link_role) {
1355   tBTM_STATUS cmd = BTM_NO_RESOURCES;
1356   tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1357   tBTM_BLE_SEC_REQ_ACT sec_req_act;
1358   tBTM_LE_AUTH_REQ auth_req;
1359 
1360   if (p_rec == NULL) {
1361     BTM_TRACE_WARNING(
1362         "btm_ble_set_encryption (NULL device record!! sec_act=0x%x", sec_act);
1363     return (BTM_WRONG_MODE);
1364   }
1365 
1366   BTM_TRACE_DEBUG("btm_ble_set_encryption sec_act=0x%x role_central=%d",
1367                   sec_act, p_rec->role_central);
1368 
1369   if (sec_act == BTM_BLE_SEC_ENCRYPT_MITM) {
1370     p_rec->security_required |= BTM_SEC_IN_MITM;
1371   }
1372 
1373   switch (sec_act) {
1374     case BTM_BLE_SEC_ENCRYPT:
1375       if (link_role == HCI_ROLE_CENTRAL) {
1376         /* start link layer encryption using the security info stored */
1377         cmd = btm_ble_start_encrypt(bd_addr, false, NULL);
1378         break;
1379       }
1380       /* if salve role then fall through to call SMP_Pair below which will send
1381          a sec_request to request the central to encrypt the link */
1382       FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1383     case BTM_BLE_SEC_ENCRYPT_NO_MITM:
1384     case BTM_BLE_SEC_ENCRYPT_MITM:
1385       auth_req = (sec_act == BTM_BLE_SEC_ENCRYPT_NO_MITM)
1386                      ? SMP_AUTH_BOND
1387                      : (SMP_AUTH_BOND | SMP_AUTH_YN_BIT);
1388       btm_ble_link_sec_check(bd_addr, auth_req, &sec_req_act);
1389       if (sec_req_act == BTM_BLE_SEC_REQ_ACT_NONE ||
1390           sec_req_act == BTM_BLE_SEC_REQ_ACT_DISCARD) {
1391         BTM_TRACE_DEBUG("%s, no action needed. Ignore", __func__);
1392         cmd = BTM_SUCCESS;
1393         break;
1394       }
1395       if (link_role == HCI_ROLE_CENTRAL) {
1396         if (sec_req_act == BTM_BLE_SEC_REQ_ACT_ENCRYPT) {
1397           cmd = btm_ble_start_encrypt(bd_addr, false, NULL);
1398           break;
1399         }
1400       }
1401 
1402       if (SMP_Pair(bd_addr) == SMP_STARTED) {
1403         cmd = BTM_CMD_STARTED;
1404         p_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
1405       }
1406       break;
1407 
1408     default:
1409       cmd = BTM_WRONG_MODE;
1410       break;
1411   }
1412   return cmd;
1413 }
1414 
1415 /*******************************************************************************
1416  *
1417  * Function         btm_ble_ltk_request
1418  *
1419  * Description      This function is called when encryption request is received
1420  *                  on a peripheral device.
1421  *
1422  *
1423  * Returns          void
1424  *
1425  ******************************************************************************/
btm_ble_ltk_request(uint16_t handle,uint8_t rand[8],uint16_t ediv)1426 void btm_ble_ltk_request(uint16_t handle, uint8_t rand[8], uint16_t ediv) {
1427   tBTM_CB* p_cb = &btm_cb;
1428   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
1429 
1430   BTM_TRACE_DEBUG("btm_ble_ltk_request");
1431 
1432   p_cb->ediv = ediv;
1433 
1434   memcpy(p_cb->enc_rand, rand, BT_OCTET8_LEN);
1435 
1436   if (p_dev_rec != NULL) {
1437     if (!smp_proc_ltk_request(p_dev_rec->bd_addr)) {
1438       btm_ble_ltk_request_reply(p_dev_rec->bd_addr, false, Octet16{0});
1439     }
1440   }
1441 }
1442 
1443 /** This function is called to start LE encryption.
1444  * Returns BTM_SUCCESS if encryption was started successfully
1445  */
btm_ble_start_encrypt(const RawAddress & bda,bool use_stk,Octet16 * p_stk)1446 tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk,
1447                                   Octet16* p_stk) {
1448   tBTM_CB* p_cb = &btm_cb;
1449   tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
1450   BT_OCTET8 dummy_rand = {0};
1451 
1452   BTM_TRACE_DEBUG("btm_ble_start_encrypt");
1453 
1454   if (!p_rec) {
1455     BTM_TRACE_ERROR("Link is not active, can not encrypt!");
1456     return BTM_WRONG_MODE;
1457   }
1458 
1459   if (p_rec->is_security_state_encrypting()) {
1460     BTM_TRACE_WARNING("Link Encryption is active, Busy!");
1461     return BTM_BUSY;
1462   }
1463 
1464   p_cb->enc_handle = p_rec->ble_hci_handle;
1465 
1466   if (use_stk) {
1467     btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, dummy_rand, 0, *p_stk);
1468   } else if (p_rec->ble.key_type & BTM_LE_KEY_PENC) {
1469     btsnd_hcic_ble_start_enc(p_rec->ble_hci_handle, p_rec->ble.keys.rand,
1470                              p_rec->ble.keys.ediv, p_rec->ble.keys.pltk);
1471   } else {
1472     BTM_TRACE_ERROR("No key available to encrypt the link");
1473     return BTM_NO_RESOURCES;
1474   }
1475 
1476   if (p_rec->sec_state == BTM_SEC_STATE_IDLE)
1477     p_rec->sec_state = BTM_SEC_STATE_LE_ENCRYPTING;
1478 
1479   return BTM_CMD_STARTED;
1480 }
1481 
1482 /*******************************************************************************
1483  *
1484  * Function         btm_ble_link_encrypted
1485  *
1486  * Description      This function is called when LE link encrption status is
1487  *                  changed.
1488  *
1489  * Returns          void
1490  *
1491  ******************************************************************************/
btm_ble_link_encrypted(const RawAddress & bd_addr,uint8_t encr_enable)1492 void btm_ble_link_encrypted(const RawAddress& bd_addr, uint8_t encr_enable) {
1493   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1494   bool enc_cback;
1495 
1496   if (!p_dev_rec) {
1497     BTM_TRACE_WARNING(
1498         "btm_ble_link_encrypted (No Device Found!) encr_enable=%d",
1499         encr_enable);
1500     return;
1501   }
1502 
1503   BTM_TRACE_DEBUG("btm_ble_link_encrypted encr_enable=%d", encr_enable);
1504 
1505   enc_cback = p_dev_rec->is_security_state_le_encrypting();
1506 
1507   smp_link_encrypted(bd_addr, encr_enable);
1508 
1509   BTM_TRACE_DEBUG(" p_dev_rec->sec_flags=0x%x", p_dev_rec->sec_flags);
1510 
1511   if (encr_enable && p_dev_rec->enc_key_size == 0)
1512     p_dev_rec->enc_key_size = p_dev_rec->ble.keys.key_size;
1513 
1514   p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1515   if (p_dev_rec->p_callback && enc_cback) {
1516     if (encr_enable)
1517       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_SUCCESS, true);
1518     else if (p_dev_rec->sec_flags & ~BTM_SEC_LE_LINK_KEY_KNOWN) {
1519       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_FAILED_ON_SECURITY, true);
1520     }
1521     /* LTK missing on peripheral */
1522     else if (p_dev_rec->role_central && (p_dev_rec->sec_status == HCI_ERR_KEY_MISSING)) {
1523       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_KEY_MISSING, true);
1524     }
1525     else if (p_dev_rec->role_central)
1526       btm_sec_dev_rec_cback_event(p_dev_rec, BTM_ERR_PROCESSING, true);
1527   }
1528 
1529   if (encr_enable) {
1530     /* Link is encrypted, start EATT */
1531     bluetooth::eatt::EattExtension::GetInstance()->Connect(
1532         p_dev_rec->ble.pseudo_addr);
1533   }
1534 
1535   /* to notify GATT to send data if any request is pending */
1536   gatt_notify_enc_cmpl(p_dev_rec->ble.pseudo_addr);
1537 }
1538 
1539 /*******************************************************************************
1540  *
1541  * Function         btm_ble_ltk_request_reply
1542  *
1543  * Description      This function is called to send a LTK request reply on a
1544  *                  peripheral
1545  *                  device.
1546  *
1547  * Returns          void
1548  *
1549  ******************************************************************************/
btm_ble_ltk_request_reply(const RawAddress & bda,bool use_stk,const Octet16 & stk)1550 void btm_ble_ltk_request_reply(const RawAddress& bda, bool use_stk,
1551                                const Octet16& stk) {
1552   tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bda);
1553   tBTM_CB* p_cb = &btm_cb;
1554 
1555   if (p_rec == NULL) {
1556     BTM_TRACE_ERROR("btm_ble_ltk_request_reply received for unknown device");
1557     return;
1558   }
1559 
1560   BTM_TRACE_DEBUG("btm_ble_ltk_request_reply");
1561   p_cb->enc_handle = p_rec->ble_hci_handle;
1562   p_cb->key_size = p_rec->ble.keys.key_size;
1563 
1564   BTM_TRACE_ERROR("key size = %d", p_rec->ble.keys.key_size);
1565   if (use_stk) {
1566     btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, stk);
1567     return;
1568   }
1569   /* calculate LTK using peer device  */
1570   if (p_rec->ble.key_type & BTM_LE_KEY_LENC) {
1571     btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, p_rec->ble.keys.lltk);
1572     return;
1573   }
1574 
1575   p_rec = btm_find_dev_with_lenc(bda);
1576   if (!p_rec) {
1577     btsnd_hcic_ble_ltk_req_neg_reply(btm_cb.enc_handle);
1578     return;
1579   }
1580 
1581   LOG_INFO("Found second sec_dev_rec for device that have LTK");
1582   /* This can happen when remote established LE connection using RPA to this
1583    * device, but then pair with us using Classing transport while still keeping
1584    * LE connection. If remote attempts to encrypt the LE connection, we might
1585    * end up here. We will eventually consolidate both entries, this is to avoid
1586    * race conditions. */
1587 
1588   LOG_ASSERT(p_rec->ble.key_type & BTM_LE_KEY_LENC);
1589   p_cb->key_size = p_rec->ble.keys.key_size;
1590   btsnd_hcic_ble_ltk_req_reply(btm_cb.enc_handle, p_rec->ble.keys.lltk);
1591 }
1592 
1593 /*******************************************************************************
1594  *
1595  * Function         btm_ble_io_capabilities_req
1596  *
1597  * Description      This function is called to handle SMP get IO capability
1598  *                  request.
1599  *
1600  * Returns          void
1601  *
1602  ******************************************************************************/
btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC * p_dev_rec,tBTM_LE_IO_REQ * p_data)1603 uint8_t btm_ble_io_capabilities_req(tBTM_SEC_DEV_REC* p_dev_rec,
1604                                     tBTM_LE_IO_REQ* p_data) {
1605   uint8_t callback_rc = BTM_SUCCESS;
1606   BTM_TRACE_DEBUG("btm_ble_io_capabilities_req");
1607   if (btm_cb.api.p_le_callback) {
1608     /* the callback function implementation may change the IO capability... */
1609     callback_rc = (*btm_cb.api.p_le_callback)(
1610         BTM_LE_IO_REQ_EVT, p_dev_rec->bd_addr, (tBTM_LE_EVT_DATA*)p_data);
1611   }
1612   if ((callback_rc == BTM_SUCCESS) || (BTM_OOB_UNKNOWN != p_data->oob_data)) {
1613 #if (BTM_BLE_CONFORMANCE_TESTING == TRUE)
1614     if (btm_cb.devcb.keep_rfu_in_auth_req) {
1615       BTM_TRACE_DEBUG("btm_ble_io_capabilities_req keep_rfu_in_auth_req = %u",
1616                       btm_cb.devcb.keep_rfu_in_auth_req);
1617       p_data->auth_req &= BTM_LE_AUTH_REQ_MASK_KEEP_RFU;
1618       btm_cb.devcb.keep_rfu_in_auth_req = false;
1619     } else { /* default */
1620       p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
1621     }
1622 #else
1623     p_data->auth_req &= BTM_LE_AUTH_REQ_MASK;
1624 #endif
1625 
1626     BTM_TRACE_DEBUG(
1627         "btm_ble_io_capabilities_req 1: p_dev_rec->security_required = %d "
1628         "auth_req:%d",
1629         p_dev_rec->security_required, p_data->auth_req);
1630     BTM_TRACE_DEBUG(
1631         "btm_ble_io_capabilities_req 2: i_keys=0x%x r_keys=0x%x (bit 0-LTK "
1632         "1-IRK 2-CSRK)",
1633         p_data->init_keys, p_data->resp_keys);
1634 
1635     /* if authentication requires MITM protection, put on the mask */
1636     if (p_dev_rec->security_required & BTM_SEC_IN_MITM)
1637       p_data->auth_req |= BTM_LE_AUTH_REQ_MITM;
1638 
1639     if (!(p_data->auth_req & SMP_AUTH_BOND)) {
1640       BTM_TRACE_DEBUG("Non bonding: No keys should be exchanged");
1641       p_data->init_keys = 0;
1642       p_data->resp_keys = 0;
1643     }
1644 
1645     BTM_TRACE_DEBUG("btm_ble_io_capabilities_req 3: auth_req:%d",
1646                     p_data->auth_req);
1647     BTM_TRACE_DEBUG("btm_ble_io_capabilities_req 4: i_keys=0x%x r_keys=0x%x",
1648                     p_data->init_keys, p_data->resp_keys);
1649 
1650     BTM_TRACE_DEBUG(
1651         "btm_ble_io_capabilities_req 5: p_data->io_cap = %d auth_req:%d",
1652         p_data->io_cap, p_data->auth_req);
1653 
1654     /* remove MITM protection requirement if IO cap does not allow it */
1655     if ((p_data->io_cap == BTM_IO_CAP_NONE) && p_data->oob_data == SMP_OOB_NONE)
1656       p_data->auth_req &= ~BTM_LE_AUTH_REQ_MITM;
1657 
1658     if (!(p_data->auth_req & SMP_SC_SUPPORT_BIT)) {
1659       /* if Secure Connections are not supported then remove LK derivation,
1660       ** and keypress notifications.
1661       */
1662       BTM_TRACE_DEBUG(
1663           "%s-SC not supported -> No LK derivation, no keypress notifications",
1664           __func__);
1665       p_data->auth_req &= ~SMP_KP_SUPPORT_BIT;
1666       p_data->init_keys &= ~SMP_SEC_KEY_TYPE_LK;
1667       p_data->resp_keys &= ~SMP_SEC_KEY_TYPE_LK;
1668     }
1669 
1670     BTM_TRACE_DEBUG(
1671         "btm_ble_io_capabilities_req 6: IO_CAP:%d oob_data:%d auth_req:0x%02x",
1672         p_data->io_cap, p_data->oob_data, p_data->auth_req);
1673   }
1674   return callback_rc;
1675 }
1676 
1677 /*******************************************************************************
1678  *
1679  * Function         btm_ble_br_keys_req
1680  *
1681  * Description      This function is called to handle SMP request for keys sent
1682  *                  over BR/EDR.
1683  *
1684  * Returns          void
1685  *
1686  ******************************************************************************/
btm_ble_br_keys_req(tBTM_SEC_DEV_REC * p_dev_rec,tBTM_LE_IO_REQ * p_data)1687 uint8_t btm_ble_br_keys_req(tBTM_SEC_DEV_REC* p_dev_rec,
1688                             tBTM_LE_IO_REQ* p_data) {
1689   uint8_t callback_rc = BTM_SUCCESS;
1690   BTM_TRACE_DEBUG("%s", __func__);
1691   p_data->io_cap =
1692       osi_property_get_int32(kPropertyCtkdIoCapabilities, BTM_IO_CAP_UNKNOWN);
1693   p_data->auth_req = osi_property_get_int32(kPropertyCtkdAuthRequest,
1694                                             BTM_LE_AUTH_REQ_SC_MITM_BOND);
1695   p_data->init_keys = osi_property_get_int32(
1696       kPropertyCtkdInitiatorKeyDistribution, SMP_BR_SEC_DEFAULT_KEY);
1697   p_data->resp_keys = osi_property_get_int32(
1698       kPropertyCtkdResponderKeyDistribution, SMP_BR_SEC_DEFAULT_KEY);
1699   p_data->max_key_size =
1700       osi_property_get_int32(kPropertyCtkdMaxKeySize, BTM_BLE_MAX_KEY_SIZE);
1701   // No OOB data for BR/EDR
1702   p_data->oob_data = false;
1703 
1704   return callback_rc;
1705 }
1706 
1707 /*******************************************************************************
1708  *
1709  * Function         btm_ble_connected
1710  *
1711  * Description      This function is when a LE connection to the peer device is
1712  *                  establsihed
1713  *
1714  * Returns          void
1715  *
1716  ******************************************************************************/
btm_ble_connected(const RawAddress & bda,uint16_t handle,uint8_t enc_mode,uint8_t role,tBLE_ADDR_TYPE addr_type,bool addr_matched,bool can_read_discoverable_characteristics)1717 void btm_ble_connected(const RawAddress& bda, uint16_t handle, uint8_t enc_mode,
1718                        uint8_t role, tBLE_ADDR_TYPE addr_type,
1719                        bool addr_matched,
1720                        bool can_read_discoverable_characteristics) {
1721   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
1722   if (!p_dev_rec) {
1723     LOG_INFO("Creating new device record for new ble connection");
1724     p_dev_rec = btm_sec_alloc_dev(bda);
1725     if (p_dev_rec == nullptr) {
1726       LOG_WARN("Unable to create device record for new ble connection");
1727       return;
1728     }
1729   } else {
1730     LOG_INFO("Updating device record timestamp for existing ble connection");
1731     // TODO() Why is timestamp a counter ?
1732     p_dev_rec->timestamp = btm_cb.dev_rec_count++;
1733   }
1734 
1735   if (is_ble_addr_type_known(addr_type))
1736     p_dev_rec->ble.SetAddressType(addr_type);
1737   else
1738     LOG_WARN(
1739         "Please do not update device record from anonymous le advertisement");
1740 
1741   p_dev_rec->ble.pseudo_addr = bda;
1742   p_dev_rec->ble_hci_handle = handle;
1743   p_dev_rec->device_type |= BT_DEVICE_TYPE_BLE;
1744   p_dev_rec->role_central = (role == HCI_ROLE_CENTRAL) ? true : false;
1745   p_dev_rec->can_read_discoverable = can_read_discoverable_characteristics;
1746 
1747   if (!addr_matched) {
1748     p_dev_rec->ble.active_addr_type = tBTM_SEC_BLE::BTM_BLE_ADDR_PSEUDO;
1749     if (p_dev_rec->ble.AddressType() == BLE_ADDR_RANDOM) {
1750       p_dev_rec->ble.cur_rand_addr = bda;
1751     }
1752   }
1753   btm_cb.ble_ctr_cb.inq_var.directed_conn = BTM_BLE_ADV_IND_EVT;
1754 }
1755 
1756 /*****************************************************************************
1757  *  Function        btm_proc_smp_cback
1758  *
1759  *  Description     This function is the SMP callback handler.
1760  *
1761  *****************************************************************************/
btm_proc_smp_cback(tSMP_EVT event,const RawAddress & bd_addr,const tSMP_EVT_DATA * p_data)1762 tBTM_STATUS btm_proc_smp_cback(tSMP_EVT event, const RawAddress& bd_addr,
1763                                const tSMP_EVT_DATA* p_data) {
1764   BTM_TRACE_DEBUG("btm_proc_smp_cback event = %d", event);
1765 
1766   if (event == SMP_SC_LOC_OOB_DATA_UP_EVT) {
1767     btm_sec_cr_loc_oob_data_cback_event(RawAddress{}, p_data->loc_oob_data);
1768     return BTM_SUCCESS;
1769   }
1770 
1771   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1772   tBTM_STATUS res = BTM_SUCCESS;
1773 
1774   if (p_dev_rec != NULL) {
1775     switch (event) {
1776       case SMP_IO_CAP_REQ_EVT:
1777         btm_ble_io_capabilities_req(p_dev_rec,
1778                                     (tBTM_LE_IO_REQ*)&p_data->io_req);
1779         break;
1780 
1781       case SMP_BR_KEYS_REQ_EVT:
1782         btm_ble_br_keys_req(p_dev_rec, (tBTM_LE_IO_REQ*)&p_data->io_req);
1783         break;
1784 
1785       case SMP_PASSKEY_REQ_EVT:
1786       case SMP_PASSKEY_NOTIF_EVT:
1787       case SMP_OOB_REQ_EVT:
1788       case SMP_NC_REQ_EVT:
1789       case SMP_SC_OOB_REQ_EVT:
1790         p_dev_rec->sec_flags |= BTM_SEC_LE_AUTHENTICATED;
1791         FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1792 
1793       case SMP_CONSENT_REQ_EVT:
1794       case SMP_SEC_REQUEST_EVT:
1795         if (event == SMP_SEC_REQUEST_EVT &&
1796             btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) {
1797           BTM_TRACE_DEBUG("%s: Ignoring SMP Security request", __func__);
1798           break;
1799         }
1800         btm_cb.pairing_bda = bd_addr;
1801         if (event != SMP_CONSENT_REQ_EVT) {
1802           p_dev_rec->sec_state = BTM_SEC_STATE_AUTHENTICATING;
1803         }
1804         btm_cb.pairing_flags |= BTM_PAIR_FLAGS_LE_ACTIVE;
1805         FALLTHROUGH_INTENDED; /* FALLTHROUGH */
1806 
1807       case SMP_COMPLT_EVT:
1808         if (btm_cb.api.p_le_callback) {
1809           /* the callback function implementation may change the IO
1810            * capability... */
1811           BTM_TRACE_DEBUG("btm_cb.api.p_le_callback=0x%x",
1812                           btm_cb.api.p_le_callback);
1813           (*btm_cb.api.p_le_callback)(event, bd_addr,
1814                                       (tBTM_LE_EVT_DATA*)p_data);
1815         }
1816 
1817         if (event == SMP_COMPLT_EVT) {
1818           p_dev_rec = btm_find_dev(bd_addr);
1819           if (p_dev_rec == NULL) {
1820             BTM_TRACE_ERROR("%s: p_dev_rec is NULL", __func__);
1821             return BTM_SUCCESS;
1822           }
1823           BTM_TRACE_DEBUG(
1824               "evt=SMP_COMPLT_EVT before update sec_level=0x%x sec_flags=0x%x",
1825               p_data->cmplt.sec_level, p_dev_rec->sec_flags);
1826 
1827           res = (p_data->cmplt.reason == SMP_SUCCESS) ? BTM_SUCCESS
1828                                                       : BTM_ERR_PROCESSING;
1829 
1830           BTM_TRACE_DEBUG(
1831               "after update result=%d sec_level=0x%x sec_flags=0x%x", res,
1832               p_data->cmplt.sec_level, p_dev_rec->sec_flags);
1833 
1834           if (p_data->cmplt.is_pair_cancel &&
1835               btm_cb.api.p_bond_cancel_cmpl_callback) {
1836             BTM_TRACE_DEBUG("Pairing Cancel completed");
1837             (*btm_cb.api.p_bond_cancel_cmpl_callback)(BTM_SUCCESS);
1838           }
1839 #if (BTM_BLE_CONFORMANCE_TESTING == TRUE)
1840           if (res != BTM_SUCCESS) {
1841             if (!btm_cb.devcb.no_disc_if_pair_fail &&
1842                 p_data->cmplt.reason != SMP_CONN_TOUT) {
1843               BTM_TRACE_DEBUG("Pairing failed - prepare to remove ACL");
1844               l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
1845             } else {
1846               BTM_TRACE_DEBUG("Pairing failed - Not Removing ACL");
1847               p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1848             }
1849           }
1850 #else
1851           if (res != BTM_SUCCESS && p_data->cmplt.reason != SMP_CONN_TOUT) {
1852             BTM_TRACE_DEBUG("Pairing failed - prepare to remove ACL");
1853             l2cu_start_post_bond_timer(p_dev_rec->ble_hci_handle);
1854           }
1855 #endif
1856 
1857           BTM_TRACE_DEBUG(
1858               "btm_cb pairing_state=%x pairing_flags=%x pin_code_len=%x",
1859               btm_cb.pairing_state, btm_cb.pairing_flags, btm_cb.pin_code_len);
1860           VLOG(1) << "btm_cb.pairing_bda: " << btm_cb.pairing_bda;
1861 
1862           /* Reset btm state only if the callback address matches pairing
1863            * address*/
1864           if (bd_addr == btm_cb.pairing_bda) {
1865             btm_cb.pairing_bda = RawAddress::kAny;
1866             btm_cb.pairing_state = BTM_PAIR_STATE_IDLE;
1867             btm_cb.pairing_flags = 0;
1868           }
1869 
1870           if (res == BTM_SUCCESS) {
1871             p_dev_rec->sec_state = BTM_SEC_STATE_IDLE;
1872             /* add all bonded device into resolving list if IRK is available*/
1873             btm_ble_resolving_list_load_dev(*p_dev_rec);
1874           }
1875 
1876           btm_sec_dev_rec_cback_event(p_dev_rec, res, true);
1877         }
1878         break;
1879 
1880       case SMP_LE_ADDR_ASSOC_EVT:
1881         if (btm_cb.api.p_le_callback) {
1882           BTM_TRACE_DEBUG("btm_cb.api.p_le_callback=0x%x",
1883                           btm_cb.api.p_le_callback);
1884           (*btm_cb.api.p_le_callback)(event, bd_addr,
1885                                       (tBTM_LE_EVT_DATA*)p_data);
1886         }
1887         break;
1888 
1889       default:
1890         BTM_TRACE_DEBUG("unknown event = %d", event);
1891         break;
1892     }
1893   } else {
1894     LOG_WARN("Unexpected event '%d' for unknown device.", event);
1895   }
1896 
1897   return BTM_SUCCESS;
1898 }
1899 
1900 /*******************************************************************************
1901  *
1902  * Function         BTM_BleDataSignature
1903  *
1904  * Description      This function is called to sign the data using AES128 CMAC
1905  *                  algorith.
1906  *
1907  * Parameter        bd_addr: target device the data to be signed for.
1908  *                  p_text: singing data
1909  *                  len: length of the data to be signed.
1910  *                  signature: output parameter where data signature is going to
1911  *                             be stored.
1912  *
1913  * Returns          true if signing sucessul, otherwise false.
1914  *
1915  ******************************************************************************/
BTM_BleDataSignature(const RawAddress & bd_addr,uint8_t * p_text,uint16_t len,BLE_SIGNATURE signature)1916 bool BTM_BleDataSignature(const RawAddress& bd_addr, uint8_t* p_text,
1917                           uint16_t len, BLE_SIGNATURE signature) {
1918   tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1919 
1920   BTM_TRACE_DEBUG("%s", __func__);
1921   if (p_rec == NULL) {
1922     BTM_TRACE_ERROR("%s-data signing can not be done from unknown device",
1923                     __func__);
1924     return false;
1925   }
1926 
1927   uint8_t* p_mac = (uint8_t*)signature;
1928   uint8_t* pp;
1929   uint8_t* p_buf = (uint8_t*)osi_malloc(len + 4);
1930 
1931   BTM_TRACE_DEBUG("%s-Start to generate Local CSRK", __func__);
1932   pp = p_buf;
1933   /* prepare plain text */
1934   if (p_text) {
1935     memcpy(p_buf, p_text, len);
1936     pp = (p_buf + len);
1937   }
1938 
1939   UINT32_TO_STREAM(pp, p_rec->ble.keys.local_counter);
1940   UINT32_TO_STREAM(p_mac, p_rec->ble.keys.local_counter);
1941 
1942   crypto_toolbox::aes_cmac(p_rec->ble.keys.lcsrk, p_buf, (uint16_t)(len + 4),
1943                            BTM_CMAC_TLEN_SIZE, p_mac);
1944   btm_ble_increment_sign_ctr(bd_addr, true);
1945 
1946   BTM_TRACE_DEBUG("%s p_mac = %d", __func__, p_mac);
1947   BTM_TRACE_DEBUG(
1948       "p_mac[0] = 0x%02x p_mac[1] = 0x%02x p_mac[2] = 0x%02x p_mac[3] = "
1949       "0x%02x",
1950       *p_mac, *(p_mac + 1), *(p_mac + 2), *(p_mac + 3));
1951   BTM_TRACE_DEBUG(
1952       "p_mac[4] = 0x%02x p_mac[5] = 0x%02x p_mac[6] = 0x%02x p_mac[7] = "
1953       "0x%02x",
1954       *(p_mac + 4), *(p_mac + 5), *(p_mac + 6), *(p_mac + 7));
1955   osi_free(p_buf);
1956   return true;
1957 }
1958 
1959 /*******************************************************************************
1960  *
1961  * Function         BTM_BleVerifySignature
1962  *
1963  * Description      This function is called to verify the data signature
1964  *
1965  * Parameter        bd_addr: target device the data to be signed for.
1966  *                  p_orig:  original data before signature.
1967  *                  len: length of the signing data
1968  *                  counter: counter used when doing data signing
1969  *                  p_comp: signature to be compared against.
1970 
1971  * Returns          true if signature verified correctly; otherwise false.
1972  *
1973  ******************************************************************************/
BTM_BleVerifySignature(const RawAddress & bd_addr,uint8_t * p_orig,uint16_t len,uint32_t counter,uint8_t * p_comp)1974 bool BTM_BleVerifySignature(const RawAddress& bd_addr, uint8_t* p_orig,
1975                             uint16_t len, uint32_t counter, uint8_t* p_comp) {
1976   bool verified = false;
1977   tBTM_SEC_DEV_REC* p_rec = btm_find_dev(bd_addr);
1978   uint8_t p_mac[BTM_CMAC_TLEN_SIZE];
1979 
1980   if (p_rec == NULL || (p_rec && !(p_rec->ble.key_type & BTM_LE_KEY_PCSRK))) {
1981     BTM_TRACE_ERROR("can not verify signature for unknown device");
1982   } else if (counter < p_rec->ble.keys.counter) {
1983     BTM_TRACE_ERROR("signature received with out dated sign counter");
1984   } else if (p_orig == NULL) {
1985     BTM_TRACE_ERROR("No signature to verify");
1986   } else {
1987     BTM_TRACE_DEBUG("%s rcv_cnt=%d >= expected_cnt=%d", __func__, counter,
1988                     p_rec->ble.keys.counter);
1989 
1990     crypto_toolbox::aes_cmac(p_rec->ble.keys.pcsrk, p_orig, len,
1991                              BTM_CMAC_TLEN_SIZE, p_mac);
1992     if (CRYPTO_memcmp(p_mac, p_comp, BTM_CMAC_TLEN_SIZE) == 0) {
1993       btm_ble_increment_sign_ctr(bd_addr, false);
1994       verified = true;
1995     }
1996   }
1997   return verified;
1998 }
1999 
2000 /*******************************************************************************
2001  *  Utility functions for LE device IR/ER generation
2002  ******************************************************************************/
2003 /** This function is to notify application new keys have been generated. */
btm_notify_new_key(uint8_t key_type)2004 static void btm_notify_new_key(uint8_t key_type) {
2005   tBTM_BLE_LOCAL_KEYS* p_local_keys = NULL;
2006 
2007   BTM_TRACE_DEBUG("btm_notify_new_key key_type=%d", key_type);
2008 
2009   if (btm_cb.api.p_le_key_callback) {
2010     switch (key_type) {
2011       case BTM_BLE_KEY_TYPE_ID:
2012         BTM_TRACE_DEBUG("BTM_BLE_KEY_TYPE_ID");
2013         p_local_keys = (tBTM_BLE_LOCAL_KEYS*)&btm_cb.devcb.id_keys;
2014         break;
2015 
2016       case BTM_BLE_KEY_TYPE_ER:
2017         BTM_TRACE_DEBUG("BTM_BLE_KEY_TYPE_ER");
2018         p_local_keys =
2019             (tBTM_BLE_LOCAL_KEYS*)&btm_cb.devcb.ble_encryption_key_value;
2020         break;
2021 
2022       default:
2023         BTM_TRACE_ERROR("unknown key type: %d", key_type);
2024         break;
2025     }
2026     if (p_local_keys != NULL)
2027       (*btm_cb.api.p_le_key_callback)(key_type, p_local_keys);
2028   }
2029 }
2030 
2031 /** implementation of btm_ble_reset_id */
btm_ble_reset_id_impl(const Octet16 & rand1,const Octet16 & rand2)2032 static void btm_ble_reset_id_impl(const Octet16& rand1, const Octet16& rand2) {
2033   /* Regenerate Identity Root */
2034   btm_cb.devcb.id_keys.ir = rand1;
2035   uint8_t btm_ble_dhk_pt = 0x03;
2036 
2037   /* generate DHK= Eir({0x03, 0x00, 0x00 ...}) */
2038   btm_cb.devcb.id_keys.dhk =
2039       crypto_toolbox::aes_128(btm_cb.devcb.id_keys.ir, &btm_ble_dhk_pt, 1);
2040 
2041   uint8_t btm_ble_irk_pt = 0x01;
2042   /* IRK = D1(IR, 1) */
2043   btm_cb.devcb.id_keys.irk =
2044       crypto_toolbox::aes_128(btm_cb.devcb.id_keys.ir, &btm_ble_irk_pt, 1);
2045 
2046   btm_notify_new_key(BTM_BLE_KEY_TYPE_ID);
2047 
2048   /* if privacy is enabled, new RPA should be calculated */
2049   if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
2050     btm_gen_resolvable_private_addr(base::Bind(&btm_gen_resolve_paddr_low));
2051   }
2052 
2053   /* proceed generate ER */
2054   btm_cb.devcb.ble_encryption_key_value = rand2;
2055   btm_notify_new_key(BTM_BLE_KEY_TYPE_ER);
2056 
2057   /* if privacy is enabled, update the irk and RPA in the LE address manager */
2058   if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
2059     BTM_BleConfigPrivacy(true);
2060   }
2061 }
2062 
2063 struct reset_id_data {
2064   Octet16 rand1;
2065   Octet16 rand2;
2066 };
2067 
2068 /** This function is called to reset LE device identity. */
btm_ble_reset_id(void)2069 void btm_ble_reset_id(void) {
2070   BTM_TRACE_DEBUG("btm_ble_reset_id");
2071 
2072   /* In order to reset identity, we need four random numbers. Make four nested
2073    * calls to generate them first, then proceed to perform the actual reset in
2074    * btm_ble_reset_id_impl. */
2075   btsnd_hcic_ble_rand(base::Bind([](BT_OCTET8 rand) {
2076     reset_id_data tmp;
2077     memcpy(tmp.rand1.data(), rand, BT_OCTET8_LEN);
2078     btsnd_hcic_ble_rand(base::Bind(
2079         [](reset_id_data tmp, BT_OCTET8 rand) {
2080           memcpy(tmp.rand1.data() + 8, rand, BT_OCTET8_LEN);
2081           btsnd_hcic_ble_rand(base::Bind(
2082               [](reset_id_data tmp, BT_OCTET8 rand) {
2083                 memcpy(tmp.rand2.data(), rand, BT_OCTET8_LEN);
2084                 btsnd_hcic_ble_rand(base::Bind(
2085                     [](reset_id_data tmp, BT_OCTET8 rand) {
2086                       memcpy(tmp.rand2.data() + 8, rand, BT_OCTET8_LEN);
2087                       // when all random numbers are ready, do the actual reset.
2088                       btm_ble_reset_id_impl(tmp.rand1, tmp.rand2);
2089                     },
2090                     tmp));
2091               },
2092               tmp));
2093         },
2094         tmp));
2095   }));
2096 }
2097 
2098 /*******************************************************************************
2099  *
2100  * Function         btm_ble_get_acl_remote_addr
2101  *
2102  * Description      This function reads the active remote address used for the
2103  *                  connection.
2104  *
2105  * Returns          success return true, otherwise false.
2106  *
2107  ******************************************************************************/
btm_ble_get_acl_remote_addr(uint16_t hci_handle,RawAddress & conn_addr,tBLE_ADDR_TYPE * p_addr_type)2108 bool btm_ble_get_acl_remote_addr(uint16_t hci_handle, RawAddress& conn_addr,
2109                                  tBLE_ADDR_TYPE* p_addr_type) {
2110   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(hci_handle);
2111   if (p_dev_rec == nullptr) {
2112     LOG_WARN("Unable to find security device record hci_handle:%hu",
2113              hci_handle);
2114     // TODO Release acl resource
2115     return false;
2116   }
2117 
2118   bool st = true;
2119 
2120   switch (p_dev_rec->ble.active_addr_type) {
2121     case tBTM_SEC_BLE::BTM_BLE_ADDR_PSEUDO:
2122       conn_addr = p_dev_rec->bd_addr;
2123       *p_addr_type = p_dev_rec->ble.AddressType();
2124       break;
2125 
2126     case tBTM_SEC_BLE::BTM_BLE_ADDR_RRA:
2127       conn_addr = p_dev_rec->ble.cur_rand_addr;
2128       *p_addr_type = BLE_ADDR_RANDOM;
2129       break;
2130 
2131     case tBTM_SEC_BLE::BTM_BLE_ADDR_STATIC:
2132       conn_addr = p_dev_rec->ble.identity_address_with_type.bda;
2133       *p_addr_type = p_dev_rec->ble.identity_address_with_type.type;
2134       break;
2135 
2136     default:
2137       LOG_WARN("Unable to find record with active address type: %d",
2138                p_dev_rec->ble.active_addr_type);
2139       st = false;
2140       break;
2141   }
2142   return st;
2143 }
2144 
2145 #if BTM_BLE_CONFORMANCE_TESTING == TRUE
2146 /*******************************************************************************
2147  *
2148  * Function         btm_ble_set_no_disc_if_pair_fail
2149  *
2150  * Description      This function indicates whether no disconnect of the ACL
2151  *                  should be used if pairing failed
2152  *
2153  * Returns          void
2154  *
2155  ******************************************************************************/
btm_ble_set_no_disc_if_pair_fail(bool disable_disc)2156 void btm_ble_set_no_disc_if_pair_fail(bool disable_disc) {
2157   BTM_TRACE_DEBUG("btm_ble_set_disc_enable_if_pair_fail disable_disc=%d",
2158                   disable_disc);
2159   btm_cb.devcb.no_disc_if_pair_fail = disable_disc;
2160 }
2161 
2162 /*******************************************************************************
2163  *
2164  * Function         btm_ble_set_test_mac_value
2165  *
2166  * Description      This function set test MAC value
2167  *
2168  * Returns          void
2169  *
2170  ******************************************************************************/
btm_ble_set_test_mac_value(bool enable,uint8_t * p_test_mac_val)2171 void btm_ble_set_test_mac_value(bool enable, uint8_t* p_test_mac_val) {
2172   BTM_TRACE_DEBUG("btm_ble_set_test_mac_value enable=%d", enable);
2173   btm_cb.devcb.enable_test_mac_val = enable;
2174   memcpy(btm_cb.devcb.test_mac, p_test_mac_val, BT_OCTET8_LEN);
2175 }
2176 
2177 /*******************************************************************************
2178  *
2179  * Function         btm_ble_set_test_local_sign_cntr_value
2180  *
2181  * Description      This function set test local sign counter value
2182  *
2183  * Returns          void
2184  *
2185  ******************************************************************************/
btm_ble_set_test_local_sign_cntr_value(bool enable,uint32_t test_local_sign_cntr)2186 void btm_ble_set_test_local_sign_cntr_value(bool enable,
2187                                             uint32_t test_local_sign_cntr) {
2188   BTM_TRACE_DEBUG(
2189       "btm_ble_set_test_local_sign_cntr_value enable=%d local_sign_cntr=%d",
2190       enable, test_local_sign_cntr);
2191   btm_cb.devcb.enable_test_local_sign_cntr = enable;
2192   btm_cb.devcb.test_local_sign_cntr = test_local_sign_cntr;
2193 }
2194 
2195 /*******************************************************************************
2196  *
2197  * Function         btm_ble_set_keep_rfu_in_auth_req
2198  *
2199  * Description      This function indicates if RFU bits have to be kept as is
2200  *                  (by default they have to be set to 0 by the sender).
2201  *
2202  * Returns          void
2203  *
2204  ******************************************************************************/
btm_ble_set_keep_rfu_in_auth_req(bool keep_rfu)2205 void btm_ble_set_keep_rfu_in_auth_req(bool keep_rfu) {
2206   BTM_TRACE_DEBUG("btm_ble_set_keep_rfu_in_auth_req keep_rfus=%d", keep_rfu);
2207   btm_cb.devcb.keep_rfu_in_auth_req = keep_rfu;
2208 }
2209 
2210 #endif /* BTM_BLE_CONFORMANCE_TESTING */
2211