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