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