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 GATT authentication handling functions
22 *
23 ******************************************************************************/
24#include "bt_target.h"
25
26#if BLE_INCLUDED == TRUE
27#include <string.h>
28#include "gki.h"
29
30#include "gatt_int.h"
31#include "gatt_api.h"
32#include "btm_int.h"
33
34/*******************************************************************************
35**
36** Function         gatt_sign_data
37**
38** Description      This function sign the data for write command.
39**
40** Returns          TRUE if encrypted, otherwise FALSE.
41**
42*******************************************************************************/
43static BOOLEAN gatt_sign_data (tGATT_CLCB *p_clcb)
44{
45    tGATT_VALUE         *p_attr = (tGATT_VALUE *)p_clcb->p_attr_buf;
46    UINT8               *p_data = NULL, *p;
47    UINT16              payload_size = p_clcb->p_tcb->payload_size;
48    BOOLEAN             status = FALSE;
49    UINT8                *p_signature;
50
51    /* do not need to mark channel securoty activity for data signing */
52    gatt_set_sec_act(p_clcb->p_tcb, GATT_SEC_OK);
53
54    p_data = (UINT8 *)GKI_getbuf((UINT16)(p_attr->len + 3)); /* 3 = 2 byte handle + opcode */
55
56    if (p_data != NULL)
57    {
58        p = p_data;
59        UINT8_TO_STREAM(p, GATT_SIGN_CMD_WRITE);
60        UINT16_TO_STREAM(p, p_attr->handle);
61        ARRAY_TO_STREAM(p, p_attr->value, p_attr->len);
62
63        /* sign data length should be attribulte value length plus 2B handle + 1B op code */
64        if ((payload_size - GATT_AUTH_SIGN_LEN - 3) < p_attr->len)
65            p_attr->len = payload_size - GATT_AUTH_SIGN_LEN - 3;
66
67        p_signature = p_attr->value + p_attr->len;
68        if (BTM_BleDataSignature(p_clcb->p_tcb->peer_bda,
69                                p_data,
70                                (UINT16)(p_attr->len + 3), /* 3 = 2 byte handle + opcode */
71                                p_signature))
72        {
73            p_attr->len += BTM_BLE_AUTH_SIGN_LEN;
74            gatt_set_ch_state(p_clcb->p_tcb, GATT_CH_OPEN);
75            gatt_act_write(p_clcb, GATT_SEC_SIGN_DATA);
76        }
77        else
78        {
79            gatt_end_operation(p_clcb, GATT_INTERNAL_ERROR, NULL);
80        }
81
82        GKI_freebuf(p_data);
83    }
84
85    return status;
86}
87
88/*******************************************************************************
89**
90** Function         gatt_verify_signature
91**
92** Description      This function start to verify the sign data when receiving
93**                  the data from peer device.
94**
95** Returns
96**
97*******************************************************************************/
98void gatt_verify_signature(tGATT_TCB *p_tcb, BT_HDR *p_buf)
99{
100    UINT16  cmd_len;
101    UINT8   op_code;
102    UINT8   *p, *p_orig = (UINT8 *)(p_buf + 1) + p_buf->offset;
103    UINT32  counter;
104
105    cmd_len = p_buf->len - GATT_AUTH_SIGN_LEN + 4;
106    p =  p_orig + cmd_len - 4;
107    STREAM_TO_UINT32(counter, p);
108
109    if (BTM_BleVerifySignature(p_tcb->peer_bda, p_orig, cmd_len, counter, p))
110    {
111        STREAM_TO_UINT8(op_code, p_orig);
112        gatt_server_handle_client_req (p_tcb, op_code, (UINT16)(p_buf->len - 1), p_orig);
113    }
114    else
115    {
116        /* if this is a bad signature, assume from attacker, ignore it */
117        GATT_TRACE_ERROR0("Signature Verification Failed");
118        gatt_disconnect(p_tcb->peer_bda);
119    }
120
121    return;
122}
123/*******************************************************************************
124**
125** Function         gatt_sec_check_complete
126**
127** Description      security check complete and proceed to data sending action.
128**
129** Returns          void.
130**
131*******************************************************************************/
132void gatt_sec_check_complete(BOOLEAN sec_check_ok, tGATT_CLCB   *p_clcb, UINT8 sec_act)
133{
134    if (GKI_queue_is_empty(&p_clcb->p_tcb->pending_enc_clcb))
135        gatt_set_sec_act(p_clcb->p_tcb, GATT_SEC_NONE);
136
137    if (!sec_check_ok)
138    {
139        gatt_end_operation(p_clcb, GATT_AUTH_FAIL, NULL);
140    }
141    else if (p_clcb->operation == GATTC_OPTYPE_WRITE)
142    {
143        gatt_act_write(p_clcb, sec_act);
144    }
145    else if (p_clcb->operation == GATTC_OPTYPE_READ)
146    {
147        gatt_act_read(p_clcb, p_clcb->counter);
148    }
149}
150/*******************************************************************************
151**
152** Function         gatt_enc_cmpl_cback
153**
154** Description      link encryption complete callback.
155**
156** Returns
157**
158*******************************************************************************/
159void gatt_enc_cmpl_cback(BD_ADDR bd_addr, void *p_ref_data, tBTM_STATUS result)
160{
161    tGATT_TCB   *p_tcb;
162    UINT8       sec_flag;
163    BOOLEAN     status = FALSE;
164    tGATT_PENDING_ENC_CLCB  *p_buf;
165    UINT16       count;
166
167    GATT_TRACE_DEBUG0("gatt_enc_cmpl_cback");
168    if ((p_tcb = gatt_find_tcb_by_addr(bd_addr)) != NULL)
169    {
170        if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING)
171            return;
172
173        if ((p_buf = (tGATT_PENDING_ENC_CLCB *)GKI_dequeue (&p_tcb->pending_enc_clcb)) != NULL)
174        {
175            if (result == BTM_SUCCESS)
176            {
177                if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENCRYPT_MITM )
178                {
179                    BTM_GetSecurityFlags(bd_addr, &sec_flag);
180                    if (sec_flag & sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
181                    {
182                        status = TRUE;
183                    }
184                }
185                else
186                {
187                    status = TRUE;
188                }
189            }
190            gatt_sec_check_complete(status , p_buf->p_clcb, p_tcb->sec_act);
191            GKI_freebuf(p_buf);
192            /* start all other pending operation in queue */
193            count = p_tcb->pending_enc_clcb.count;
194            for (; count > 0; count --)
195            {
196                if ((p_buf = (tGATT_PENDING_ENC_CLCB *)GKI_dequeue (&p_tcb->pending_enc_clcb)) != NULL)
197                {
198                    gatt_security_check_start(p_buf->p_clcb);
199                    GKI_freebuf(p_buf);
200                }
201                else
202                    break;
203            }
204        }
205        else
206        {
207            GATT_TRACE_ERROR0("Unknown operation encryption completed");
208        }
209    }
210    else
211    {
212        GATT_TRACE_ERROR0("enc callback for unknown bd_addr");
213    }
214}
215
216/*******************************************************************************
217**
218** Function         gatt_notify_enc_cmpl
219**
220** Description      link encryption complete notification for all encryption process
221**                  initiated outside GATT.
222**
223** Returns
224**
225*******************************************************************************/
226void gatt_notify_enc_cmpl(BD_ADDR bd_addr)
227{
228    tGATT_TCB   *p_tcb;
229    tGATT_PENDING_ENC_CLCB  *p_buf;
230    UINT16       count;
231    UINT8        i = 0;
232
233    if ((p_tcb = gatt_find_tcb_by_addr(bd_addr)) != NULL)
234    {
235        for (i = 0; i < GATT_MAX_APPS; i++)
236        {
237            if (gatt_cb.cl_rcb[i].in_use && gatt_cb.cl_rcb[i].app_cb.p_enc_cmpl_cb)
238            {
239                (*gatt_cb.cl_rcb[i].app_cb.p_enc_cmpl_cb)(gatt_cb.cl_rcb[i].gatt_if, bd_addr);
240            }
241        }
242
243        if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING)
244        {
245            gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
246
247            count = p_tcb->pending_enc_clcb.count;
248
249            for (; count > 0; count --)
250            {
251                if ((p_buf = (tGATT_PENDING_ENC_CLCB *)GKI_dequeue (&p_tcb->pending_enc_clcb)) != NULL)
252                {
253                    gatt_security_check_start(p_buf->p_clcb);
254                    GKI_freebuf(p_buf);
255                }
256                else
257                    break;
258            }
259        }
260    }
261    else
262    {
263        GATT_TRACE_DEBUG0("notify GATT for encryption completion of unknown device");
264    }
265    return;
266}
267/*******************************************************************************
268**
269** Function         gatt_set_sec_act
270**
271** Description      This function set the sec_act in clcb
272**
273** Returns          none
274**
275*******************************************************************************/
276void gatt_set_sec_act(tGATT_TCB *p_tcb, tGATT_SEC_ACTION sec_act)
277{
278    if (p_tcb)
279    {
280        p_tcb->sec_act = sec_act;
281    }
282}
283/*******************************************************************************
284**
285** Function         gatt_get_sec_act
286**
287** Description      This function get the sec_act in clcb
288**
289** Returns          none
290**
291*******************************************************************************/
292tGATT_SEC_ACTION gatt_get_sec_act(tGATT_TCB *p_tcb)
293{
294    tGATT_SEC_ACTION sec_act = GATT_SEC_NONE;
295    if (p_tcb)
296    {
297        sec_act = p_tcb->sec_act;
298    }
299    return sec_act;
300}
301/*******************************************************************************
302**
303** Function         gatt_determine_sec_act
304**
305** Description      This routine determine the security action based on auth_request and
306**                  current link status
307**
308** Returns          tGATT_SEC_ACTION security action
309**
310*******************************************************************************/
311tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB *p_clcb )
312{
313    tGATT_SEC_ACTION    act = GATT_SEC_OK;
314    UINT8               sec_flag;
315    tGATT_TCB           *p_tcb = p_clcb->p_tcb;
316    tGATT_AUTH_REQ      auth_req = p_clcb->auth_req;
317
318    BOOLEAN             is_link_encrypted= FALSE;
319    BOOLEAN             is_le_link=FALSE;
320    BOOLEAN             is_link_key_known=FALSE;
321    BOOLEAN             is_key_mitm=FALSE;
322    UINT8               key_type;
323    tBTM_BLE_SEC_REQ_ACT    sec_act = BTM_LE_SEC_NONE;
324
325    if (auth_req == GATT_AUTH_REQ_NONE )
326        return act;
327
328    is_le_link = BTM_UseLeLink(p_tcb->peer_bda);
329    BTM_GetSecurityFlags(p_tcb->peer_bda, &sec_flag);
330    btm_ble_link_sec_check(p_tcb->peer_bda, auth_req, &sec_act);
331
332    /* if a encryption is pending, need to wait */
333    if (sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD &&
334        auth_req != GATT_AUTH_REQ_NONE)
335        return GATT_SEC_ENC_PENDING;
336
337    if (sec_flag & BTM_SEC_FLAG_ENCRYPTED)
338    {
339        is_link_encrypted = TRUE;
340        is_link_key_known = TRUE;
341
342        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
343        {
344            is_key_mitm = TRUE;
345        }
346
347    }
348    else if (sec_flag & BTM_SEC_FLAG_LKEY_KNOWN)
349    {
350        is_link_key_known = TRUE;
351        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
352        {
353            is_key_mitm = TRUE;
354        }
355    }
356
357    /* first check link key upgrade required or not */
358    switch (auth_req)
359    {
360        case GATT_AUTH_REQ_MITM:
361        case GATT_AUTH_REQ_SIGNED_MITM:
362            if (!is_key_mitm)
363                act = GATT_SEC_ENCRYPT_MITM;
364            break;
365
366        case GATT_AUTH_REQ_NO_MITM:
367        case GATT_AUTH_REQ_SIGNED_NO_MITM:
368            if (!is_link_key_known)
369                act = GATT_SEC_ENCRYPT_NO_MITM;
370            break;
371        default:
372            break;
373    }
374
375    /* now check link needs to be encrypted or not if the link key upgrade is not required */
376    if (act == GATT_SEC_OK)
377    {
378        if (is_le_link &&
379            (p_clcb->operation == GATTC_OPTYPE_WRITE) &&
380            (p_clcb->op_subtype == GATT_WRITE_NO_RSP))
381        {
382            /* this is a write command request
383               check data signing required or not */
384            if (!is_link_encrypted)
385            {
386                btm_ble_get_enc_key_type(p_tcb->peer_bda, &key_type);
387
388                if ( (key_type & BTM_LE_KEY_LCSRK) &&
389                     ((auth_req == GATT_AUTH_REQ_SIGNED_NO_MITM) ||
390                      (auth_req == GATT_AUTH_REQ_SIGNED_MITM)))
391                {
392                    act = GATT_SEC_SIGN_DATA;
393                }
394                else
395                {
396                    act = GATT_SEC_ENCRYPT;
397                }
398            }
399        }
400        else
401        {
402            if (!is_link_encrypted)
403            {
404                act = GATT_SEC_ENCRYPT;
405            }
406        }
407
408    }
409
410    return  act ;
411
412}
413
414
415
416/*******************************************************************************
417**
418** Function         gatt_get_link_encrypt_status
419**
420** Description      This routine get the encryption status of the specified link
421**
422**
423** Returns          tGATT_STATUS link encryption status
424**
425*******************************************************************************/
426tGATT_STATUS gatt_get_link_encrypt_status(tGATT_TCB *p_tcb)
427{
428    tGATT_STATUS    encrypt_status = GATT_NOT_ENCRYPTED;
429    UINT8           sec_flag=0;
430
431    BTM_GetSecurityFlags(p_tcb->peer_bda, &sec_flag);
432
433    if ((sec_flag & BTM_SEC_FLAG_ENCRYPTED) && (sec_flag & BTM_SEC_FLAG_LKEY_KNOWN))
434    {
435        encrypt_status = GATT_ENCRYPED_NO_MITM;
436        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
437            encrypt_status = GATT_ENCRYPED_MITM;
438    }
439
440    GATT_TRACE_DEBUG1("gatt_get_link_encrypt_status status=0x%x",encrypt_status);
441    return  encrypt_status ;
442}
443
444
445/*******************************************************************************
446**
447** Function          gatt_convert_sec_action
448**
449** Description      Convert GATT security action enum into equivalent BTM BLE security action enum
450**
451** Returns          BOOLEAN TRUE - conversation is successful
452**
453*******************************************************************************/
454static BOOLEAN gatt_convert_sec_action(tGATT_SEC_ACTION gatt_sec_act, tBTM_BLE_SEC_ACT *p_btm_sec_act )
455{
456    BOOLEAN status = TRUE;
457    switch (gatt_sec_act)
458    {
459        case GATT_SEC_ENCRYPT:
460            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT;
461            break;
462        case GATT_SEC_ENCRYPT_NO_MITM:
463            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT_NO_MITM;
464            break;
465        case GATT_SEC_ENCRYPT_MITM:
466            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT_MITM;
467            break;
468        default:
469            status = FALSE;
470            break;
471    }
472
473    return status;
474}
475/*******************************************************************************
476**
477** Function         gatt_check_enc_req
478**
479** Description      check link security.
480**
481** Returns          TRUE if encrypted, otherwise FALSE.
482**
483*******************************************************************************/
484BOOLEAN gatt_security_check_start(tGATT_CLCB *p_clcb)
485{
486    tGATT_TCB           *p_tcb = p_clcb->p_tcb;
487    tGATT_SEC_ACTION    gatt_sec_act;
488    tBTM_BLE_SEC_ACT    btm_ble_sec_act;
489    BOOLEAN             status = TRUE;
490    tBTM_STATUS         btm_status;
491    tGATT_SEC_ACTION    sec_act_old =  gatt_get_sec_act(p_tcb);
492
493    gatt_sec_act = gatt_determine_sec_act(p_clcb);
494
495    if (sec_act_old == GATT_SEC_NONE)
496        gatt_set_sec_act(p_tcb, gatt_sec_act);
497
498    switch (gatt_sec_act )
499    {
500        case GATT_SEC_SIGN_DATA:
501            GATT_TRACE_DEBUG0("gatt_security_check_start: Do data signing");
502            gatt_sign_data(p_clcb);
503            break;
504        case GATT_SEC_ENCRYPT:
505        case GATT_SEC_ENCRYPT_NO_MITM:
506        case GATT_SEC_ENCRYPT_MITM:
507            if (sec_act_old < GATT_SEC_ENCRYPT)
508            {
509                GATT_TRACE_DEBUG0("gatt_security_check_start: Encrypt now or key upgreade first");
510                gatt_convert_sec_action(gatt_sec_act, &btm_ble_sec_act);
511                btm_status = BTM_SetEncryption(p_tcb->peer_bda, gatt_enc_cmpl_cback, &btm_ble_sec_act);
512                if ( (btm_status != BTM_SUCCESS) && (btm_status != BTM_CMD_STARTED))
513                {
514                    GATT_TRACE_ERROR1("gatt_security_check_start BTM_SetEncryption failed btm_status=%d", btm_status);
515                    status = FALSE;
516                }
517            }
518            if (status)
519                gatt_add_pending_enc_channel_clcb (p_tcb, p_clcb);
520            break;
521        case GATT_SEC_ENC_PENDING:
522            gatt_add_pending_enc_channel_clcb (p_tcb, p_clcb);
523            /* wait for link encrypotion to finish */
524            break;
525        default:
526            gatt_sec_check_complete(TRUE, p_clcb, gatt_sec_act);
527            break;
528    }
529
530    if (status == FALSE)
531    {
532        gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
533        gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
534    }
535
536    return status;
537}
538
539
540#endif  /* BLE_INCLUDED */
541