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