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 functions for the SMP L2Cap interface
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "smp"
26 
27 #include <bluetooth/log.h>
28 #include <com_android_bluetooth_flags.h>
29 
30 #include "internal_include/bt_target.h"
31 #include "osi/include/allocator.h"
32 #include "smp_int.h"
33 #include "stack/btm/btm_dev.h"
34 #include "stack/include/bt_hdr.h"
35 #include "stack/include/bt_types.h"
36 #include "stack/include/l2c_api.h"
37 #include "stack/include/l2cdefs.h"
38 #include "types/raw_address.h"
39 
40 using namespace bluetooth;
41 
42 static void smp_tx_complete_callback(uint16_t cid, uint16_t num_pkt);
43 
44 static void smp_connect_callback(uint16_t channel, const RawAddress& bd_addr,
45                                  bool connected, uint16_t reason,
46                                  tBT_TRANSPORT transport);
47 static void smp_data_received(uint16_t channel, const RawAddress& bd_addr,
48                               BT_HDR* p_buf);
49 
50 static void smp_br_connect_callback(uint16_t channel, const RawAddress& bd_addr,
51                                     bool connected, uint16_t reason,
52                                     tBT_TRANSPORT transport);
53 static void smp_br_data_received(uint16_t channel, const RawAddress& bd_addr,
54                                  BT_HDR* p_buf);
55 
56 /*******************************************************************************
57  *
58  * Function         smp_l2cap_if_init
59  *
60  * Description      This function is called during the SMP task startup
61  *                  to register interface functions with L2CAP.
62  *
63  ******************************************************************************/
smp_l2cap_if_init(void)64 void smp_l2cap_if_init(void) {
65   tL2CAP_FIXED_CHNL_REG fixed_reg;
66   log::verbose("SMDBG l2c");
67 
68   fixed_reg.pL2CA_FixedConn_Cb = smp_connect_callback;
69   fixed_reg.pL2CA_FixedData_Cb = smp_data_received;
70   fixed_reg.pL2CA_FixedTxComplete_Cb = smp_tx_complete_callback;
71 
72   fixed_reg.pL2CA_FixedCong_Cb =
73       NULL; /* do not handle congestion on this channel */
74   fixed_reg.default_idle_tout =
75       60; /* set 60 seconds timeout, 0xffff default idle timeout */
76 
77   if (!L2CA_RegisterFixedChannel(L2CAP_SMP_CID, &fixed_reg)) {
78     log::error("Unable to register with L2CAP fixed channel profile SMP psm:{}",
79                L2CAP_SMP_CID);
80   }
81 
82   fixed_reg.pL2CA_FixedConn_Cb = smp_br_connect_callback;
83   fixed_reg.pL2CA_FixedData_Cb = smp_br_data_received;
84 
85   if (!L2CA_RegisterFixedChannel(L2CAP_SMP_BR_CID, &fixed_reg)) {
86     log::error(
87         "Unable to register with L2CAP fixed channel profile SMP_BR psm:{}",
88         L2CAP_SMP_BR_CID);
89   }
90 }
91 
92 /*******************************************************************************
93  *
94  * Function         smp_connect_callback
95  *
96  * Description      This callback function is called by L2CAP to indicate that
97  *                  SMP channel is
98  *                      connected (conn = true)/disconnected (conn = false).
99  *
100  ******************************************************************************/
smp_connect_callback(uint16_t,const RawAddress & bd_addr,bool connected,uint16_t,tBT_TRANSPORT transport)101 static void smp_connect_callback(uint16_t /* channel */,
102                                  const RawAddress& bd_addr, bool connected,
103                                  uint16_t /* reason */,
104                                  tBT_TRANSPORT transport) {
105   tSMP_CB* p_cb = &smp_cb;
106   tSMP_INT_DATA int_data;
107 
108   log::debug("bd_addr:{} transport:{}, connected:{}", bd_addr,
109              bt_transport_text(transport), connected);
110 
111   if (bd_addr.IsEmpty()) {
112     log::warn("empty address");
113     return;
114   }
115 
116   if (transport == BT_TRANSPORT_BR_EDR) {
117     log::warn("unexpected transport");
118     return;
119   }
120 
121   if (bd_addr == p_cb->pairing_bda) {
122     log::debug("in pairing process");
123 
124     if (connected) {
125       if (!p_cb->connect_initialized) {
126         p_cb->connect_initialized = true;
127         /* initiating connection established */
128         p_cb->role = L2CA_GetBleConnRole(bd_addr);
129 
130         /* initialize local i/r key to be default keys */
131         p_cb->local_r_key = p_cb->local_i_key = SMP_SEC_DEFAULT_KEY;
132         p_cb->loc_auth_req = p_cb->peer_auth_req = SMP_DEFAULT_AUTH_REQ;
133         p_cb->cb_evt = SMP_IO_CAP_REQ_EVT;
134         smp_sm_event(p_cb, SMP_L2CAP_CONN_EVT, NULL);
135       }
136     } else {
137       /* Disconnected while doing security */
138       smp_sm_event(p_cb, SMP_L2CAP_DISCONN_EVT, &int_data);
139     }
140   }
141 }
142 
143 /*******************************************************************************
144  *
145  * Function         smp_data_received
146  *
147  * Description      This function is called when data is received from L2CAP on
148  *                  SMP channel.
149  *
150  *
151  * Returns          void
152  *
153  ******************************************************************************/
smp_data_received(uint16_t channel,const RawAddress & bd_addr,BT_HDR * p_buf)154 static void smp_data_received(uint16_t channel, const RawAddress& bd_addr,
155                               BT_HDR* p_buf) {
156   tSMP_CB* p_cb = &smp_cb;
157   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
158   uint8_t cmd;
159 
160   if (p_buf->len < 1) {
161     log::warn("packet too short");
162     osi_free(p_buf);
163     return;
164   }
165 
166   STREAM_TO_UINT8(cmd, p);
167 
168   log::verbose("cmd={}[0x{:02x}]",
169                smp_opcode_text(static_cast<tSMP_OPCODE>(cmd)), cmd);
170 
171   /* sanity check */
172   if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) {
173     log::warn("invalid command");
174     osi_free(p_buf);
175     return;
176   }
177 
178   /* reject the pairing request if there is an on-going SMP pairing */
179   if (SMP_OPCODE_PAIRING_REQ == cmd || SMP_OPCODE_SEC_REQ == cmd) {
180     if ((p_cb->state == SMP_STATE_IDLE) &&
181         (p_cb->br_state == SMP_BR_STATE_IDLE) &&
182         !(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) {
183       p_cb->role = L2CA_GetBleConnRole(bd_addr);
184       p_cb->pairing_bda = bd_addr;
185     } else if (bd_addr != p_cb->pairing_bda) {
186       osi_free(p_buf);
187       smp_reject_unexpected_pairing_command(bd_addr);
188       return;
189     }
190     /* else, out of state pairing request/security request received, passed into
191      * SM */
192   }
193 
194   if (bd_addr == p_cb->pairing_bda) {
195     alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS,
196                        smp_rsp_timeout, NULL);
197 
198     smp_log_metrics(p_cb->pairing_bda, false /* incoming */,
199                     p_buf->data + p_buf->offset, p_buf->len,
200                     false /* is_over_br */);
201 
202     if (cmd == SMP_OPCODE_CONFIRM) {
203       log::verbose("peer_auth_req=0x{:02x}, loc_auth_req=0x{:02x}",
204                    p_cb->peer_auth_req, p_cb->loc_auth_req);
205 
206       if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) &&
207           (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) {
208         cmd = SMP_OPCODE_PAIR_COMMITM;
209       }
210     }
211 
212     p_cb->rcvd_cmd_code = cmd;
213     p_cb->rcvd_cmd_len = (uint8_t)p_buf->len;
214     tSMP_INT_DATA smp_int_data;
215     smp_int_data.p_data = p;
216     smp_sm_event(p_cb, static_cast<tSMP_EVENT>(cmd), &smp_int_data);
217   } else {
218     if (!L2CA_RemoveFixedChnl(channel, bd_addr)) {
219       log::error("Unable to remove fixed channel peer:{} cid:{}", bd_addr,
220                  channel);
221     }
222   }
223 
224   osi_free(p_buf);
225 }
226 
227 /*******************************************************************************
228  *
229  * Function         smp_tx_complete_callback
230  *
231  * Description      SMP channel tx complete callback
232  *
233  ******************************************************************************/
smp_tx_complete_callback(uint16_t cid,uint16_t num_pkt)234 static void smp_tx_complete_callback(uint16_t cid, uint16_t num_pkt) {
235   tSMP_CB* p_cb = &smp_cb;
236 
237   if (!com::android::bluetooth::flags::l2cap_tx_complete_cb_info()) {
238     log::verbose("Exit since l2cap_tx_complete_cb_info is disabled");
239     return;
240   }
241 
242   log::verbose("l2cap_tx_complete_cb_info is enabled, continue");
243   if (p_cb->total_tx_unacked >= num_pkt) {
244     p_cb->total_tx_unacked -= num_pkt;
245   } else {
246     log::error("Unexpected complete callback: num_pkt = {}", num_pkt);
247   }
248 
249   if (p_cb->total_tx_unacked == 0 && p_cb->wait_for_authorization_complete) {
250     tSMP_INT_DATA smp_int_data;
251     smp_int_data.status = SMP_SUCCESS;
252     if (cid == L2CAP_SMP_CID) {
253       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
254     } else {
255       smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
256     }
257   }
258 }
259 
260 /*******************************************************************************
261  *
262  * Function         smp_br_connect_callback
263  *
264  * Description      This callback function is called by L2CAP to indicate that
265  *                  SMP BR channel is
266  *                      connected (conn = true)/disconnected (conn = false).
267  *
268  ******************************************************************************/
smp_br_connect_callback(uint16_t,const RawAddress & bd_addr,bool connected,uint16_t,tBT_TRANSPORT transport)269 static void smp_br_connect_callback(uint16_t /* channel */,
270                                     const RawAddress& bd_addr, bool connected,
271                                     uint16_t /* reason */,
272                                     tBT_TRANSPORT transport) {
273   tSMP_CB* p_cb = &smp_cb;
274   tSMP_INT_DATA int_data;
275 
276   if (transport != BT_TRANSPORT_BR_EDR) {
277     log::warn("unexpected transport {}", bt_transport_text(transport));
278     return;
279   }
280 
281   log::info("BDA:{} pairing_bda:{}, connected:{}", bd_addr, p_cb->pairing_bda,
282             connected);
283 
284   if (bd_addr != p_cb->pairing_bda) return;
285 
286   /* Check if we already finished SMP pairing over LE, and are waiting to
287    * check if other side returns some errors. Connection/disconnection on
288    * Classic transport shouldn't impact that.
289    */
290   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
291   if ((smp_get_state() == SMP_STATE_BOND_PENDING ||
292        smp_get_state() == SMP_STATE_IDLE) &&
293       (p_dev_rec && p_dev_rec->sec_rec.is_link_key_known()) &&
294       alarm_is_scheduled(p_cb->delayed_auth_timer_ent)) {
295     /* If we were to not return here, we would reset SMP control block, and
296      * delayed_auth_timer_ent would never be executed. Even though we stored all
297      * keys, stack would consider device as not bonded. It would reappear after
298      * stack restart, when we re-read record from storage. Service discovery
299      * would stay broken.
300      */
301     log::info("Classic event after CTKD on LE transport");
302     return;
303   }
304 
305   if (connected) {
306     if (!p_cb->connect_initialized) {
307       p_cb->connect_initialized = true;
308       /* initialize local i/r key to be default keys */
309       p_cb->local_r_key = p_cb->local_i_key = SMP_BR_SEC_DEFAULT_KEY;
310       p_cb->loc_auth_req = p_cb->peer_auth_req = 0;
311       p_cb->cb_evt = SMP_BR_KEYS_REQ_EVT;
312       smp_br_state_machine_event(p_cb, SMP_BR_L2CAP_CONN_EVT, NULL);
313     }
314   } else {
315     /* Disconnected while doing security */
316     if (p_cb->smp_over_br) {
317       log::debug(
318           "SMP over BR/EDR not supported, terminate the ongoing pairing");
319       smp_br_state_machine_event(p_cb, SMP_BR_L2CAP_DISCONN_EVT, &int_data);
320     } else {
321       log::debug("SMP over BR/EDR not supported, continue the LE pairing");
322     }
323   }
324 }
325 
326 /*******************************************************************************
327  *
328  * Function         smp_br_data_received
329  *
330  * Description      This function is called when data is received from L2CAP on
331  *                  SMP BR channel.
332  *
333  * Returns          void
334  *
335  ******************************************************************************/
smp_br_data_received(uint16_t,const RawAddress & bd_addr,BT_HDR * p_buf)336 static void smp_br_data_received(uint16_t /* channel */,
337                                  const RawAddress& bd_addr, BT_HDR* p_buf) {
338   tSMP_CB* p_cb = &smp_cb;
339   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
340   uint8_t cmd;
341   log::verbose("SMDBG l2c");
342 
343   if (p_buf->len < 1) {
344     log::warn("packet too short");
345     osi_free(p_buf);
346     return;
347   }
348 
349   STREAM_TO_UINT8(cmd, p);
350   log::verbose("cmd={}[0x{:02x}]",
351                smp_opcode_text(static_cast<tSMP_OPCODE>(cmd)), cmd);
352 
353   /* sanity check */
354   if ((SMP_OPCODE_MAX < cmd) || (SMP_OPCODE_MIN > cmd)) {
355     log::warn("invalid command 0x{:02x}", cmd);
356     osi_free(p_buf);
357     return;
358   }
359 
360   /* reject the pairing request if there is an on-going SMP pairing */
361   if (SMP_OPCODE_PAIRING_REQ == cmd) {
362     if ((p_cb->state == SMP_STATE_IDLE) &&
363         (p_cb->br_state == SMP_BR_STATE_IDLE)) {
364       p_cb->role = HCI_ROLE_PERIPHERAL;
365       p_cb->smp_over_br = true;
366       p_cb->pairing_bda = bd_addr;
367     } else if (bd_addr != p_cb->pairing_bda) {
368       osi_free(p_buf);
369       smp_reject_unexpected_pairing_command(bd_addr);
370       return;
371     }
372     /* else, out of state pairing request received, passed into State Machine */
373   }
374 
375   if (bd_addr == p_cb->pairing_bda) {
376     alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS,
377                        smp_rsp_timeout, NULL);
378 
379     smp_log_metrics(p_cb->pairing_bda, false /* incoming */,
380                     p_buf->data + p_buf->offset, p_buf->len,
381                     true /* is_over_br */);
382 
383     p_cb->rcvd_cmd_code = cmd;
384     p_cb->rcvd_cmd_len = (uint8_t)p_buf->len;
385     tSMP_INT_DATA smp_int_data;
386     smp_int_data.p_data = p;
387     smp_br_state_machine_event(p_cb, static_cast<tSMP_EVENT>(cmd),
388                                &smp_int_data);
389   }
390 
391   osi_free(p_buf);
392 }
393