• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 utility functions
22  *
23  ******************************************************************************/
24 #define LOG_TAG "smp"
25 
26 #include <bluetooth/log.h>
27 #include <com_android_bluetooth_flags.h>
28 
29 #include <cstdint>
30 #include <cstring>
31 
32 #include "crypto_toolbox/crypto_toolbox.h"
33 #include "hci/controller_interface.h"
34 #include "internal_include/bt_target.h"
35 #include "internal_include/stack_config.h"
36 #include "main/shim/entry.h"
37 #include "main/shim/helpers.h"
38 #include "main/shim/metrics_api.h"
39 #include "metrics/bluetooth_event.h"
40 #include "osi/include/allocator.h"
41 #include "p_256_ecc_pp.h"
42 #include "smp_int.h"
43 #include "stack/btm/btm_ble_sec.h"
44 #include "stack/btm/btm_dev.h"
45 #include "stack/include/acl_api.h"
46 #include "stack/include/bt_hdr.h"
47 #include "stack/include/bt_octets.h"
48 #include "stack/include/bt_types.h"
49 #include "stack/include/btm_ble_api.h"
50 #include "stack/include/btm_ble_sec_api.h"
51 #include "stack/include/btm_log_history.h"
52 #include "stack/include/l2cap_interface.h"
53 #include "stack/include/l2cdefs.h"
54 #include "stack/include/smp_status.h"
55 #include "types/raw_address.h"
56 
57 #define SMP_PAIRING_REQ_SIZE 7
58 #define SMP_CONFIRM_CMD_SIZE (OCTET16_LEN + 1)
59 #define SMP_RAND_CMD_SIZE (OCTET16_LEN + 1)
60 #define SMP_INIT_CMD_SIZE (OCTET16_LEN + 1)
61 #define SMP_ENC_INFO_SIZE (OCTET16_LEN + 1)
62 #define SMP_CENTRAL_ID_SIZE (BT_OCTET8_LEN + 2 + 1)
63 #define SMP_ID_INFO_SIZE (OCTET16_LEN + 1)
64 #define SMP_ID_ADDR_SIZE (BD_ADDR_LEN + 1 + 1)
65 #define SMP_SIGN_INFO_SIZE (OCTET16_LEN + 1)
66 #define SMP_PAIR_FAIL_SIZE 2
67 #define SMP_SECURITY_REQUEST_SIZE 2
68 #define SMP_PAIR_PUBL_KEY_SIZE (1 /* opcode */ + (2 * BT_OCTET32_LEN))
69 #define SMP_PAIR_COMMITM_SIZE (1 /* opcode */ + OCTET16_LEN /*Commitment*/)
70 #define SMP_PAIR_DHKEY_CHECK_SIZE \
71   (1 /* opcode */ + OCTET16_LEN /*DHKey \
72                                                                    Check*/)
73 #define SMP_PAIR_KEYPR_NOTIF_SIZE (1 /* opcode */ + 1 /*Notif Type*/)
74 
75 using namespace bluetooth;
76 
77 namespace {
78 constexpr char kBtmLogTag[] = "SMP";
79 }
80 
81 /* SMP command sizes per spec */
82 static const uint8_t smp_cmd_size_per_spec[] = {
83         0,
84         SMP_PAIRING_REQ_SIZE,      /* 0x01: pairing request */
85         SMP_PAIRING_REQ_SIZE,      /* 0x02: pairing response */
86         SMP_CONFIRM_CMD_SIZE,      /* 0x03: pairing confirm */
87         SMP_RAND_CMD_SIZE,         /* 0x04: pairing random */
88         SMP_PAIR_FAIL_SIZE,        /* 0x05: pairing failed */
89         SMP_ENC_INFO_SIZE,         /* 0x06: encryption information */
90         SMP_CENTRAL_ID_SIZE,       /* 0x07: central identification */
91         SMP_ID_INFO_SIZE,          /* 0x08: identity information */
92         SMP_ID_ADDR_SIZE,          /* 0x09: identity address information */
93         SMP_SIGN_INFO_SIZE,        /* 0x0A: signing information */
94         SMP_SECURITY_REQUEST_SIZE, /* 0x0B: security request */
95         SMP_PAIR_PUBL_KEY_SIZE,    /* 0x0C: pairing public key */
96         SMP_PAIR_DHKEY_CHECK_SIZE, /* 0x0D: pairing dhkey check */
97         SMP_PAIR_KEYPR_NOTIF_SIZE, /* 0x0E: pairing keypress notification */
98         SMP_PAIR_COMMITM_SIZE      /* 0x0F: pairing commitment */
99 };
100 
101 static bool smp_parameter_unconditionally_valid(tSMP_CB* p_cb);
102 static bool smp_parameter_unconditionally_invalid(tSMP_CB* p_cb);
103 
104 /* type for SMP command length validation functions */
105 typedef bool (*tSMP_CMD_LEN_VALID)(tSMP_CB* p_cb);
106 
107 static bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb);
108 
109 static const tSMP_CMD_LEN_VALID smp_cmd_len_is_valid[] = {
110         smp_parameter_unconditionally_invalid,
111         smp_command_has_valid_fixed_length, /* 0x01: pairing request */
112         smp_command_has_valid_fixed_length, /* 0x02: pairing response */
113         smp_command_has_valid_fixed_length, /* 0x03: pairing confirm */
114         smp_command_has_valid_fixed_length, /* 0x04: pairing random */
115         smp_command_has_valid_fixed_length, /* 0x05: pairing failed */
116         smp_command_has_valid_fixed_length, /* 0x06: encryption information */
117         smp_command_has_valid_fixed_length, /* 0x07: central identification */
118         smp_command_has_valid_fixed_length, /* 0x08: identity information */
119         smp_command_has_valid_fixed_length, /* 0x09: identity address information */
120         smp_command_has_valid_fixed_length, /* 0x0A: signing information */
121         smp_command_has_valid_fixed_length, /* 0x0B: security request */
122         smp_command_has_valid_fixed_length, /* 0x0C: pairing public key */
123         smp_command_has_valid_fixed_length, /* 0x0D: pairing dhkey check */
124         smp_command_has_valid_fixed_length, /* 0x0E: pairing keypress notification*/
125         smp_command_has_valid_fixed_length  /* 0x0F: pairing commitment */
126 };
127 
128 /* type for SMP command parameter ranges validation functions */
129 typedef bool (*tSMP_CMD_PARAM_RANGES_VALID)(tSMP_CB* p_cb);
130 
131 static bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb);
132 static bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb);
133 
134 static const tSMP_CMD_PARAM_RANGES_VALID smp_cmd_param_ranges_are_valid[] = {
135         smp_parameter_unconditionally_invalid,
136         smp_pairing_request_response_parameters_are_valid, /* 0x01: pairing
137                                                               request */
138         smp_pairing_request_response_parameters_are_valid, /* 0x02: pairing
139                                                               response */
140         smp_parameter_unconditionally_valid,               /* 0x03: pairing confirm */
141         smp_parameter_unconditionally_valid,               /* 0x04: pairing random */
142         smp_parameter_unconditionally_valid,               /* 0x05: pairing failed */
143         smp_parameter_unconditionally_valid,               /* 0x06: encryption information */
144         smp_parameter_unconditionally_valid,               /* 0x07: central identification */
145         smp_parameter_unconditionally_valid,               /* 0x08: identity information */
146         smp_parameter_unconditionally_valid,               /* 0x09: identity address
147                                                               information */
148         smp_parameter_unconditionally_valid,               /* 0x0A: signing information */
149         smp_parameter_unconditionally_valid,               /* 0x0B: security request */
150         smp_parameter_unconditionally_valid,               /* 0x0C: pairing public key */
151         smp_parameter_unconditionally_valid,               /* 0x0D: pairing dhkey check */
152         smp_pairing_keypress_notification_is_valid,        /* 0x0E: pairing keypress
153                                                               notification */
154         smp_parameter_unconditionally_valid                /* 0x0F: pairing commitment */
155 };
156 
157 /* type for action functions */
158 typedef BT_HDR* (*tSMP_CMD_ACT)(uint8_t cmd_code, tSMP_CB* p_cb);
159 
160 static BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
161 static BT_HDR* smp_build_confirm_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
162 static BT_HDR* smp_build_rand_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
163 static BT_HDR* smp_build_pairing_fail(uint8_t cmd_code, tSMP_CB* p_cb);
164 static BT_HDR* smp_build_identity_info_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
165 static BT_HDR* smp_build_encrypt_info_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
166 static BT_HDR* smp_build_security_request(uint8_t cmd_code, tSMP_CB* p_cb);
167 static BT_HDR* smp_build_signing_info_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
168 static BT_HDR* smp_build_central_id_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
169 static BT_HDR* smp_build_id_addr_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
170 static BT_HDR* smp_build_pair_public_key_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
171 static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
172 static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
173 static BT_HDR* smp_build_pairing_keypress_notification_cmd(uint8_t cmd_code, tSMP_CB* p_cb);
174 
175 static const tSMP_CMD_ACT smp_cmd_build_act[] = {
176         NULL,
177         smp_build_pairing_cmd,                       /* 0x01: pairing request */
178         smp_build_pairing_cmd,                       /* 0x02: pairing response */
179         smp_build_confirm_cmd,                       /* 0x03: pairing confirm */
180         smp_build_rand_cmd,                          /* 0x04: pairing random */
181         smp_build_pairing_fail,                      /* 0x05: pairing failure */
182         smp_build_encrypt_info_cmd,                  /* 0x06: encryption information */
183         smp_build_central_id_cmd,                    /* 0x07: central identification */
184         smp_build_identity_info_cmd,                 /* 0x08: identity information */
185         smp_build_id_addr_cmd,                       /* 0x09: identity address information */
186         smp_build_signing_info_cmd,                  /* 0x0A: signing information */
187         smp_build_security_request,                  /* 0x0B: security request */
188         smp_build_pair_public_key_cmd,               /* 0x0C: pairing public key */
189         smp_build_pair_dhkey_check_cmd,              /* 0x0D: pairing DHKey check */
190         smp_build_pairing_keypress_notification_cmd, /* 0x0E: pairing keypress
191                                                         notification */
192         smp_build_pairing_commitment_cmd             /* 0x0F: pairing commitment */
193 };
194 
195 static const tSMP_ASSO_MODEL smp_association_table[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = {
196         /* display only */ /* Display Yes/No */ /* keyboard only */
197         /* No Input/Output */                   /* keyboard display */
198 
199         /* initiator */
200         /* model = tbl[peer_io_caps][loc_io_caps] */
201         /* Display Only */
202         {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY,
203           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY},
204 
205          /* Display Yes/No */
206          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY,
207           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_PASSKEY},
208 
209          /* Keyboard only */
210          {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY,
211           SMP_MODEL_KEY_NOTIF},
212 
213          /* No Input No Output */
214          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
215           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY},
216 
217          /* keyboard display */
218          {SMP_MODEL_KEY_NOTIF, SMP_MODEL_KEY_NOTIF, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY,
219           SMP_MODEL_KEY_NOTIF}},
220 
221         /* responder */
222         /* model = tbl[loc_io_caps][peer_io_caps] */
223         /* Display Only */
224         {{SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF,
225           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF},
226 
227          /* Display Yes/No */
228          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF,
229           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_KEY_NOTIF},
230 
231          /* keyboard only */
232          {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_ENCRYPTION_ONLY,
233           SMP_MODEL_PASSKEY},
234 
235          /* No Input No Output */
236          {SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY,
237           SMP_MODEL_ENCRYPTION_ONLY, SMP_MODEL_ENCRYPTION_ONLY},
238 
239          /* keyboard display */
240          {SMP_MODEL_PASSKEY, SMP_MODEL_PASSKEY, SMP_MODEL_KEY_NOTIF, SMP_MODEL_ENCRYPTION_ONLY,
241           SMP_MODEL_PASSKEY}}};
242 
243 static const tSMP_ASSO_MODEL smp_association_table_sc[2][SMP_IO_CAP_MAX][SMP_IO_CAP_MAX] = {
244         /* display only */ /* Display Yes/No */ /* keyboard only */
245         /* No InputOutput */                    /* keyboard display */
246 
247         /* initiator */
248         /* model = tbl[peer_io_caps][loc_io_caps] */
249 
250         /* Display Only */
251         {{SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
252           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
253           SMP_MODEL_SEC_CONN_PASSKEY_ENT},
254 
255          /* Display Yes/No */
256          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP, SMP_MODEL_SEC_CONN_PASSKEY_ENT,
257           SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP},
258 
259          /* keyboard only */
260          {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_PASSKEY_DISP,
261           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
262           SMP_MODEL_SEC_CONN_PASSKEY_DISP},
263 
264          /* No Input No Output */
265          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
266           SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS},
267 
268          /* keyboard display */
269          {SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_NUM_COMP,
270           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
271           SMP_MODEL_SEC_CONN_NUM_COMP}},
272 
273         /* responder */
274         /* model = tbl[loc_io_caps][peer_io_caps] */
275 
276         /* Display Only */
277         {{SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
278           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
279           SMP_MODEL_SEC_CONN_PASSKEY_DISP},
280 
281          /* Display Yes/No */
282          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_NUM_COMP,
283           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
284           SMP_MODEL_SEC_CONN_NUM_COMP},
285 
286          /* keyboard only */
287          {SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_PASSKEY_ENT,
288           SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_JUSTWORKS,
289           SMP_MODEL_SEC_CONN_PASSKEY_ENT},
290 
291          /* No Input No Output */
292          {SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS,
293           SMP_MODEL_SEC_CONN_JUSTWORKS, SMP_MODEL_SEC_CONN_JUSTWORKS},
294 
295          /* keyboard display */
296          {SMP_MODEL_SEC_CONN_PASSKEY_ENT, SMP_MODEL_SEC_CONN_NUM_COMP,
297           SMP_MODEL_SEC_CONN_PASSKEY_DISP, SMP_MODEL_SEC_CONN_JUSTWORKS,
298           SMP_MODEL_SEC_CONN_NUM_COMP}}};
299 
300 static tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb);
301 static tSMP_ASSO_MODEL smp_select_association_model_secure_connections(tSMP_CB* p_cb);
302 
303 /**
304  * Log metrics data for SMP command
305  *
306  * @param bd_addr current pairing address
307  * @param is_outgoing whether this command is outgoing
308  * @param p_buf buffer to the beginning of SMP command
309  * @param buf_len length available to read for p_buf
310  */
smp_log_metrics(const RawAddress & bd_addr,bool is_outgoing,const uint8_t * p_buf,size_t buf_len,bool is_over_br)311 void smp_log_metrics(const RawAddress& bd_addr, bool is_outgoing, const uint8_t* p_buf,
312                      size_t buf_len, bool is_over_br) {
313   if (buf_len < 1) {
314     log::warn("buffer is too small");
315     return;
316   }
317   uint8_t raw_cmd;
318   STREAM_TO_UINT8(raw_cmd, p_buf);
319   buf_len--;
320   uint8_t failure_reason = 0;
321   if (raw_cmd == SMP_OPCODE_PAIRING_FAILED && buf_len >= 1) {
322     STREAM_TO_UINT8(failure_reason, p_buf);
323     bluetooth::shim::LogMetricLePairingFail(bd_addr, failure_reason, is_outgoing);
324   }
325   if (smp_cb.is_pair_cancel) {
326     failure_reason = SMP_USER_CANCELLED;  // Tracking pairing cancellations
327   }
328   uint16_t metric_cmd = is_over_br ? SMP_METRIC_COMMAND_BR_FLAG : SMP_METRIC_COMMAND_LE_FLAG;
329   metric_cmd |= static_cast<uint16_t>(raw_cmd);
330   android::bluetooth::DirectionEnum direction =
331           is_outgoing ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING
332                       : android::bluetooth::DirectionEnum::DIRECTION_INCOMING;
333   bluetooth::shim::LogMetricSmpPairingEvent(bd_addr, metric_cmd, direction,
334                                             static_cast<uint16_t>(failure_reason));
335 }
336 
337 /*******************************************************************************
338  *
339  * Function         smp_send_msg_to_L2CAP
340  *
341  * Description      Send message to L2CAP.
342  *
343  ******************************************************************************/
smp_send_msg_to_L2CAP(const RawAddress & rem_bda,BT_HDR * p_toL2CAP)344 static bool smp_send_msg_to_L2CAP(const RawAddress& rem_bda, BT_HDR* p_toL2CAP) {
345   tL2CAP_DW_RESULT l2cap_ret;
346   uint16_t fixed_cid = L2CAP_SMP_CID;
347 
348   if (smp_cb.smp_over_br) {
349     fixed_cid = L2CAP_SMP_BR_CID;
350   }
351 
352   log::verbose("rem_bda:{}, over_bredr:{}", rem_bda, smp_cb.smp_over_br);
353 
354   smp_log_metrics(rem_bda, true /* outgoing */, p_toL2CAP->data + p_toL2CAP->offset, p_toL2CAP->len,
355                   smp_cb.smp_over_br /* is_over_br */);
356 
357   if (com::android::bluetooth::flags::l2cap_tx_complete_cb_info()) {
358     /* Unacked needs to be incremented before calling SendFixedChnlData */
359     smp_cb.total_tx_unacked++;
360     l2cap_ret = stack::l2cap::get_interface().L2CA_SendFixedChnlData(fixed_cid, rem_bda, p_toL2CAP);
361     if (l2cap_ret == tL2CAP_DW_RESULT::FAILED) {
362       smp_cb.total_tx_unacked--;
363       log::error("SMP failed to pass msg to L2CAP");
364       return false;
365     }
366     log::verbose("l2cap_tx_complete_cb_info is enabled");
367     return true;
368   }
369 
370   l2cap_ret = stack::l2cap::get_interface().L2CA_SendFixedChnlData(fixed_cid, rem_bda, p_toL2CAP);
371   if (l2cap_ret == tL2CAP_DW_RESULT::FAILED) {
372     log::error("SMP failed to pass msg to L2CAP");
373     return false;
374   } else {
375     tSMP_CB* p_cb = &smp_cb;
376 
377     log::verbose("l2cap_tx_complete_cb_info is disabled");
378     if (p_cb->wait_for_authorization_complete) {
379       tSMP_INT_DATA smp_int_data;
380       smp_int_data.status = SMP_SUCCESS;
381       if (fixed_cid == L2CAP_SMP_CID) {
382         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
383       } else {
384         smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
385       }
386     }
387     return true;
388   }
389 }
390 
391 /*******************************************************************************
392  *
393  * Function         smp_send_cmd
394  *
395  * Description      send a SMP command on L2CAP channel.
396  *
397  ******************************************************************************/
smp_send_cmd(uint8_t cmd_code,tSMP_CB * p_cb)398 bool smp_send_cmd(uint8_t cmd_code, tSMP_CB* p_cb) {
399   BT_HDR* p_buf;
400   bool sent = false;
401 
402   log::debug("Sending SMP command:{}[0x{:x}] pairing_bda={}",
403              smp_opcode_text(static_cast<tSMP_OPCODE>(cmd_code)), cmd_code, p_cb->pairing_bda);
404 
405   if (cmd_code <= (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */) &&
406       smp_cmd_build_act[cmd_code] != NULL) {
407     p_buf = (*smp_cmd_build_act[cmd_code])(cmd_code, p_cb);
408 
409     if (p_buf != NULL && smp_send_msg_to_L2CAP(p_cb->pairing_bda, p_buf)) {
410       sent = true;
411       alarm_set_on_mloop(p_cb->smp_rsp_timer_ent, SMP_WAIT_FOR_RSP_TIMEOUT_MS, smp_rsp_timeout,
412                          NULL);
413     }
414   }
415 
416   if (!sent) {
417     tSMP_INT_DATA smp_int_data;
418     smp_int_data.status = SMP_PAIR_INTERNAL_ERR;
419     if (p_cb->smp_over_br) {
420       smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
421     } else {
422       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
423     }
424   }
425   return sent;
426 }
427 
428 /*******************************************************************************
429  *
430  * Function         smp_rsp_timeout
431  *
432  * Description      Called when SMP wait for SMP command response timer expires
433  *
434  * Returns          void
435  *
436  ******************************************************************************/
smp_rsp_timeout(void *)437 void smp_rsp_timeout(void* /* data */) {
438   tSMP_CB* p_cb = &smp_cb;
439 
440   log::verbose("state:{} br_state:{}", p_cb->state, p_cb->br_state);
441 
442   tSMP_INT_DATA smp_int_data;
443   smp_int_data.status = SMP_RSP_TIMEOUT;
444   if (p_cb->smp_over_br) {
445     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
446   } else {
447     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
448   }
449 }
450 
451 /*******************************************************************************
452  *
453  * Function         smp_delayed_auth_complete_timeout
454  *
455  * Description      Called when no pairing failed command received within
456  *                  timeout period.
457  *
458  * Returns          void
459  *
460  ******************************************************************************/
smp_delayed_auth_complete_timeout(void *)461 void smp_delayed_auth_complete_timeout(void* /* data */) {
462   /*
463    * Waited for potential pair failure. Send SMP_AUTH_CMPL_EVT if
464    * the state is still in bond pending.
465    */
466   if (smp_get_state() == SMP_STATE_BOND_PENDING) {
467     log::verbose("sending delayed auth complete.");
468     tSMP_INT_DATA smp_int_data;
469     smp_int_data.status = SMP_SUCCESS;
470     smp_sm_event(&smp_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
471   }
472 }
473 
474 /*******************************************************************************
475  *
476  * Function         smp_build_pairing_req_cmd
477  *
478  * Description      Build pairing request command.
479  *
480  ******************************************************************************/
smp_build_pairing_cmd(uint8_t cmd_code,tSMP_CB * p_cb)481 BT_HDR* smp_build_pairing_cmd(uint8_t cmd_code, tSMP_CB* p_cb) {
482   uint8_t* p;
483   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIRING_REQ_SIZE + L2CAP_MIN_OFFSET);
484 
485   log::verbose("building cmd:{}", smp_opcode_text(static_cast<tSMP_OPCODE>(cmd_code)));
486 
487   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
488   UINT8_TO_STREAM(p, cmd_code);
489   UINT8_TO_STREAM(p, p_cb->local_io_capability);
490   UINT8_TO_STREAM(p, p_cb->loc_oob_flag);
491   UINT8_TO_STREAM(p, p_cb->loc_auth_req);
492   UINT8_TO_STREAM(p, p_cb->loc_enc_size);
493   UINT8_TO_STREAM(p, p_cb->local_i_key);
494   UINT8_TO_STREAM(p, p_cb->local_r_key);
495 
496   p_buf->offset = L2CAP_MIN_OFFSET;
497   /* 1B ERR_RSP op code + 1B cmd_op_code + 2B handle + 1B status */
498   p_buf->len = SMP_PAIRING_REQ_SIZE;
499 
500   return p_buf;
501 }
502 
503 /*******************************************************************************
504  *
505  * Function         smp_build_confirm_cmd
506  *
507  * Description      Build confirm request command.
508  *
509  ******************************************************************************/
smp_build_confirm_cmd(uint8_t,tSMP_CB * p_cb)510 static BT_HDR* smp_build_confirm_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
511   uint8_t* p;
512   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CONFIRM_CMD_SIZE + L2CAP_MIN_OFFSET);
513 
514   log::verbose("addr:{}", p_cb->pairing_bda);
515 
516   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
517 
518   UINT8_TO_STREAM(p, SMP_OPCODE_CONFIRM);
519   ARRAY_TO_STREAM(p, p_cb->confirm, OCTET16_LEN);
520 
521   p_buf->offset = L2CAP_MIN_OFFSET;
522   p_buf->len = SMP_CONFIRM_CMD_SIZE;
523 
524   return p_buf;
525 }
526 
527 /*******************************************************************************
528  *
529  * Function         smp_build_rand_cmd
530  *
531  * Description      Build Random command.
532  *
533  ******************************************************************************/
smp_build_rand_cmd(uint8_t,tSMP_CB * p_cb)534 static BT_HDR* smp_build_rand_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
535   uint8_t* p;
536   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_RAND_CMD_SIZE + L2CAP_MIN_OFFSET);
537 
538   log::verbose("addr:{}", p_cb->pairing_bda);
539 
540   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
541   UINT8_TO_STREAM(p, SMP_OPCODE_RAND);
542   ARRAY_TO_STREAM(p, p_cb->rand, OCTET16_LEN);
543 
544   p_buf->offset = L2CAP_MIN_OFFSET;
545   p_buf->len = SMP_RAND_CMD_SIZE;
546 
547   return p_buf;
548 }
549 
550 /*******************************************************************************
551  *
552  * Function         smp_build_encrypt_info_cmd
553  *
554  * Description      Build security information command.
555  *
556  ******************************************************************************/
smp_build_encrypt_info_cmd(uint8_t,tSMP_CB * p_cb)557 static BT_HDR* smp_build_encrypt_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
558   uint8_t* p;
559   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ENC_INFO_SIZE + L2CAP_MIN_OFFSET);
560 
561   log::verbose("addr:{}", p_cb->pairing_bda);
562 
563   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
564   UINT8_TO_STREAM(p, SMP_OPCODE_ENCRYPT_INFO);
565   ARRAY_TO_STREAM(p, p_cb->ltk, OCTET16_LEN);
566 
567   p_buf->offset = L2CAP_MIN_OFFSET;
568   p_buf->len = SMP_ENC_INFO_SIZE;
569 
570   return p_buf;
571 }
572 
573 /*******************************************************************************
574  *
575  * Function         smp_build_central_id_cmd
576  *
577  * Description      Build security information command.
578  *
579  ******************************************************************************/
smp_build_central_id_cmd(uint8_t,tSMP_CB * p_cb)580 static BT_HDR* smp_build_central_id_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
581   uint8_t* p;
582   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_CENTRAL_ID_SIZE + L2CAP_MIN_OFFSET);
583 
584   log::verbose("addr:{}", p_cb->pairing_bda);
585 
586   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
587   UINT8_TO_STREAM(p, SMP_OPCODE_CENTRAL_ID);
588   UINT16_TO_STREAM(p, p_cb->ediv);
589   ARRAY_TO_STREAM(p, p_cb->enc_rand, BT_OCTET8_LEN);
590 
591   p_buf->offset = L2CAP_MIN_OFFSET;
592   p_buf->len = SMP_CENTRAL_ID_SIZE;
593 
594   return p_buf;
595 }
596 
597 /*******************************************************************************
598  *
599  * Function         smp_build_identity_info_cmd
600  *
601  * Description      Build identity information command.
602  *
603  ******************************************************************************/
smp_build_identity_info_cmd(uint8_t,tSMP_CB * p_cb)604 static BT_HDR* smp_build_identity_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
605   uint8_t* p;
606   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_INFO_SIZE + L2CAP_MIN_OFFSET);
607 
608   log::verbose("addr:{}", p_cb->pairing_bda);
609 
610   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
611 
612   const Octet16& irk = BTM_GetDeviceIDRoot();
613 
614   UINT8_TO_STREAM(p, SMP_OPCODE_IDENTITY_INFO);
615   ARRAY_TO_STREAM(p, irk.data(), OCTET16_LEN);
616 
617   p_buf->offset = L2CAP_MIN_OFFSET;
618   p_buf->len = SMP_ID_INFO_SIZE;
619 
620   return p_buf;
621 }
622 
623 /*******************************************************************************
624  *
625  * Function         smp_build_id_addr_cmd
626  *
627  * Description      Build identity address information command.
628  *
629  ******************************************************************************/
smp_build_id_addr_cmd(uint8_t,tSMP_CB * p_cb)630 static BT_HDR* smp_build_id_addr_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
631   uint8_t* p;
632   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_ID_ADDR_SIZE + L2CAP_MIN_OFFSET);
633 
634   log::verbose("addr:{}", p_cb->pairing_bda);
635 
636   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
637   UINT8_TO_STREAM(p, SMP_OPCODE_ID_ADDR);
638   UINT8_TO_STREAM(p, 0);
639   BDADDR_TO_STREAM(p, bluetooth::ToRawAddress(bluetooth::shim::GetController()->GetMacAddress()));
640 
641   p_buf->offset = L2CAP_MIN_OFFSET;
642   p_buf->len = SMP_ID_ADDR_SIZE;
643 
644   return p_buf;
645 }
646 
647 /*******************************************************************************
648  *
649  * Function         smp_build_signing_info_cmd
650  *
651  * Description      Build signing information command.
652  *
653  ******************************************************************************/
smp_build_signing_info_cmd(uint8_t,tSMP_CB * p_cb)654 static BT_HDR* smp_build_signing_info_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
655   uint8_t* p;
656   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_SIGN_INFO_SIZE + L2CAP_MIN_OFFSET);
657 
658   log::verbose("addr:{}", p_cb->pairing_bda);
659 
660   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
661   UINT8_TO_STREAM(p, SMP_OPCODE_SIGN_INFO);
662   ARRAY_TO_STREAM(p, p_cb->csrk, OCTET16_LEN);
663 
664   p_buf->offset = L2CAP_MIN_OFFSET;
665   p_buf->len = SMP_SIGN_INFO_SIZE;
666 
667   return p_buf;
668 }
669 
670 /*******************************************************************************
671  *
672  * Function         smp_build_pairing_fail
673  *
674  * Description      Build Pairing Fail command.
675  *
676  ******************************************************************************/
smp_build_pairing_fail(uint8_t,tSMP_CB * p_cb)677 static BT_HDR* smp_build_pairing_fail(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
678   uint8_t* p;
679   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + L2CAP_MIN_OFFSET);
680 
681   log::verbose("addr:{}", p_cb->pairing_bda);
682 
683   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
684   UINT8_TO_STREAM(p, SMP_OPCODE_PAIRING_FAILED);
685   UINT8_TO_STREAM(p, p_cb->failure);
686 
687   p_buf->offset = L2CAP_MIN_OFFSET;
688   p_buf->len = SMP_PAIR_FAIL_SIZE;
689 
690   return p_buf;
691 }
692 
693 /*******************************************************************************
694  *
695  * Function         smp_build_security_request
696  *
697  * Description      Build security request command.
698  *
699  ******************************************************************************/
smp_build_security_request(uint8_t,tSMP_CB * p_cb)700 static BT_HDR* smp_build_security_request(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
701   uint8_t* p;
702   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + 2 + L2CAP_MIN_OFFSET);
703 
704   log::verbose("addr:{}", p_cb->pairing_bda);
705 
706   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
707   UINT8_TO_STREAM(p, SMP_OPCODE_SEC_REQ);
708   UINT8_TO_STREAM(p, p_cb->loc_auth_req);
709 
710   p_buf->offset = L2CAP_MIN_OFFSET;
711   p_buf->len = SMP_SECURITY_REQUEST_SIZE;
712 
713   log::verbose("opcode={} auth_req=0x{:x}", SMP_OPCODE_SEC_REQ, p_cb->loc_auth_req);
714 
715   return p_buf;
716 }
717 
718 /*******************************************************************************
719  *
720  * Function         smp_build_pair_public_key_cmd
721  *
722  * Description      Build pairing public key command.
723  *
724  ******************************************************************************/
smp_build_pair_public_key_cmd(uint8_t,tSMP_CB * p_cb)725 static BT_HDR* smp_build_pair_public_key_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
726   uint8_t* p;
727   uint8_t publ_key[2 * BT_OCTET32_LEN];
728   uint8_t* p_publ_key = publ_key;
729   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_PUBL_KEY_SIZE + L2CAP_MIN_OFFSET);
730 
731   log::verbose("addr:{}", p_cb->pairing_bda);
732 
733   memcpy(p_publ_key, p_cb->loc_publ_key.x, BT_OCTET32_LEN);
734   memcpy(p_publ_key + BT_OCTET32_LEN, p_cb->loc_publ_key.y, BT_OCTET32_LEN);
735 
736   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
737   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_PUBLIC_KEY);
738   ARRAY_TO_STREAM(p, p_publ_key, 2 * BT_OCTET32_LEN);
739 
740   p_buf->offset = L2CAP_MIN_OFFSET;
741   p_buf->len = SMP_PAIR_PUBL_KEY_SIZE;
742 
743   return p_buf;
744 }
745 
746 /*******************************************************************************
747  *
748  * Function         smp_build_pairing_commitment_cmd
749  *
750  * Description      Build pairing commitment command.
751  *
752  ******************************************************************************/
smp_build_pairing_commitment_cmd(uint8_t,tSMP_CB * p_cb)753 static BT_HDR* smp_build_pairing_commitment_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
754   uint8_t* p;
755   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_COMMITM_SIZE + L2CAP_MIN_OFFSET);
756 
757   log::verbose("addr:{}", p_cb->pairing_bda);
758 
759   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
760   UINT8_TO_STREAM(p, SMP_OPCODE_CONFIRM);
761   ARRAY_TO_STREAM(p, p_cb->commitment, OCTET16_LEN);
762 
763   p_buf->offset = L2CAP_MIN_OFFSET;
764   p_buf->len = SMP_PAIR_COMMITM_SIZE;
765 
766   return p_buf;
767 }
768 
769 /*******************************************************************************
770  *
771  * Function         smp_build_pair_dhkey_check_cmd
772  *
773  * Description      Build pairing DHKey check command.
774  *
775  ******************************************************************************/
smp_build_pair_dhkey_check_cmd(uint8_t,tSMP_CB * p_cb)776 static BT_HDR* smp_build_pair_dhkey_check_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
777   uint8_t* p;
778   BT_HDR* p_buf =
779           (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_DHKEY_CHECK_SIZE + L2CAP_MIN_OFFSET);
780 
781   log::verbose("addr:{}", p_cb->pairing_bda);
782 
783   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
784   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_DHKEY_CHECK);
785   ARRAY_TO_STREAM(p, p_cb->dhkey_check, OCTET16_LEN);
786 
787   p_buf->offset = L2CAP_MIN_OFFSET;
788   p_buf->len = SMP_PAIR_DHKEY_CHECK_SIZE;
789 
790   return p_buf;
791 }
792 
793 /*******************************************************************************
794  *
795  * Function         smp_build_pairing_keypress_notification_cmd
796  *
797  * Description      Build keypress notification command.
798  *
799  ******************************************************************************/
smp_build_pairing_keypress_notification_cmd(uint8_t,tSMP_CB * p_cb)800 static BT_HDR* smp_build_pairing_keypress_notification_cmd(uint8_t /* cmd_code */, tSMP_CB* p_cb) {
801   uint8_t* p;
802   BT_HDR* p_buf =
803           (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_KEYPR_NOTIF_SIZE + L2CAP_MIN_OFFSET);
804 
805   log::verbose("addr:{}", p_cb->pairing_bda);
806 
807   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
808   UINT8_TO_STREAM(p, SMP_OPCODE_PAIR_KEYPR_NOTIF);
809   UINT8_TO_STREAM(p, p_cb->local_keypress_notification);
810 
811   p_buf->offset = L2CAP_MIN_OFFSET;
812   p_buf->len = SMP_PAIR_KEYPR_NOTIF_SIZE;
813 
814   return p_buf;
815 }
816 
817 /** This function is called to convert a 6 to 16 digits numeric character string
818  * into SMP TK. */
smp_convert_string_to_tk(Octet16 * tk,uint32_t passkey)819 void smp_convert_string_to_tk(Octet16* tk, uint32_t passkey) {
820   uint8_t* p = tk->data();
821   tSMP_KEY key;
822   log::verbose("smp_convert_string_to_tk");
823   UINT32_TO_STREAM(p, passkey);
824 
825   key.key_type = SMP_KEY_TYPE_TK;
826   key.p_data = tk->data();
827 
828   tSMP_INT_DATA smp_int_data;
829   smp_int_data.key = key;
830   smp_sm_event(&smp_cb, SMP_KEY_READY_EVT, &smp_int_data);
831 }
832 
833 /** This function is called to mask off the encryption key based on the maximum
834  * encryption key size. */
smp_mask_enc_key(uint8_t loc_enc_size,Octet16 * p_data)835 void smp_mask_enc_key(uint8_t loc_enc_size, Octet16* p_data) {
836   log::verbose("smp_mask_enc_key");
837   if (loc_enc_size < OCTET16_LEN) {
838     for (; loc_enc_size < OCTET16_LEN; loc_enc_size++) {
839       (*p_data)[loc_enc_size] = 0;
840     }
841   }
842   return;
843 }
844 
845 /** utility function to do an biteise exclusive-OR of two bit strings of the
846  * length of OCTET16_LEN. Result is stored in first argument.
847  */
smp_xor_128(Octet16 * a,const Octet16 & b)848 void smp_xor_128(Octet16* a, const Octet16& b) {
849   log::assert_that(a != nullptr, "assert failed: a != nullptr");
850   uint8_t i, *aa = a->data();
851   const uint8_t* bb = b.data();
852 
853   for (i = 0; i < OCTET16_LEN; i++) {
854     aa[i] = aa[i] ^ bb[i];
855   }
856 }
857 
init(uint8_t security_mode)858 void tSMP_CB::init(uint8_t security_mode) {
859   *this = {};
860 
861   init_security_mode = security_mode;
862   smp_cb.smp_rsp_timer_ent = alarm_new("smp.smp_rsp_timer_ent");
863   smp_cb.delayed_auth_timer_ent = alarm_new("smp.delayed_auth_timer_ent");
864 
865   log::verbose("init_security_mode:{}", init_security_mode);
866 
867   smp_l2cap_if_init();
868   /* initialization of P-256 parameters */
869   p_256_init_curve();
870 
871   /* Initialize failure case for certification */
872   smp_cb.cert_failure =
873           static_cast<tSMP_STATUS>(stack_config_get_interface()->get_pts_smp_failure_case());
874   if (smp_cb.cert_failure) {
875     log::error("PTS FAILURE MODE IN EFFECT (CASE {})", smp_cb.cert_failure);
876   }
877 }
878 
879 /*******************************************************************************
880  *
881  * Function         reset
882  *
883  * Description      reset SMP control block
884  *
885  * Returns          void
886  *
887  ******************************************************************************/
reset()888 void tSMP_CB::reset() {
889   tSMP_CALLBACK* p_callback = this->p_callback;
890   uint8_t init_security_mode = this->init_security_mode;
891   alarm_t* smp_rsp_timer_ent = this->smp_rsp_timer_ent;
892   alarm_t* delayed_auth_timer_ent = this->delayed_auth_timer_ent;
893 
894   log::verbose("resetting SMP_CB");
895 
896   alarm_cancel(this->smp_rsp_timer_ent);
897   alarm_cancel(this->delayed_auth_timer_ent);
898 
899   *this = {};
900   this->init_security_mode = init_security_mode;
901 
902   this->p_callback = p_callback;
903   this->init_security_mode = init_security_mode;
904   this->smp_rsp_timer_ent = smp_rsp_timer_ent;
905   this->delayed_auth_timer_ent = delayed_auth_timer_ent;
906 }
907 
908 /*******************************************************************************
909  *
910  * Function         smp_remove_fixed_channel
911  *
912  * Description      This function is called to remove the fixed channel
913  *
914  * Returns          void
915  *
916  ******************************************************************************/
smp_remove_fixed_channel(tSMP_CB * p_cb)917 void smp_remove_fixed_channel(tSMP_CB* p_cb) {
918   log::verbose("addr:{}", p_cb->pairing_bda);
919 
920   if (p_cb->smp_over_br) {
921     if (!stack::l2cap::get_interface().L2CA_RemoveFixedChnl(L2CAP_SMP_BR_CID, p_cb->pairing_bda)) {
922       log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", p_cb->pairing_bda,
923                  L2CAP_SMP_BR_CID);
924     }
925   } else {
926     if (!stack::l2cap::get_interface().L2CA_RemoveFixedChnl(L2CAP_SMP_CID, p_cb->pairing_bda)) {
927       log::error("Unable to remove L2CAP fixed channel peer:{} cid:{}", p_cb->pairing_bda,
928                  L2CAP_SMP_CID);
929     }
930   }
931 }
932 
933 /*******************************************************************************
934  *
935  * Function         smp_reset_control_value
936  *
937  * Description      This function is called to reset the control block value
938  *                  when the pairing procedure finished.
939  *
940  *
941  * Returns          void
942  *
943  ******************************************************************************/
smp_reset_control_value(tSMP_CB * p_cb)944 void smp_reset_control_value(tSMP_CB* p_cb) {
945   log::verbose("reset smp_cb");
946 
947   alarm_cancel(p_cb->smp_rsp_timer_ent);
948   p_cb->flags = 0;
949   /* set the link idle timer to drop the link when pairing is done
950      usually service discovery will follow authentication complete, to avoid
951      racing condition for a link down/up, set link idle timer to be
952      SMP_LINK_TOUT_MIN to guarantee SMP key exchange */
953   if (!stack::l2cap::get_interface().L2CA_SetIdleTimeoutByBdAddr(
954               p_cb->pairing_bda, SMP_LINK_TOUT_MIN, BT_TRANSPORT_LE)) {
955     log::warn("Unable to set L2CAP idle timeout peer:{} transport:{} timeout:{}", p_cb->pairing_bda,
956               BT_TRANSPORT_LE, SMP_LINK_TOUT_MIN);
957   }
958 
959   /* We can tell L2CAP to remove the fixed channel (if it has one) */
960   smp_remove_fixed_channel(p_cb);
961   p_cb->reset();
962 }
963 
964 /*******************************************************************************
965  *
966  * Function         smp_proc_pairing_cmpl
967  *
968  * Description      This function is called to process pairing complete
969  *
970  *
971  * Returns          void
972  *
973  ******************************************************************************/
smp_proc_pairing_cmpl(tSMP_CB * p_cb)974 void smp_proc_pairing_cmpl(tSMP_CB* p_cb) {
975   tSMP_CALLBACK* p_callback = p_cb->p_callback;
976   const RawAddress pairing_bda = p_cb->pairing_bda;
977 
978   tSMP_EVT_DATA evt_data = {
979           .cmplt =
980                   {
981                           .reason = p_cb->status,
982                           .sec_level =
983                                   (p_cb->status == SMP_SUCCESS) ? p_cb->sec_level : SMP_SEC_NONE,
984                           .is_pair_cancel = p_cb->is_pair_cancel,
985                           .smp_over_br = p_cb->smp_over_br,
986                   },
987   };
988 
989   if (p_cb->status == SMP_SUCCESS) {
990     log::debug(
991             "Pairing process has completed successfully remote:{} "
992             "sec_level:0x{:0x}",
993             p_cb->pairing_bda, evt_data.cmplt.sec_level);
994     BTM_LogHistory(kBtmLogTag, pairing_bda, "Pairing success");
995   } else {
996     log::warn(
997             "Pairing process has failed to remote:{} smp_reason:{} "
998             "sec_level:0x{:0x}",
999             p_cb->pairing_bda, smp_status_text(evt_data.cmplt.reason), evt_data.cmplt.sec_level);
1000     BTM_LogHistory(kBtmLogTag, pairing_bda, "Pairing failed",
1001                    std::format("reason:{}", smp_status_text(evt_data.cmplt.reason)));
1002   }
1003 
1004   // Log pairing complete event
1005   {
1006     auto direction = p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD
1007                              ? android::bluetooth::DirectionEnum::DIRECTION_OUTGOING
1008                              : android::bluetooth::DirectionEnum::DIRECTION_INCOMING;
1009     uint16_t metric_cmd = p_cb->smp_over_br ? SMP_METRIC_COMMAND_BR_PAIRING_CMPL
1010                                             : SMP_METRIC_COMMAND_LE_PAIRING_CMPL;
1011     uint16_t metric_status = p_cb->status;
1012     if (metric_status > SMP_MAX_FAIL_RSN_PER_SPEC) {
1013       metric_status |= SMP_METRIC_STATUS_INTERNAL_FLAG;
1014     }
1015     bluetooth::shim::LogMetricSmpPairingEvent(p_cb->pairing_bda, metric_cmd, direction,
1016                                               metric_status);
1017   }
1018 
1019   if (p_cb->status == SMP_SUCCESS && p_cb->smp_over_br) {
1020     btm_dev_consolidate_existing_connections(pairing_bda);
1021   }
1022 
1023   smp_reset_control_value(p_cb);
1024 
1025   if (p_callback) {
1026     (*p_callback)(SMP_COMPLT_EVT, pairing_bda, &evt_data);
1027   }
1028 }
1029 
1030 /*******************************************************************************
1031  *
1032  * Function         smp_command_has_invalid_length
1033  *
1034  * Description      Checks if the received SMP command has invalid length
1035  *                  It returns true if the command has invalid length.
1036  *
1037  * Returns          true if the command has invalid length, false otherwise.
1038  *
1039  ******************************************************************************/
smp_command_has_invalid_length(tSMP_CB * p_cb)1040 bool smp_command_has_invalid_length(tSMP_CB* p_cb) {
1041   uint8_t cmd_code = p_cb->rcvd_cmd_code;
1042 
1043   if ((cmd_code > (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */)) ||
1044       (cmd_code < SMP_OPCODE_MIN)) {
1045     log::warn("Received command with RESERVED code 0x{:02x}", cmd_code);
1046     return true;
1047   }
1048 
1049   if (!smp_command_has_valid_fixed_length(p_cb)) {
1050     return true;
1051   }
1052 
1053   return false;
1054 }
1055 
1056 /*******************************************************************************
1057  *
1058  * Function         smp_command_has_invalid_parameters
1059  *
1060  * Description      Checks if the received SMP command has invalid parameters
1061  *                  i.e. if the command length is valid and the command
1062  *                  parameters are inside specified range.
1063  *                  It returns true if the command has invalid parameters.
1064  *
1065  * Returns          true if the command has invalid parameters, false otherwise.
1066  *
1067  ******************************************************************************/
smp_command_has_invalid_parameters(tSMP_CB * p_cb)1068 bool smp_command_has_invalid_parameters(tSMP_CB* p_cb) {
1069   uint8_t cmd_code = p_cb->rcvd_cmd_code;
1070 
1071   if ((cmd_code > (SMP_OPCODE_MAX + 1 /* for SMP_OPCODE_PAIR_COMMITM */)) ||
1072       (cmd_code < SMP_OPCODE_MIN)) {
1073     log::warn("Received command with RESERVED code 0x{:02x}", cmd_code);
1074     return true;
1075   }
1076 
1077   if (!(*smp_cmd_len_is_valid[cmd_code])(p_cb)) {
1078     log::warn("Command length not valid for cmd_code 0x{:02x}", cmd_code);
1079     return true;
1080   }
1081 
1082   if (!(*smp_cmd_param_ranges_are_valid[cmd_code])(p_cb)) {
1083     log::warn("Parameter ranges not valid code 0x{:02x}", cmd_code);
1084     return true;
1085   }
1086 
1087   return false;
1088 }
1089 
1090 /*******************************************************************************
1091  *
1092  * Function         smp_command_has_valid_fixed_length
1093  *
1094  * Description      Checks if the received command size is equal to the size
1095  *                  according to specs.
1096  *
1097  * Returns          true if the command size is as expected, false otherwise.
1098  *
1099  * Note             The command is expected to have fixed length.
1100  ******************************************************************************/
smp_command_has_valid_fixed_length(tSMP_CB * p_cb)1101 bool smp_command_has_valid_fixed_length(tSMP_CB* p_cb) {
1102   uint8_t cmd_code = p_cb->rcvd_cmd_code;
1103 
1104   log::verbose("cmd code 0x{:02x}", cmd_code);
1105 
1106   if (p_cb->rcvd_cmd_len != smp_cmd_size_per_spec[cmd_code]) {
1107     log::warn(
1108             "Rcvd from the peer cmd 0x{:02x} with invalid length 0x{:02x} (per "
1109             "spec the length is 0x{:02x}).",
1110             cmd_code, p_cb->rcvd_cmd_len, smp_cmd_size_per_spec[cmd_code]);
1111     return false;
1112   }
1113 
1114   return true;
1115 }
1116 
1117 /*******************************************************************************
1118  *
1119  * Function         smp_pairing_request_response_parameters_are_valid
1120  *
1121  * Description      Validates parameter ranges in the received SMP command
1122  *                  pairing request or pairing response.
1123  *                  The parameters to validate:
1124  *                  IO capability,
1125  *                  OOB data flag,
1126  *                  Bonding_flags in AuthReq
1127  *                  Maximum encryption key size.
1128  *                  Returns false if at least one of these parameters is out of
1129  *                  range.
1130  *
1131  ******************************************************************************/
smp_pairing_request_response_parameters_are_valid(tSMP_CB * p_cb)1132 bool smp_pairing_request_response_parameters_are_valid(tSMP_CB* p_cb) {
1133   uint8_t io_caps = p_cb->peer_io_caps;
1134   uint8_t oob_flag = p_cb->peer_oob_flag;
1135   uint8_t bond_flag = p_cb->peer_auth_req & 0x03;  // 0x03 is gen bond with appropriate mask
1136   uint8_t enc_size = p_cb->peer_enc_size;
1137 
1138   log::verbose("cmd code 0x{:02x}", p_cb->rcvd_cmd_code);
1139 
1140   if (io_caps >= BTM_IO_CAP_MAX) {
1141     log::warn(
1142             "Rcvd from the peer cmd 0x{:02x} with IO Capability value (0x{:02x}) "
1143             "out of range).",
1144             p_cb->rcvd_cmd_code, io_caps);
1145     return false;
1146   }
1147 
1148   if (!((oob_flag == SMP_OOB_NONE) || (oob_flag == SMP_OOB_PRESENT))) {
1149     log::warn(
1150             "Rcvd from the peer cmd 0x{:02x} with OOB data flag value (0x{:02x}) "
1151             "out of range).",
1152             p_cb->rcvd_cmd_code, oob_flag);
1153     return false;
1154   }
1155 
1156   if (!((bond_flag == SMP_AUTH_NO_BOND) || (bond_flag == SMP_AUTH_BOND))) {
1157     log::warn(
1158             "Rcvd from the peer cmd 0x{:02x} with Bonding_Flags value (0x{:02x}) "
1159             "out of range).",
1160             p_cb->rcvd_cmd_code, bond_flag);
1161     return false;
1162   }
1163 
1164   if ((enc_size < SMP_ENCR_KEY_SIZE_MIN) || (enc_size > SMP_ENCR_KEY_SIZE_MAX)) {
1165     log::warn(
1166             "Rcvd from the peer cmd 0x{:02x} with Maximum Encryption Key value "
1167             "(0x{:02x}) out of range).",
1168             p_cb->rcvd_cmd_code, enc_size);
1169     return false;
1170   }
1171 
1172   return true;
1173 }
1174 
1175 /*******************************************************************************
1176  *
1177  * Function         smp_pairing_keypress_notification_is_valid
1178  *
1179  * Description      Validates Notification Type parameter range in the received
1180  *                  SMP command pairing keypress notification.
1181  *                  Returns false if this parameter is out of range.
1182  *
1183  ******************************************************************************/
smp_pairing_keypress_notification_is_valid(tSMP_CB * p_cb)1184 bool smp_pairing_keypress_notification_is_valid(tSMP_CB* p_cb) {
1185   tSMP_SC_KEY_TYPE keypress_notification = p_cb->peer_keypress_notification;
1186 
1187   log::verbose("cmd code 0x{:02x}", p_cb->rcvd_cmd_code);
1188 
1189   if (keypress_notification >= SMP_SC_KEY_OUT_OF_RANGE) {
1190     log::warn(
1191             "Rcvd from the peer cmd 0x{:02x} with Pairing Keypress Notification "
1192             "value (0x{:02x}) out of range).",
1193             p_cb->rcvd_cmd_code, keypress_notification);
1194     return false;
1195   }
1196 
1197   return true;
1198 }
1199 
1200 /*******************************************************************************
1201  *
1202  * Function         smp_parameter_unconditionally_valid
1203  *
1204  * Description      Always returns true.
1205  *
1206  ******************************************************************************/
smp_parameter_unconditionally_valid(tSMP_CB *)1207 bool smp_parameter_unconditionally_valid(tSMP_CB* /* p_cb */) { return true; }
1208 
1209 /*******************************************************************************
1210  *
1211  * Function         smp_parameter_unconditionally_invalid
1212  *
1213  * Description      Always returns false.
1214  *
1215  ******************************************************************************/
smp_parameter_unconditionally_invalid(tSMP_CB *)1216 bool smp_parameter_unconditionally_invalid(tSMP_CB* /* p_cb */) { return false; }
1217 
1218 /*******************************************************************************
1219  *
1220  * Function         smp_reject_unexpected_pairing_command
1221  *
1222  * Description      send pairing failure to an unexpected pairing command during
1223  *                  an active pairing process.
1224  *
1225  * Returns          void
1226  *
1227  ******************************************************************************/
smp_reject_unexpected_pairing_command(const RawAddress & bd_addr)1228 void smp_reject_unexpected_pairing_command(const RawAddress& bd_addr) {
1229   uint8_t* p;
1230   BT_HDR* p_buf = (BT_HDR*)osi_malloc(sizeof(BT_HDR) + SMP_PAIR_FAIL_SIZE + L2CAP_MIN_OFFSET);
1231 
1232   log::verbose("bd_addr:{}", bd_addr);
1233 
1234   p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
1235   UINT8_TO_STREAM(p, SMP_OPCODE_PAIRING_FAILED);
1236   UINT8_TO_STREAM(p, SMP_BUSY);
1237 
1238   p_buf->offset = L2CAP_MIN_OFFSET;
1239   p_buf->len = SMP_PAIR_FAIL_SIZE;
1240 
1241   smp_send_msg_to_L2CAP(bd_addr, p_buf);
1242 }
1243 
1244 /*******************************************************************************
1245  * Function         smp_select_association_model
1246  *
1247  * Description      This function selects association model to use for STK
1248  *                  generation. Selection is based on both sides' io capability,
1249  *                  oob data flag and authentication request.
1250  *
1251  * Note             If Secure Connections Only mode is required locally then we
1252  *                  come to this point only if both sides support Secure
1253  *                  Connections mode, i.e.
1254  *                  if p_cb->sc_only_mode_locally_required = true
1255  *                  then we come to this point only if
1256  *                      (p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) ==
1257  *                      (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) ==
1258  *                      SMP_SC_SUPPORT_BIT
1259  *
1260  ******************************************************************************/
smp_select_association_model(tSMP_CB * p_cb)1261 tSMP_ASSO_MODEL smp_select_association_model(tSMP_CB* p_cb) {
1262   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1263   p_cb->sc_mode_required_by_peer = false;
1264 
1265   log::verbose("p_cb->peer_io_caps = {} p_cb->local_io_capability = {}", p_cb->peer_io_caps,
1266                p_cb->local_io_capability);
1267   log::verbose("p_cb->peer_oob_flag = {} p_cb->loc_oob_flag = {}", p_cb->peer_oob_flag,
1268                p_cb->loc_oob_flag);
1269   log::verbose("p_cb->peer_auth_req = 0x{:02x} p_cb->loc_auth_req = 0x{:02x}", p_cb->peer_auth_req,
1270                p_cb->loc_auth_req);
1271   log::verbose("p_cb->sc_only_mode_locally_required = {}", p_cb->sc_only_mode_locally_required);
1272 
1273   if ((p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT)) {
1274     p_cb->sc_mode_required_by_peer = true;
1275   }
1276 
1277   if ((p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT) && (p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT)) {
1278     p_cb->key_derivation_h7_used = TRUE;
1279   }
1280 
1281   log::verbose("use_sc_process = {}, h7 use = {}", p_cb->sc_mode_required_by_peer,
1282                p_cb->key_derivation_h7_used);
1283 
1284   if (p_cb->sc_mode_required_by_peer) {
1285     model = smp_select_association_model_secure_connections(p_cb);
1286   } else {
1287     model = smp_select_legacy_association_model(p_cb);
1288   }
1289   return model;
1290 }
1291 
1292 /*******************************************************************************
1293  * Function         smp_select_legacy_association_model
1294  *
1295  * Description      This function is called to select association mode if at
1296  *                  least one side doesn't support secure connections.
1297  *
1298  ******************************************************************************/
smp_select_legacy_association_model(tSMP_CB * p_cb)1299 tSMP_ASSO_MODEL smp_select_legacy_association_model(tSMP_CB* p_cb) {
1300   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1301 
1302   log::verbose("addr:{}", p_cb->pairing_bda);
1303   /* if OOB data is present on both devices, then use OOB association model */
1304   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1305     return SMP_MODEL_OOB;
1306   }
1307 
1308   /* else if neither device requires MITM, then use Just Works association model
1309    */
1310   if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) {
1311     return SMP_MODEL_ENCRYPTION_ONLY;
1312   }
1313 
1314   /* otherwise use IO capability to select association model */
1315   if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && p_cb->local_io_capability < SMP_IO_CAP_MAX) {
1316     if (p_cb->role == HCI_ROLE_CENTRAL) {
1317       model = smp_association_table[p_cb->role][p_cb->peer_io_caps][p_cb->local_io_capability];
1318     } else {
1319       model = smp_association_table[p_cb->role][p_cb->local_io_capability][p_cb->peer_io_caps];
1320     }
1321   }
1322 
1323   return model;
1324 }
1325 
1326 /*******************************************************************************
1327  * Function         smp_select_association_model_secure_connections
1328  *
1329  * Description      This function is called to select association mode if both
1330  *                  sides support secure connections.
1331  *
1332  ******************************************************************************/
smp_select_association_model_secure_connections(tSMP_CB * p_cb)1333 tSMP_ASSO_MODEL smp_select_association_model_secure_connections(tSMP_CB* p_cb) {
1334   tSMP_ASSO_MODEL model = SMP_MODEL_OUT_OF_RANGE;
1335 
1336   log::verbose("addr:{}", p_cb->pairing_bda);
1337   /* if OOB data is present on at least one device, then use OOB association
1338    * model */
1339   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT || p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1340     return SMP_MODEL_SEC_CONN_OOB;
1341   }
1342 
1343   /* else if neither device requires MITM, then use Just Works association model
1344    */
1345   if (SMP_NO_MITM_REQUIRED(p_cb->peer_auth_req) && SMP_NO_MITM_REQUIRED(p_cb->loc_auth_req)) {
1346     return SMP_MODEL_SEC_CONN_JUSTWORKS;
1347   }
1348 
1349   /* otherwise use IO capability to select association model */
1350   if (p_cb->peer_io_caps < SMP_IO_CAP_MAX && p_cb->local_io_capability < SMP_IO_CAP_MAX) {
1351     if (p_cb->role == HCI_ROLE_CENTRAL) {
1352       model = smp_association_table_sc[p_cb->role][p_cb->peer_io_caps][p_cb->local_io_capability];
1353     } else {
1354       model = smp_association_table_sc[p_cb->role][p_cb->local_io_capability][p_cb->peer_io_caps];
1355     }
1356   }
1357 
1358   return model;
1359 }
1360 
1361 /*******************************************************************************
1362  * Function         smp_calculate_random_input
1363  *
1364  * Description      This function returns random input value to be used in
1365  *                  commitment calculation for SC passkey entry association mode
1366  *                  (if bit["round"] in "random" array == 1 then returns 0x81
1367  *                   else returns 0x80).
1368  *
1369  * Returns          ri value
1370  *
1371  ******************************************************************************/
smp_calculate_random_input(uint8_t * random,uint8_t round)1372 uint8_t smp_calculate_random_input(uint8_t* random, uint8_t round) {
1373   uint8_t i = round / 8;
1374   uint8_t j = round % 8;
1375   uint8_t ri;
1376 
1377   ri = ((random[i] >> j) & 1) | 0x80;
1378   log::verbose("random:0x{:02x}, round:{}, i:{}, j:{}, ri:0x{:02x}", random[i], round, i, j, ri);
1379   return ri;
1380 }
1381 
1382 /*******************************************************************************
1383  * Function         smp_collect_local_io_capabilities
1384  *
1385  * Description      This function puts into IOcap array local device
1386  *                  IOCapability, OOB data, AuthReq.
1387  *
1388  * Returns          void
1389  *
1390  ******************************************************************************/
smp_collect_local_io_capabilities(uint8_t * iocap,tSMP_CB * p_cb)1391 void smp_collect_local_io_capabilities(uint8_t* iocap, tSMP_CB* p_cb) {
1392   log::verbose("addr:{}", p_cb->pairing_bda);
1393 
1394   iocap[0] = p_cb->local_io_capability;
1395   iocap[1] = p_cb->loc_oob_flag;
1396   iocap[2] = p_cb->loc_auth_req;
1397 }
1398 
1399 /*******************************************************************************
1400  * Function         smp_collect_peer_io_capabilities
1401  *
1402  * Description      This function puts into IOcap array peer device
1403  *                  IOCapability, OOB data, AuthReq.
1404  *
1405  * Returns          void
1406  *
1407  ******************************************************************************/
smp_collect_peer_io_capabilities(uint8_t * iocap,tSMP_CB * p_cb)1408 void smp_collect_peer_io_capabilities(uint8_t* iocap, tSMP_CB* p_cb) {
1409   log::verbose("addr:{}", p_cb->pairing_bda);
1410 
1411   iocap[0] = p_cb->peer_io_caps;
1412   iocap[1] = p_cb->peer_oob_flag;
1413   iocap[2] = p_cb->peer_auth_req;
1414 }
1415 
1416 /*******************************************************************************
1417  * Function         smp_collect_local_ble_address
1418  *
1419  * Description      Put the the local device LE address into the le_addr array:
1420  *                  le_addr[0-5] = local BD ADDR,
1421  *                  le_addr[6] = local le address type (PUBLIC/RANDOM).
1422  *
1423  * Returns          void
1424  *
1425  ******************************************************************************/
smp_collect_local_ble_address(uint8_t * le_addr,tSMP_CB * p_cb)1426 void smp_collect_local_ble_address(uint8_t* le_addr, tSMP_CB* p_cb) {
1427   tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
1428   RawAddress bda;
1429   uint8_t* p = le_addr;
1430 
1431   log::verbose("addr:{}", p_cb->pairing_bda);
1432 
1433   BTM_ReadConnectionAddr(p_cb->pairing_bda, bda, &addr_type, true);
1434   BDADDR_TO_STREAM(p, bda);
1435   UINT8_TO_STREAM(p, addr_type);
1436 }
1437 
1438 /*******************************************************************************
1439  * Function         smp_collect_peer_ble_address
1440  *
1441  * Description      Put the peer device LE addr into the le_addr array:
1442  *                  le_addr[0-5] = peer BD ADDR,
1443  *                  le_addr[6] = peer le address type (PUBLIC/RANDOM).
1444  *
1445  * Returns          void
1446  *
1447  ******************************************************************************/
smp_collect_peer_ble_address(uint8_t * le_addr,tSMP_CB * p_cb)1448 void smp_collect_peer_ble_address(uint8_t* le_addr, tSMP_CB* p_cb) {
1449   tBLE_ADDR_TYPE addr_type = BLE_ADDR_PUBLIC;
1450   RawAddress bda;
1451   uint8_t* p = le_addr;
1452 
1453   log::verbose("addr:{}", p_cb->pairing_bda);
1454 
1455   if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda, &addr_type, true)) {
1456     log::error("can not collect peer le addr information for unknown device");
1457     return;
1458   }
1459 
1460   BDADDR_TO_STREAM(p, bda);
1461   UINT8_TO_STREAM(p, addr_type);
1462 }
1463 
1464 /*******************************************************************************
1465  * Function         smp_check_commitment
1466  *
1467  * Description      This function compares peer commitment values:
1468  *                  - expected (i.e. calculated locally),
1469  *                  - received from the peer.
1470  *
1471  * Returns          true  if the values are the same
1472  *                  false otherwise
1473  *
1474  ******************************************************************************/
smp_check_commitment(tSMP_CB * p_cb)1475 bool smp_check_commitment(tSMP_CB* p_cb) {
1476   log::verbose("addr:{}", p_cb->pairing_bda);
1477 
1478   Octet16 expected = smp_calculate_peer_commitment(p_cb);
1479   print128(expected, "calculated peer commitment");
1480   print128(p_cb->remote_commitment, "received peer commitment");
1481 
1482   if (memcmp(p_cb->remote_commitment.data(), expected.data(), OCTET16_LEN)) {
1483     log::warn("Commitment check fails");
1484     return false;
1485   }
1486 
1487   return true;
1488 }
1489 
1490 /*******************************************************************************
1491  *
1492  * Function         smp_save_secure_connections_long_term_key
1493  *
1494  * Description      The function saves SC LTK as BLE key for future use as local
1495  *                  and/or peer key.
1496  *
1497  * Returns          void
1498  *
1499  ******************************************************************************/
smp_save_secure_connections_long_term_key(tSMP_CB * p_cb)1500 void smp_save_secure_connections_long_term_key(tSMP_CB* p_cb) {
1501   log::verbose("Save LTK as local and peer key");
1502   tBTM_LE_KEY_VALUE lle_key = {
1503           .lenc_key =
1504                   {
1505                           .ltk = p_cb->ltk,
1506                           .div = 0,
1507                           .key_size = p_cb->loc_enc_size,
1508                           .sec_level = p_cb->sec_level,
1509                   },
1510   };
1511   btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LENC, &lle_key, true);
1512 
1513   tBTM_LE_KEY_VALUE ple_key = {
1514           .penc_key =
1515                   {
1516                           .ltk = p_cb->ltk,
1517                           .ediv = 0,
1518                           .sec_level = p_cb->sec_level,
1519                           .key_size = p_cb->loc_enc_size,
1520                   },
1521   };
1522   memset(ple_key.penc_key.rand, 0, BT_OCTET8_LEN);
1523   btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, &ple_key, true);
1524 }
1525 
1526 /** The function calculates MacKey and LTK and saves them in CB. To calculate
1527  * MacKey and LTK it calls smp_calc_f5(...). MacKey is used in dhkey
1528  * calculation, LTK is used to encrypt the link. */
smp_calculate_f5_mackey_and_long_term_key(tSMP_CB * p_cb)1529 void smp_calculate_f5_mackey_and_long_term_key(tSMP_CB* p_cb) {
1530   uint8_t a[7];
1531   uint8_t b[7];
1532   Octet16 na;
1533   Octet16 nb;
1534 
1535   log::verbose("addr:{}", p_cb->pairing_bda);
1536 
1537   if (p_cb->role == HCI_ROLE_CENTRAL) {
1538     smp_collect_local_ble_address(a, p_cb);
1539     smp_collect_peer_ble_address(b, p_cb);
1540     na = p_cb->rand;
1541     nb = p_cb->rrand;
1542   } else {
1543     smp_collect_local_ble_address(b, p_cb);
1544     smp_collect_peer_ble_address(a, p_cb);
1545     na = p_cb->rrand;
1546     nb = p_cb->rand;
1547   }
1548 
1549   crypto_toolbox::f5(p_cb->dhkey, na, nb, a, b, &p_cb->mac_key, &p_cb->ltk);
1550 }
1551 
1552 /*******************************************************************************
1553  *
1554  * Function         smp_request_oob_data
1555  *
1556  * Description      Requests application to provide OOB data.
1557  *
1558  * Returns          true - OOB data has to be provided by application
1559  *                  false - otherwise (unexpected)
1560  *
1561  ******************************************************************************/
smp_request_oob_data(tSMP_CB * p_cb)1562 bool smp_request_oob_data(tSMP_CB* p_cb) {
1563   tSMP_OOB_DATA_TYPE req_oob_type = SMP_OOB_INVALID_TYPE;
1564 
1565   log::verbose("addr:{}", p_cb->pairing_bda);
1566 
1567   if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1568     /* both local and peer rcvd data OOB */
1569     req_oob_type = SMP_OOB_BOTH;
1570   } else if (p_cb->peer_oob_flag == SMP_OOB_PRESENT) {
1571     /* peer rcvd OOB local data, local didn't receive OOB peer data */
1572     req_oob_type = SMP_OOB_LOCAL;
1573   } else if (p_cb->loc_oob_flag == SMP_OOB_PRESENT) {
1574     req_oob_type = SMP_OOB_PEER;
1575   }
1576 
1577   log::verbose("req_oob_type={}", req_oob_type);
1578 
1579   if (req_oob_type == SMP_OOB_INVALID_TYPE) {
1580     return false;
1581   }
1582 
1583   p_cb->req_oob_type = req_oob_type;
1584   p_cb->cb_evt = SMP_SC_OOB_REQ_EVT;
1585   tSMP_INT_DATA smp_int_data;
1586   smp_int_data.req_oob_type = req_oob_type;
1587   smp_sm_event(p_cb, SMP_TK_REQ_EVT, &smp_int_data);
1588 
1589   return true;
1590 }
1591 
print128(const Octet16 & x,const char * key_name)1592 void print128(const Octet16& x, const char* key_name) {
1593   uint8_t* p = (uint8_t*)x.data();
1594 
1595   log::info("{}(MSB~LSB):", key_name);
1596   for (int i = 0; i < 4; i++) {
1597     log::info("{:02x}:{:02x}:{:02x}:{:02x}", p[OCTET16_LEN - i * 4 - 1], p[OCTET16_LEN - i * 4 - 2],
1598               p[OCTET16_LEN - i * 4 - 3], p[OCTET16_LEN - i * 4 - 4]);
1599   }
1600 }
1601