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