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
232    if ((p_tcb = gatt_find_tcb_by_addr(bd_addr)) != NULL)
233    {
234        if (gatt_get_sec_act(p_tcb) == GATT_SEC_ENC_PENDING)
235        {
236            gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
237
238            count = p_tcb->pending_enc_clcb.count;
239
240            for (; count > 0; count --)
241            {
242                if ((p_buf = (tGATT_PENDING_ENC_CLCB *)GKI_dequeue (&p_tcb->pending_enc_clcb)) != NULL)
243                {
244                    gatt_security_check_start(p_buf->p_clcb);
245                    GKI_freebuf(p_buf);
246                }
247                else
248                    break;
249            }
250        }
251    }
252    else
253    {
254        GATT_TRACE_DEBUG0("notify GATT for encryption completion of unknown device");
255    }
256    return;
257}
258/*******************************************************************************
259**
260** Function         gatt_set_sec_act
261**
262** Description      This function set the sec_act in clcb
263**
264** Returns          none
265**
266*******************************************************************************/
267void gatt_set_sec_act(tGATT_TCB *p_tcb, tGATT_SEC_ACTION sec_act)
268{
269    if (p_tcb)
270    {
271        p_tcb->sec_act = sec_act;
272    }
273}
274/*******************************************************************************
275**
276** Function         gatt_get_sec_act
277**
278** Description      This function get the sec_act in clcb
279**
280** Returns          none
281**
282*******************************************************************************/
283tGATT_SEC_ACTION gatt_get_sec_act(tGATT_TCB *p_tcb)
284{
285    tGATT_SEC_ACTION sec_act = GATT_SEC_NONE;
286    if (p_tcb)
287    {
288        sec_act = p_tcb->sec_act;
289    }
290    return sec_act;
291}
292/*******************************************************************************
293**
294** Function         gatt_determine_sec_act
295**
296** Description      This routine determine the security action based on auth_request and
297**                  current link status
298**
299** Returns          tGATT_SEC_ACTION security action
300**
301*******************************************************************************/
302tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB *p_clcb )
303{
304    tGATT_SEC_ACTION    act = GATT_SEC_OK;
305    UINT8               sec_flag;
306    tGATT_TCB           *p_tcb = p_clcb->p_tcb;
307    tGATT_AUTH_REQ      auth_req = p_clcb->auth_req;
308
309    BOOLEAN             is_link_encrypted= FALSE;
310    BOOLEAN             is_le_link=FALSE;
311    BOOLEAN             is_link_key_known=FALSE;
312    BOOLEAN             is_key_mitm=FALSE;
313    UINT8               key_type;
314    tBTM_BLE_SEC_REQ_ACT    sec_act = BTM_LE_SEC_NONE;
315
316    if (auth_req == GATT_AUTH_REQ_NONE )
317        return act;
318
319    is_le_link = BTM_UseLeLink(p_tcb->peer_bda);
320    BTM_GetSecurityFlags(p_tcb->peer_bda, &sec_flag);
321    btm_ble_link_sec_check(p_tcb->peer_bda, auth_req, &sec_act);
322
323    /* if a encryption is pending, need to wait */
324    if (sec_act == BTM_BLE_SEC_REQ_ACT_DISCARD &&
325        auth_req != GATT_AUTH_REQ_NONE)
326        return GATT_SEC_ENC_PENDING;
327
328    if (sec_flag & BTM_SEC_FLAG_ENCRYPTED)
329    {
330        is_link_encrypted = TRUE;
331        is_link_key_known = TRUE;
332
333        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
334        {
335            is_key_mitm = TRUE;
336        }
337
338    }
339    else if (sec_flag & BTM_SEC_FLAG_LKEY_KNOWN)
340    {
341        is_link_key_known = TRUE;
342        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
343        {
344            is_key_mitm = TRUE;
345        }
346    }
347
348    /* first check link key upgrade required or not */
349    switch (auth_req)
350    {
351        case GATT_AUTH_REQ_MITM:
352        case GATT_AUTH_REQ_SIGNED_MITM:
353            if (!is_key_mitm)
354                act = GATT_SEC_ENCRYPT_MITM;
355            break;
356
357        case GATT_AUTH_REQ_NO_MITM:
358        case GATT_AUTH_REQ_SIGNED_NO_MITM:
359            if (!is_link_key_known)
360                act = GATT_SEC_ENCRYPT_NO_MITM;
361            break;
362        default:
363            break;
364    }
365
366    /* now check link needs to be encrypted or not if the link key upgrade is not required */
367    if (act == GATT_SEC_OK)
368    {
369        if (is_le_link &&
370            (p_clcb->operation == GATTC_OPTYPE_WRITE) &&
371            (p_clcb->op_subtype == GATT_WRITE_NO_RSP))
372        {
373            /* this is a write command request
374               check data signing required or not */
375            if (!is_link_encrypted)
376            {
377                btm_ble_get_enc_key_type(p_tcb->peer_bda, &key_type);
378
379                if ( (key_type & BTM_LE_KEY_LCSRK) &&
380                     ((auth_req == GATT_AUTH_REQ_SIGNED_NO_MITM) ||
381                      (auth_req == GATT_AUTH_REQ_SIGNED_MITM)))
382                {
383                    act = GATT_SEC_SIGN_DATA;
384                }
385                else
386                {
387                    act = GATT_SEC_ENCRYPT;
388                }
389            }
390        }
391        else
392        {
393            if (!is_link_encrypted)
394            {
395                act = GATT_SEC_ENCRYPT;
396            }
397        }
398
399    }
400
401    return  act ;
402
403}
404
405
406
407/*******************************************************************************
408**
409** Function         gatt_get_link_encrypt_status
410**
411** Description      This routine get the encryption status of the specified link
412**
413**
414** Returns          tGATT_STATUS link encryption status
415**
416*******************************************************************************/
417tGATT_STATUS gatt_get_link_encrypt_status(tGATT_TCB *p_tcb)
418{
419    tGATT_STATUS    encrypt_status = GATT_NOT_ENCRYPTED;
420    UINT8           sec_flag=0;
421
422    BTM_GetSecurityFlags(p_tcb->peer_bda, &sec_flag);
423
424    if ((sec_flag & BTM_SEC_FLAG_ENCRYPTED) && (sec_flag & BTM_SEC_FLAG_LKEY_KNOWN))
425    {
426        encrypt_status = GATT_ENCRYPED_NO_MITM;
427        if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
428            encrypt_status = GATT_ENCRYPED_MITM;
429    }
430
431    GATT_TRACE_DEBUG1("gatt_get_link_encrypt_status status=0x%x",encrypt_status);
432    return  encrypt_status ;
433}
434
435
436/*******************************************************************************
437**
438** Function          gatt_convert_sec_action
439**
440** Description      Convert GATT security action enum into equivalent BTM BLE security action enum
441**
442** Returns          BOOLEAN TRUE - conversation is successful
443**
444*******************************************************************************/
445static BOOLEAN gatt_convert_sec_action(tGATT_SEC_ACTION gatt_sec_act, tBTM_BLE_SEC_ACT *p_btm_sec_act )
446{
447    BOOLEAN status = TRUE;
448    switch (gatt_sec_act)
449    {
450        case GATT_SEC_ENCRYPT:
451            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT;
452            break;
453        case GATT_SEC_ENCRYPT_NO_MITM:
454            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT_NO_MITM;
455            break;
456        case GATT_SEC_ENCRYPT_MITM:
457            *p_btm_sec_act = BTM_BLE_SEC_ENCRYPT_MITM;
458            break;
459        default:
460            status = FALSE;
461            break;
462    }
463
464    return status;
465}
466/*******************************************************************************
467**
468** Function         gatt_check_enc_req
469**
470** Description      check link security.
471**
472** Returns          TRUE if encrypted, otherwise FALSE.
473**
474*******************************************************************************/
475BOOLEAN gatt_security_check_start(tGATT_CLCB *p_clcb)
476{
477    tGATT_TCB           *p_tcb = p_clcb->p_tcb;
478    tGATT_SEC_ACTION    gatt_sec_act;
479    tBTM_BLE_SEC_ACT    btm_ble_sec_act;
480    BOOLEAN             status = TRUE;
481    tBTM_STATUS         btm_status;
482    tGATT_SEC_ACTION    sec_act_old =  gatt_get_sec_act(p_tcb);
483
484    gatt_sec_act = gatt_determine_sec_act(p_clcb);
485
486    if (sec_act_old == GATT_SEC_NONE)
487        gatt_set_sec_act(p_tcb, gatt_sec_act);
488
489    switch (gatt_sec_act )
490    {
491        case GATT_SEC_SIGN_DATA:
492            GATT_TRACE_DEBUG0("gatt_security_check_start: Do data signing");
493            gatt_sign_data(p_clcb);
494            break;
495        case GATT_SEC_ENCRYPT:
496        case GATT_SEC_ENCRYPT_NO_MITM:
497        case GATT_SEC_ENCRYPT_MITM:
498            if (sec_act_old < GATT_SEC_ENCRYPT)
499            {
500                GATT_TRACE_DEBUG0("gatt_security_check_start: Encrypt now or key upgreade first");
501                gatt_convert_sec_action(gatt_sec_act, &btm_ble_sec_act);
502                btm_status = BTM_SetEncryption(p_tcb->peer_bda, gatt_enc_cmpl_cback, &btm_ble_sec_act);
503                if ( (btm_status != BTM_SUCCESS) && (btm_status != BTM_CMD_STARTED))
504                {
505                    GATT_TRACE_ERROR1("gatt_security_check_start BTM_SetEncryption failed btm_status=%d", btm_status);
506                    status = FALSE;
507                }
508            }
509            if (status)
510                gatt_add_pending_enc_channel_clcb (p_tcb, p_clcb);
511            break;
512        case GATT_SEC_ENC_PENDING:
513            gatt_add_pending_enc_channel_clcb (p_tcb, p_clcb);
514            /* wait for link encrypotion to finish */
515            break;
516        default:
517            gatt_sec_check_complete(TRUE, p_clcb, gatt_sec_act);
518            break;
519    }
520
521    if (status == FALSE)
522    {
523        gatt_set_sec_act(p_tcb, GATT_SEC_NONE);
524        gatt_set_ch_state(p_tcb, GATT_CH_OPEN);
525    }
526
527    return status;
528}
529
530
531#endif  /* BLE_INCLUDED */
532