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