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