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