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