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