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