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