1 /******************************************************************************
2  *
3  *  Copyright 2003-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 #define LOG_TAG "smp_act"
20 
21 #include <bluetooth/log.h>
22 #include <com_android_bluetooth_flags.h>
23 
24 #include <cstring>
25 
26 #include "btif/include/btif_common.h"
27 #include "btif/include/core_callbacks.h"
28 #include "btif/include/stack_manager_t.h"
29 #include "crypto_toolbox/crypto_toolbox.h"
30 #include "device/include/interop.h"
31 #include "internal_include/bt_target.h"
32 #include "p_256_ecc_pp.h"
33 #include "smp_int.h"
34 #include "stack/btm/btm_ble_sec.h"
35 #include "stack/btm/btm_dev.h"
36 #include "stack/btm/btm_sec.h"
37 #include "stack/include/bt_octets.h"
38 #include "stack/include/bt_types.h"
39 #include "stack/include/btm_client_interface.h"
40 #include "stack/include/btm_log_history.h"
41 #include "stack/include/btm_status.h"
42 #include "stack/include/smp_api.h"
43 #include "stack/include/smp_api_types.h"
44 #include "types/raw_address.h"
45 
46 using namespace bluetooth;
47 
48 namespace {
49 constexpr char kBtmLogTag[] = "SMP";
50 }
51 
52 static void smp_key_distribution_by_transport(tSMP_CB* p_cb, tSMP_INT_DATA* p_data);
53 
54 #define SMP_KEY_DIST_TYPE_MAX 4
55 
56 const tSMP_ACT smp_distribute_act[] = {
57         smp_generate_ltk,       /* SMP_SEC_KEY_TYPE_ENC - '1' bit index */
58         smp_send_id_info,       /* SMP_SEC_KEY_TYPE_ID - '1' bit index */
59         smp_generate_csrk,      /* SMP_SEC_KEY_TYPE_CSRK - '1' bit index */
60         smp_set_derive_link_key /* SMP_SEC_KEY_TYPE_LK - '1' bit index */
61 };
62 
pts_test_send_authentication_complete_failure(tSMP_CB * p_cb)63 static bool pts_test_send_authentication_complete_failure(tSMP_CB* p_cb) {
64   tSMP_STATUS reason = p_cb->cert_failure;
65   if (reason == SMP_PAIR_AUTH_FAIL || reason == SMP_PAIR_FAIL_UNKNOWN ||
66       reason == SMP_PAIR_NOT_SUPPORT || reason == SMP_PASSKEY_ENTRY_FAIL ||
67       reason == SMP_REPEATED_ATTEMPTS) {
68     tSMP_INT_DATA smp_int_data;
69     smp_int_data.status = reason;
70     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
71     return true;
72   }
73   return false;
74 }
75 
76 /*******************************************************************************
77  * Function         smp_update_key_mask
78  * Description      This function updates the key mask for sending or receiving.
79  ******************************************************************************/
smp_update_key_mask(tSMP_CB * p_cb,uint8_t key_type,bool recv)80 static void smp_update_key_mask(tSMP_CB* p_cb, uint8_t key_type, bool recv) {
81   log::verbose("before update role={} recv={} local_i_key=0x{:02x}, local_r_key=0x{:02x}",
82                p_cb->role, recv, p_cb->local_i_key, p_cb->local_r_key);
83 
84   if (((p_cb->sc_mode_required_by_peer) || (p_cb->smp_over_br)) &&
85       ((key_type == SMP_SEC_KEY_TYPE_ENC) || (key_type == SMP_SEC_KEY_TYPE_LK))) {
86     /* in LE SC mode LTK, CSRK and BR/EDR LK are derived locally instead of
87     ** being exchanged with the peer */
88     p_cb->local_i_key &= ~key_type;
89     p_cb->local_r_key &= ~key_type;
90   } else if (p_cb->role == HCI_ROLE_PERIPHERAL) {
91     if (recv) {
92       p_cb->local_i_key &= ~key_type;
93     } else {
94       p_cb->local_r_key &= ~key_type;
95     }
96   } else {
97     if (recv) {
98       p_cb->local_r_key &= ~key_type;
99     } else {
100       p_cb->local_i_key &= ~key_type;
101     }
102   }
103 
104   log::verbose("updated local_i_key=0x{:02x}, local_r_key=0x{:02x}", p_cb->local_i_key,
105                p_cb->local_r_key);
106 }
107 
108 /*******************************************************************************
109  * Function     smp_send_app_cback
110  * Description  notifies application about the events the application is
111  *              interested in
112  ******************************************************************************/
smp_send_app_cback(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)113 void smp_send_app_cback(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
114   tSMP_EVT_DATA cb_data;
115   tBTM_STATUS callback_rc;
116   uint8_t remote_lmp_version = 0;
117 
118   log::debug("addr:{} event:{}", p_cb->pairing_bda, smp_evt_to_text(p_cb->cb_evt));
119 
120   if (p_cb->p_callback && p_cb->cb_evt != 0) {
121     switch (p_cb->cb_evt) {
122       case SMP_IO_CAP_REQ_EVT:
123         cb_data.io_req.auth_req = p_cb->peer_auth_req;
124         cb_data.io_req.oob_data = SMP_OOB_NONE;
125         cb_data.io_req.io_cap = SMP_IO_CAP_KBDISP;
126         cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE;
127         cb_data.io_req.init_keys = p_cb->local_i_key;
128         cb_data.io_req.resp_keys = p_cb->local_r_key;
129         log::debug("Notify app io_cap={}", cb_data.io_req.io_cap);
130         break;
131 
132       case SMP_NC_REQ_EVT:
133         cb_data.passkey = p_data->passkey;
134         break;
135       case SMP_SC_OOB_REQ_EVT:
136         cb_data.req_oob_type = p_data->req_oob_type;
137         break;
138       case SMP_SC_LOC_OOB_DATA_UP_EVT:
139         cb_data.loc_oob_data = p_cb->sc_oob_data.loc_oob_data;
140         break;
141 
142       case SMP_BR_KEYS_REQ_EVT:
143         cb_data.io_req.auth_req = 0;
144         cb_data.io_req.oob_data = SMP_OOB_NONE;
145         cb_data.io_req.io_cap = 0;
146         cb_data.io_req.max_key_size = SMP_MAX_ENC_KEY_SIZE;
147         cb_data.io_req.init_keys = SMP_BR_SEC_DEFAULT_KEY;
148         cb_data.io_req.resp_keys = SMP_BR_SEC_DEFAULT_KEY;
149         break;
150 
151       case SMP_LE_ADDR_ASSOC_EVT:
152         cb_data.id_addr_with_type.bda = p_cb->id_addr;
153         cb_data.id_addr_with_type.type = p_cb->id_addr_type;
154         break;
155 
156       default:
157         log::error("Unexpected event:{}", p_cb->cb_evt);
158         break;
159     }
160 
161     callback_rc = (*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, &cb_data);
162 
163     if (callback_rc == tBTM_STATUS::BTM_SUCCESS) {
164       switch (p_cb->cb_evt) {
165         case SMP_IO_CAP_REQ_EVT:
166           p_cb->loc_auth_req = cb_data.io_req.auth_req;
167           p_cb->local_io_capability = cb_data.io_req.io_cap;
168           p_cb->loc_oob_flag = cb_data.io_req.oob_data;
169           p_cb->loc_enc_size = cb_data.io_req.max_key_size;
170           p_cb->local_i_key = cb_data.io_req.init_keys;
171           p_cb->local_r_key = cb_data.io_req.resp_keys;
172 
173           if (!(p_cb->loc_auth_req & SMP_AUTH_BOND)) {
174             log::debug("Non bonding: No keys will be exchanged");
175             p_cb->local_i_key = 0;
176             p_cb->local_r_key = 0;
177           }
178 
179           log::debug(
180                   "Remote request IO capabilities precondition "
181                   "auth_req:0x{:02x},io_cap:{} loc_oob_flag:{} loc_enc_size:{}, "
182                   "local_i_key:0x{:02x}, local_r_key:0x{:02x}",
183                   p_cb->loc_auth_req, p_cb->local_io_capability, p_cb->loc_oob_flag,
184                   p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key);
185 
186           p_cb->sc_only_mode_locally_required =
187                   (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false;
188           /* just for PTS, force SC bit */
189           if (p_cb->sc_only_mode_locally_required) {
190             p_cb->loc_auth_req |= SMP_SC_SUPPORT_BIT;
191           }
192 
193           if (!get_btm_client_interface().peer.BTM_ReadRemoteVersion(
194                       p_cb->pairing_bda, &remote_lmp_version, nullptr, nullptr)) {
195             log::warn("SMP Unable to determine remote_lmp_version:{}", remote_lmp_version);
196           }
197 
198           if (!p_cb->sc_only_mode_locally_required &&
199               (!(p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) ||
200                (remote_lmp_version && remote_lmp_version < HCI_PROTO_VERSION_4_2) ||
201                interop_match_addr(INTEROP_DISABLE_LE_SECURE_CONNECTIONS,
202                                   (const RawAddress*)&p_cb->pairing_bda))) {
203             log::debug(
204                     "Setting SC, H7 and LinkKey bits to false to support legacy "
205                     "device with lmp version:{}",
206                     remote_lmp_version);
207             p_cb->loc_auth_req &= ~SMP_SC_SUPPORT_BIT;
208             p_cb->loc_auth_req &= ~SMP_KP_SUPPORT_BIT;
209             p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
210             p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
211           }
212 
213           if (remote_lmp_version && remote_lmp_version < HCI_PROTO_VERSION_5_0) {
214             p_cb->loc_auth_req &= ~SMP_H7_SUPPORT_BIT;
215           }
216 
217           log::debug(
218                   "Remote request IO capabilities postcondition "
219                   "auth_req:0x{:02x},local_i_key:0x{:02x}, local_r_key:0x{:02x}",
220                   p_cb->loc_auth_req, p_cb->local_i_key, p_cb->local_r_key);
221 
222           smp_sm_event(p_cb, SMP_IO_RSP_EVT, NULL);
223           break;
224 
225         case SMP_BR_KEYS_REQ_EVT:
226           p_cb->loc_enc_size = cb_data.io_req.max_key_size;
227           p_cb->local_i_key = cb_data.io_req.init_keys;
228           p_cb->local_r_key = cb_data.io_req.resp_keys;
229           p_cb->loc_auth_req |= SMP_H7_SUPPORT_BIT;
230 
231           p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
232           p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
233 
234           log::debug(
235                   "for SMP over BR max_key_size:0x{:02x}, local_i_key:0x{:02x}, "
236                   "local_r_key:0x{:02x}, p_cb->loc_auth_req:0x{:02x}",
237                   p_cb->loc_enc_size, p_cb->local_i_key, p_cb->local_r_key, p_cb->loc_auth_req);
238 
239           smp_br_state_machine_event(p_cb, SMP_BR_KEYS_RSP_EVT, NULL);
240           break;
241 
242         // Expected, but nothing to do
243         case SMP_NC_REQ_EVT:
244         case SMP_SC_OOB_REQ_EVT:
245         case SMP_SC_LOC_OOB_DATA_UP_EVT:
246         case SMP_LE_ADDR_ASSOC_EVT:
247           break;
248 
249         default:
250           log::error("Unexpected event:{}", p_cb->cb_evt);
251       }
252     }
253   }
254 
255   if (!p_cb->cb_evt && p_cb->discard_sec_req) {
256     p_cb->discard_sec_req = false;
257     smp_sm_event(p_cb, SMP_DISCARD_SEC_REQ_EVT, NULL);
258   }
259 }
260 
261 /*******************************************************************************
262  * Function     smp_send_pair_fail
263  * Description  pairing failure to peer device if needed.
264  ******************************************************************************/
smp_send_pair_fail(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)265 void smp_send_pair_fail(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
266   p_cb->status = p_data->status;
267   p_cb->failure = p_data->status;
268 
269   if (p_cb->status <= SMP_MAX_FAIL_RSN_PER_SPEC && p_cb->status != SMP_SUCCESS) {
270     log::error("Pairing failed smp_status:{}", smp_status_text(p_cb->status));
271     BTM_LogHistory(kBtmLogTag, p_cb->pairing_bda, "Pairing failed",
272                    base::StringPrintf("smp_status:%s", smp_status_text(p_cb->status).c_str()));
273     smp_send_cmd(SMP_OPCODE_PAIRING_FAILED, p_cb);
274     p_cb->wait_for_authorization_complete = true;
275   }
276 }
277 
278 /*******************************************************************************
279  * Function     smp_send_pair_req
280  * Description  actions related to sending pairing request
281  ******************************************************************************/
smp_send_pair_req(tSMP_CB * p_cb,tSMP_INT_DATA *)282 void smp_send_pair_req(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
283   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
284   log::verbose("addr:{}", p_cb->pairing_bda);
285 
286   /* erase all keys when central sends pairing req*/
287   if (p_dev_rec) {
288     btm_sec_clear_ble_keys(p_dev_rec);
289   }
290   /* do not manipulate the key, let app decide,
291      leave out to BTM to mandate key distribution for bonding case */
292   smp_send_cmd(SMP_OPCODE_PAIRING_REQ, p_cb);
293 }
294 
295 /*******************************************************************************
296  * Function     smp_send_pair_rsp
297  * Description  actions related to sending pairing response
298  ******************************************************************************/
smp_send_pair_rsp(tSMP_CB * p_cb,tSMP_INT_DATA *)299 void smp_send_pair_rsp(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
300   log::verbose("addr:{}", p_cb->pairing_bda);
301 
302   p_cb->local_i_key &= p_cb->peer_i_key;
303   p_cb->local_r_key &= p_cb->peer_r_key;
304 
305   if (smp_send_cmd(SMP_OPCODE_PAIRING_RSP, p_cb)) {
306     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
307       smp_use_oob_private_key(p_cb, NULL);
308     } else {
309       smp_decide_association_model(p_cb, NULL);
310     }
311   }
312 }
313 
314 /*******************************************************************************
315  * Function     smp_send_confirm
316  * Description  send confirmation to the peer
317  ******************************************************************************/
smp_send_confirm(tSMP_CB * p_cb,tSMP_INT_DATA *)318 void smp_send_confirm(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
319   log::verbose("addr:{}", p_cb->pairing_bda);
320   smp_send_cmd(SMP_OPCODE_CONFIRM, p_cb);
321   p_cb->flags |= SMP_PAIR_FLAGS_CMD_CONFIRM_SENT;
322 }
323 
324 /*******************************************************************************
325  * Function     smp_send_rand
326  * Description  send pairing random to the peer
327  ******************************************************************************/
smp_send_rand(tSMP_CB * p_cb,tSMP_INT_DATA *)328 void smp_send_rand(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
329   log::verbose("addr:{}", p_cb->pairing_bda);
330   smp_send_cmd(SMP_OPCODE_RAND, p_cb);
331 }
332 
333 /*******************************************************************************
334  * Function     smp_send_pair_public_key
335  * Description  send pairing public key command to the peer
336  ******************************************************************************/
smp_send_pair_public_key(tSMP_CB * p_cb,tSMP_INT_DATA *)337 void smp_send_pair_public_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
338   log::verbose("addr:{}", p_cb->pairing_bda);
339   smp_send_cmd(SMP_OPCODE_PAIR_PUBLIC_KEY, p_cb);
340 }
341 
342 /*******************************************************************************
343  * Function     SMP_SEND_COMMITMENT
344  * Description send commitment command to the peer
345  ******************************************************************************/
smp_send_commitment(tSMP_CB * p_cb,tSMP_INT_DATA *)346 void smp_send_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
347   log::verbose("addr:{}", p_cb->pairing_bda);
348   smp_send_cmd(SMP_OPCODE_PAIR_COMMITM, p_cb);
349 }
350 
351 /*******************************************************************************
352  * Function     smp_send_dhkey_check
353  * Description send DHKey Check command to the peer
354  ******************************************************************************/
smp_send_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA *)355 void smp_send_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
356   log::verbose("addr:{}", p_cb->pairing_bda);
357   smp_send_cmd(SMP_OPCODE_PAIR_DHKEY_CHECK, p_cb);
358 }
359 
360 /*******************************************************************************
361  * Function     smp_send_keypress_notification
362  * Description send Keypress Notification command to the peer
363  ******************************************************************************/
smp_send_keypress_notification(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)364 void smp_send_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
365   p_cb->local_keypress_notification = p_data->status;
366   smp_send_cmd(SMP_OPCODE_PAIR_KEYPR_NOTIF, p_cb);
367 }
368 
369 /*******************************************************************************
370  * Function     smp_send_enc_info
371  * Description  send encryption information command.
372  ******************************************************************************/
smp_send_enc_info(tSMP_CB * p_cb,tSMP_INT_DATA *)373 void smp_send_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
374   log::verbose("p_cb->loc_enc_size={}", p_cb->loc_enc_size);
375   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, false);
376 
377   smp_send_cmd(SMP_OPCODE_ENCRYPT_INFO, p_cb);
378   smp_send_cmd(SMP_OPCODE_CENTRAL_ID, p_cb);
379 
380   /* save the DIV and key size information when acting as peripheral device */
381   tBTM_LE_KEY_VALUE le_key = {
382           .lenc_key =
383                   {
384                           .ltk = p_cb->ltk,
385                           .div = p_cb->div,
386                           .key_size = p_cb->loc_enc_size,
387                           .sec_level = p_cb->sec_level,
388                   },
389   };
390 
391   if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) {
392     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LENC, &le_key, true);
393   }
394   smp_key_distribution(p_cb, NULL);
395 }
396 
397 /*******************************************************************************
398  * Function     smp_send_id_info
399  * Description  send ID information command.
400  ******************************************************************************/
smp_send_id_info(tSMP_CB * p_cb,tSMP_INT_DATA *)401 void smp_send_id_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
402   log::verbose("addr:{}", p_cb->pairing_bda);
403   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ID, false);
404 
405   smp_send_cmd(SMP_OPCODE_IDENTITY_INFO, p_cb);
406   smp_send_cmd(SMP_OPCODE_ID_ADDR, p_cb);
407 
408   if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) {
409     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LID, nullptr, true);
410   }
411 
412   smp_key_distribution_by_transport(p_cb, NULL);
413 }
414 
415 /**  send CSRK command. */
smp_send_csrk_info(tSMP_CB * p_cb,tSMP_INT_DATA *)416 void smp_send_csrk_info(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
417   log::verbose("addr:{}", p_cb->pairing_bda);
418   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_CSRK, false);
419 
420   if (smp_send_cmd(SMP_OPCODE_SIGN_INFO, p_cb)) {
421     tBTM_LE_KEY_VALUE key = {
422             .lcsrk_key =
423                     {
424                             .counter = 0, /* initialize the local counter */
425                             .div = p_cb->div,
426                             .sec_level = p_cb->sec_level,
427                             .csrk = p_cb->csrk,
428                     },
429     };
430     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_LCSRK, &key, true);
431   }
432 
433   smp_key_distribution_by_transport(p_cb, NULL);
434 }
435 
436 /*******************************************************************************
437  * Function     smp_send_ltk_reply
438  * Description  send LTK reply
439  ******************************************************************************/
smp_send_ltk_reply(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)440 void smp_send_ltk_reply(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
441   log::verbose("addr:{}", p_cb->pairing_bda);
442 
443   Octet16 stk;
444   memcpy(stk.data(), p_data->key.p_data, stk.size());
445   /* send stk as LTK response */
446   btm_ble_ltk_request_reply(p_cb->pairing_bda, true, stk);
447 }
448 
449 /*******************************************************************************
450  * Function     smp_proc_sec_req
451  * Description  process security request.
452  ******************************************************************************/
smp_proc_sec_req(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)453 void smp_proc_sec_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
454   if (smp_command_has_invalid_length(p_cb)) {
455     tSMP_INT_DATA smp_int_data;
456     smp_int_data.status = SMP_INVALID_PARAMETERS;
457     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
458     return;
459   }
460 
461   tBTM_LE_AUTH_REQ auth_req = *(tBTM_LE_AUTH_REQ*)p_data->p_data;
462   tBTM_BLE_SEC_REQ_ACT sec_req_act;
463 
464   log::verbose("auth_req=0x{:x}", auth_req);
465 
466   p_cb->cb_evt = SMP_EVT_NONE;
467 
468   btm_ble_link_sec_check(p_cb->pairing_bda, auth_req, &sec_req_act);
469 
470   log::verbose("sec_req_act={}", sec_req_act);
471 
472   switch (sec_req_act) {
473     case BTM_BLE_SEC_REQ_ACT_ENCRYPT:
474       log::verbose("BTM_BLE_SEC_REQ_ACT_ENCRYPT");
475       smp_sm_event(p_cb, SMP_ENC_REQ_EVT, NULL);
476       break;
477 
478     case BTM_BLE_SEC_REQ_ACT_PAIR:
479       p_cb->sc_only_mode_locally_required =
480               (p_cb->init_security_mode == BTM_SEC_MODE_SC) ? true : false;
481 
482       /* respond to non SC pairing request as failure in SC only mode */
483       if (p_cb->sc_only_mode_locally_required && (auth_req & SMP_SC_SUPPORT_BIT) == 0) {
484         tSMP_INT_DATA smp_int_data;
485         smp_int_data.status = SMP_PAIR_AUTH_FAIL;
486         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
487       } else {
488         /* initialize local i/r key to be default keys */
489         p_cb->peer_auth_req = auth_req;
490         p_cb->local_r_key = p_cb->local_i_key = SMP_SEC_DEFAULT_KEY;
491         p_cb->cb_evt = SMP_SEC_REQUEST_EVT;
492       }
493       break;
494 
495     case BTM_BLE_SEC_REQ_ACT_DISCARD:
496       p_cb->discard_sec_req = true;
497       break;
498 
499     default:
500       /* do nothing */
501       break;
502   }
503 }
504 
505 /*******************************************************************************
506  * Function     smp_proc_sec_grant
507  * Description  process security grant.
508  ******************************************************************************/
smp_proc_sec_grant(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)509 void smp_proc_sec_grant(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
510   uint8_t res = p_data->status;
511   log::verbose("addr:{}", p_cb->pairing_bda);
512   if (res != SMP_SUCCESS) {
513     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, p_data);
514   } else /*otherwise, start pairing */
515   {
516     /* send IO request callback */
517     p_cb->cb_evt = SMP_IO_CAP_REQ_EVT;
518   }
519 }
520 
521 /*******************************************************************************
522  * Function     smp_proc_pair_fail
523  * Description  process pairing failure from peer device
524  ******************************************************************************/
smp_proc_pair_fail(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)525 void smp_proc_pair_fail(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
526   log::verbose("addr:{}", p_cb->pairing_bda);
527 
528   if (p_cb->rcvd_cmd_len < 2) {
529     log::warn("rcvd_cmd_len {} too short: must be at least 2", p_cb->rcvd_cmd_len);
530     p_cb->status = SMP_INVALID_PARAMETERS;
531   } else {
532     p_cb->status = static_cast<tSMP_STATUS>(p_data->p_data[0]);
533   }
534 
535   /* Cancel pending auth complete timer if set */
536   alarm_cancel(p_cb->delayed_auth_timer_ent);
537 }
538 
539 /*******************************************************************************
540  * Function     smp_proc_pair_cmd
541  * Description  Process the SMP pairing request/response from peer device
542  ******************************************************************************/
smp_proc_pair_cmd(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)543 void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
544   uint8_t* p = p_data->p_data;
545   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
546 
547   log::verbose("pairing_bda={}", p_cb->pairing_bda);
548 
549   /* erase all keys if it is peripheral proc pairing req */
550   if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) {
551     btm_sec_clear_ble_keys(p_dev_rec);
552   }
553 
554   p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR;
555 
556   if (smp_command_has_invalid_length(p_cb)) {
557     tSMP_INT_DATA smp_int_data;
558     smp_int_data.status = SMP_INVALID_PARAMETERS;
559     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
560     return;
561   }
562 
563   STREAM_TO_UINT8(p_cb->peer_io_caps, p);
564   STREAM_TO_UINT8(p_cb->peer_oob_flag, p);
565   STREAM_TO_UINT8(p_cb->peer_auth_req, p);
566   STREAM_TO_UINT8(p_cb->peer_enc_size, p);
567   STREAM_TO_UINT8(p_cb->peer_i_key, p);
568   STREAM_TO_UINT8(p_cb->peer_r_key, p);
569 
570   tSMP_STATUS reason = p_cb->cert_failure;
571   if (reason == SMP_ENC_KEY_SIZE) {
572     tSMP_INT_DATA smp_int_data;
573     smp_int_data.status = reason;
574     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
575     return;
576   }
577 
578   if (smp_command_has_invalid_parameters(p_cb)) {
579     tSMP_INT_DATA smp_int_data;
580     smp_int_data.status = SMP_INVALID_PARAMETERS;
581     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
582     return;
583   }
584 
585   // PTS Testing failure modes
586   if (pts_test_send_authentication_complete_failure(p_cb)) {
587     return;
588   }
589 
590   if (p_cb->role == HCI_ROLE_PERIPHERAL) {
591     if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) {
592       /* peer (central) started pairing sending Pairing Request */
593       p_cb->local_i_key = p_cb->peer_i_key;
594       p_cb->local_r_key = p_cb->peer_r_key;
595 
596       p_cb->cb_evt = SMP_IO_CAP_REQ_EVT;
597     } else /* update local i/r key according to pairing request */
598     {
599       /* pairing started with this side (peripheral) sending Security Request */
600       p_cb->local_i_key &= p_cb->peer_i_key;
601       p_cb->local_r_key &= p_cb->peer_r_key;
602       p_cb->selected_association_model = smp_select_association_model(p_cb);
603 
604       if (p_cb->sc_only_mode_locally_required &&
605           (!(p_cb->sc_mode_required_by_peer) ||
606            (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) {
607         log::error("pairing failed - peripheral requires secure connection only mode");
608         tSMP_INT_DATA smp_int_data;
609         smp_int_data.status = SMP_PAIR_AUTH_FAIL;
610         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
611         return;
612       }
613 
614       if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
615         if (smp_request_oob_data(p_cb)) {
616           return;
617         }
618       } else {
619         smp_send_pair_rsp(p_cb, NULL);
620       }
621     }
622   } else /* Central receives pairing response */
623   {
624     p_cb->selected_association_model = smp_select_association_model(p_cb);
625 
626     if (p_cb->sc_only_mode_locally_required &&
627         (!(p_cb->sc_mode_required_by_peer) ||
628          (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) {
629       log::error(
630               "Central requires secure connection only mode but it can't be "
631               "provided -> Central fails pairing");
632       tSMP_INT_DATA smp_int_data;
633       smp_int_data.status = SMP_PAIR_AUTH_FAIL;
634       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
635       return;
636     }
637 
638     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
639       if (smp_request_oob_data(p_cb)) {
640         return;
641       }
642     } else {
643       smp_decide_association_model(p_cb, NULL);
644     }
645   }
646 }
647 
648 /** process pairing confirm from peer device */
smp_proc_confirm(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)649 void smp_proc_confirm(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
650   log::verbose("pairing_bda={}", p_cb->pairing_bda);
651 
652   if (smp_command_has_invalid_parameters(p_cb)) {
653     tSMP_INT_DATA smp_int_data;
654     smp_int_data.status = SMP_INVALID_PARAMETERS;
655     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
656     return;
657   }
658 
659   if (p_data) {
660     uint8_t* p = p_data->p_data;
661     if (p != NULL) {
662       /* save the SConfirm for comparison later */
663       STREAM_TO_ARRAY(p_cb->rconfirm.data(), p, OCTET16_LEN);
664     }
665   }
666 
667   p_cb->flags |= SMP_PAIR_FLAGS_CMD_CONFIRM_RCVD;
668 }
669 
670 /*******************************************************************************
671  * Function     smp_proc_rand
672  * Description  process pairing random (nonce) from peer device
673  ******************************************************************************/
smp_proc_rand(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)674 void smp_proc_rand(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
675   uint8_t* p = p_data->p_data;
676 
677   log::verbose("pairing_bda={}", p_cb->pairing_bda);
678 
679   if (smp_command_has_invalid_parameters(p_cb)) {
680     tSMP_INT_DATA smp_int_data;
681     smp_int_data.status = SMP_INVALID_PARAMETERS;
682     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
683     return;
684   }
685 
686   if (!((p_cb->loc_auth_req & SMP_SC_SUPPORT_BIT) && (p_cb->peer_auth_req & SMP_SC_SUPPORT_BIT)) &&
687       !(p_cb->flags & SMP_PAIR_FLAGS_CMD_CONFIRM_SENT)) {
688     // in legacy pairing, the peer should send its rand after
689     // we send our confirm
690     tSMP_INT_DATA smp_int_data{};
691     smp_int_data.status = SMP_INVALID_PARAMETERS;
692     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
693     return;
694   }
695 
696   /* save the SRand for comparison */
697   STREAM_TO_ARRAY(p_cb->rrand.data(), p, OCTET16_LEN);
698 }
699 
700 /*******************************************************************************
701  * Function     smp_process_pairing_public_key
702  * Description  process pairing public key command from the peer device
703  *              - saves the peer public key;
704  *              - sets the flag indicating that the peer public key is received;
705  *              - calls smp_wait_for_both_public_keys(...).
706  *
707  ******************************************************************************/
smp_process_pairing_public_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)708 void smp_process_pairing_public_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
709   uint8_t* p = p_data->p_data;
710 
711   log::verbose("addr:{}", p_cb->pairing_bda);
712 
713   if (smp_command_has_invalid_parameters(p_cb)) {
714     tSMP_INT_DATA smp_int_data;
715     smp_int_data.status = SMP_INVALID_PARAMETERS;
716     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
717     return;
718   }
719 
720   STREAM_TO_ARRAY(p_cb->peer_publ_key.x, p, BT_OCTET32_LEN);
721   STREAM_TO_ARRAY(p_cb->peer_publ_key.y, p, BT_OCTET32_LEN);
722 
723   Point pt;
724   memcpy(pt.x, p_cb->peer_publ_key.x, BT_OCTET32_LEN);
725   memcpy(pt.y, p_cb->peer_publ_key.y, BT_OCTET32_LEN);
726 
727   if (!memcmp(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, BT_OCTET32_LEN)) {
728     log::warn("Remote and local public keys can't match");
729     tSMP_INT_DATA smp;
730     smp.status = SMP_PAIR_AUTH_FAIL;
731     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp);
732     return;
733   }
734 
735   if (!ECC_ValidatePoint(pt)) {
736     tSMP_INT_DATA smp;
737     smp.status = SMP_PAIR_AUTH_FAIL;
738     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp);
739     return;
740   }
741 
742   p_cb->flags |= SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY;
743 
744   smp_wait_for_both_public_keys(p_cb, NULL);
745 }
746 
747 /*******************************************************************************
748  * Function     smp_process_pairing_commitment
749  * Description  process pairing commitment from peer device
750  ******************************************************************************/
smp_process_pairing_commitment(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)751 void smp_process_pairing_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
752   uint8_t* p = p_data->p_data;
753 
754   log::verbose("addr:{}", p_cb->pairing_bda);
755 
756   if (smp_command_has_invalid_parameters(p_cb)) {
757     tSMP_INT_DATA smp_int_data;
758     smp_int_data.status = SMP_INVALID_PARAMETERS;
759     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
760     return;
761   }
762 
763   p_cb->flags |= SMP_PAIR_FLAG_HAVE_PEER_COMM;
764 
765   if (p != NULL) {
766     STREAM_TO_ARRAY(p_cb->remote_commitment.data(), p, OCTET16_LEN);
767   }
768 }
769 
770 /*******************************************************************************
771  * Function     smp_process_dhkey_check
772  * Description  process DHKey Check from peer device
773  ******************************************************************************/
smp_process_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)774 void smp_process_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
775   uint8_t* p = p_data->p_data;
776 
777   log::verbose("addr:{}", p_cb->pairing_bda);
778 
779   if (smp_command_has_invalid_parameters(p_cb)) {
780     tSMP_INT_DATA smp_int_data;
781     smp_int_data.status = SMP_INVALID_PARAMETERS;
782     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
783     return;
784   }
785 
786   if (p != NULL) {
787     STREAM_TO_ARRAY(p_cb->remote_dhkey_check.data(), p, OCTET16_LEN);
788   }
789 
790   p_cb->flags |= SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK;
791 }
792 
793 /*******************************************************************************
794  * Function     smp_process_keypress_notification
795  * Description  process pairing keypress notification from peer device
796  ******************************************************************************/
smp_process_keypress_notification(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)797 void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
798   uint8_t* p = p_data->p_data;
799 
800   log::verbose("addr:{}", p_cb->pairing_bda);
801   p_cb->status = p_data->status;
802 
803   if (smp_command_has_invalid_parameters(p_cb)) {
804     tSMP_INT_DATA smp_int_data;
805     smp_int_data.status = SMP_INVALID_PARAMETERS;
806     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
807     return;
808   }
809 
810   if (p != NULL) {
811     STREAM_TO_UINT8(p_cb->peer_keypress_notification, p);
812   } else {
813     p_cb->peer_keypress_notification = SMP_SC_KEY_OUT_OF_RANGE;
814   }
815   p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT;
816 }
817 
818 /*******************************************************************************
819  * Function     smp_br_process_pairing_command
820  * Description  Process the SMP pairing request/response from peer device via
821  *              BR/EDR transport.
822  ******************************************************************************/
smp_br_process_pairing_command(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)823 void smp_br_process_pairing_command(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
824   uint8_t* p = p_data->p_data;
825   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
826 
827   log::verbose("addr:{}", p_cb->pairing_bda);
828   /* rejecting BR pairing request over non-SC BR link */
829   if (!p_dev_rec->sec_rec.new_encryption_key_is_p256 && p_cb->role == HCI_ROLE_PERIPHERAL) {
830     tSMP_INT_DATA smp_int_data;
831     smp_int_data.status = SMP_XTRANS_DERIVE_NOT_ALLOW;
832     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
833     return;
834   }
835 
836   /* erase all keys if it is peripheral proc pairing req*/
837   if (p_dev_rec && (p_cb->role == HCI_ROLE_PERIPHERAL)) {
838     btm_sec_clear_ble_keys(p_dev_rec);
839   }
840 
841   p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR;
842 
843   if (smp_command_has_invalid_length(p_cb)) {
844     tSMP_INT_DATA smp_int_data;
845     smp_int_data.status = SMP_INVALID_PARAMETERS;
846     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
847     return;
848   }
849 
850   STREAM_TO_UINT8(p_cb->peer_io_caps, p);
851   STREAM_TO_UINT8(p_cb->peer_oob_flag, p);
852   STREAM_TO_UINT8(p_cb->peer_auth_req, p);
853   STREAM_TO_UINT8(p_cb->peer_enc_size, p);
854   STREAM_TO_UINT8(p_cb->peer_i_key, p);
855   STREAM_TO_UINT8(p_cb->peer_r_key, p);
856 
857   if (smp_command_has_invalid_parameters(p_cb)) {
858     tSMP_INT_DATA smp_int_data;
859     smp_int_data.status = SMP_INVALID_PARAMETERS;
860     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
861     return;
862   }
863 
864   /* peer (central) started pairing sending Pairing Request */
865   /* or being central device always use received i/r key as keys to distribute
866    */
867   p_cb->local_i_key = p_cb->peer_i_key;
868   p_cb->local_r_key = p_cb->peer_r_key;
869 
870   if (p_cb->role == HCI_ROLE_PERIPHERAL) {
871     p_dev_rec->sec_rec.new_encryption_key_is_p256 = false;
872     /* shortcut to skip Security Grant step */
873     p_cb->cb_evt = SMP_BR_KEYS_REQ_EVT;
874   } else {
875     /* Central receives pairing response */
876     log::verbose(
877             "central rcvs valid PAIRING RESPONSE. Supposed to move to key distribution phase.");
878   }
879 
880   /* auth_req received via BR/EDR SM channel is set to 0,
881      but everything derived/exchanged has to be saved */
882   p_cb->peer_auth_req |= SMP_AUTH_BOND;
883   p_cb->loc_auth_req |= SMP_AUTH_BOND;
884 }
885 
886 /*******************************************************************************
887  * Function     smp_br_process_security_grant
888  * Description  process security grant in case of pairing over BR/EDR transport.
889  ******************************************************************************/
smp_br_process_security_grant(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)890 void smp_br_process_security_grant(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
891   log::verbose("addr:{}", p_cb->pairing_bda);
892   if (p_data->status != SMP_SUCCESS) {
893     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, p_data);
894   } else {
895     /* otherwise, start pairing; send IO request callback */
896     p_cb->cb_evt = SMP_BR_KEYS_REQ_EVT;
897   }
898 }
899 
900 /*******************************************************************************
901  * Function     smp_br_check_authorization_request
902  * Description  sets the SMP kes to be derived/distribute over BR/EDR transport
903  *              before starting the distribution/derivation
904  ******************************************************************************/
smp_br_check_authorization_request(tSMP_CB * p_cb,tSMP_INT_DATA *)905 void smp_br_check_authorization_request(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
906   log::verbose("rcvs i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)", p_cb->local_i_key,
907                p_cb->local_r_key);
908 
909   /* In LE SC mode LK field is ignored when BR/EDR transport is used */
910   p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
911   p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
912 
913   /* In LE SC mode only IRK, IAI, CSRK are exchanged with the peer.
914   ** Set local_r_key on central to expect only these keys. */
915   if (p_cb->role == HCI_ROLE_CENTRAL) {
916     p_cb->local_r_key &= (SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK);
917   }
918 
919   /* Check if H7 function needs to be used for key derivation*/
920   if ((p_cb->loc_auth_req & SMP_H7_SUPPORT_BIT) && (p_cb->peer_auth_req & SMP_H7_SUPPORT_BIT)) {
921     p_cb->key_derivation_h7_used = TRUE;
922   }
923   log::verbose("use h7={}, i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)",
924                p_cb->key_derivation_h7_used, p_cb->local_i_key, p_cb->local_r_key);
925 
926   if (/*((p_cb->peer_auth_req & SMP_AUTH_BOND) ||
927           (p_cb->loc_auth_req & SMP_AUTH_BOND)) &&*/
928       p_cb->local_i_key || p_cb->local_r_key) {
929     smp_br_state_machine_event(p_cb, SMP_BR_BOND_REQ_EVT, NULL);
930 
931     /* if no peer key is expected, start central key distribution */
932     if (p_cb->role == HCI_ROLE_CENTRAL && p_cb->local_r_key == 0) {
933       smp_key_distribution_by_transport(p_cb, NULL);
934     }
935   } else {
936     tSMP_INT_DATA smp_int_data;
937     smp_int_data.status = SMP_SUCCESS;
938     smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
939   }
940 }
941 
942 /*******************************************************************************
943  * Function     smp_br_select_next_key
944  * Description  selects the next key to derive/send when BR/EDR transport is
945  *              used.
946  ******************************************************************************/
smp_br_select_next_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)947 void smp_br_select_next_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
948   log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, p_cb->local_r_key,
949                p_cb->local_i_key);
950 
951   if (p_cb->role == HCI_ROLE_PERIPHERAL || (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) {
952     smp_key_pick_key(p_cb, p_data);
953   }
954 
955   if (!p_cb->local_i_key && !p_cb->local_r_key) {
956     /* state check to prevent re-entrance */
957     if (smp_get_br_state() == SMP_BR_STATE_BOND_PENDING) {
958       if (p_cb->total_tx_unacked == 0) {
959         tSMP_INT_DATA smp_int_data;
960         smp_int_data.status = SMP_SUCCESS;
961         smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
962       } else {
963         p_cb->wait_for_authorization_complete = true;
964       }
965     }
966   }
967 }
968 
969 /** process encryption information from peer device */
smp_proc_enc_info(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)970 void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
971   uint8_t* p = p_data->p_data;
972 
973   log::verbose("addr:{}", p_cb->pairing_bda);
974 
975   if (smp_command_has_invalid_parameters(p_cb)) {
976     tSMP_INT_DATA smp_int_data;
977     smp_int_data.status = SMP_INVALID_PARAMETERS;
978     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
979     return;
980   }
981 
982   STREAM_TO_ARRAY(p_cb->ltk.data(), p, OCTET16_LEN);
983 
984   smp_key_distribution(p_cb, NULL);
985 }
986 
987 /** process central ID from peripheral device */
smp_proc_central_id(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)988 void smp_proc_central_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
989   uint8_t* p = p_data->p_data;
990 
991   log::verbose("addr:{}", p_cb->pairing_bda);
992 
993   if (p_cb->rcvd_cmd_len < 11) {  // 1(Code) + 2(EDIV) + 8(Rand)
994     log::error("Invalid command length:{}, should be at least 11", p_cb->rcvd_cmd_len);
995     return;
996   }
997 
998   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true);
999 
1000   tBTM_LE_KEY_VALUE le_key = {
1001           .penc_key = {},
1002   };
1003   STREAM_TO_UINT16(le_key.penc_key.ediv, p);
1004   STREAM_TO_ARRAY(le_key.penc_key.rand, p, BT_OCTET8_LEN);
1005 
1006   /* store the encryption keys from peer device */
1007   le_key.penc_key.ltk = p_cb->ltk;
1008   le_key.penc_key.sec_level = p_cb->sec_level;
1009   le_key.penc_key.key_size = p_cb->loc_enc_size;
1010 
1011   if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) {
1012     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, &le_key, true);
1013   }
1014 
1015   smp_key_distribution(p_cb, NULL);
1016 }
1017 
1018 /** process identity information from peer device */
smp_proc_id_info(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1019 void smp_proc_id_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1020   uint8_t* p = p_data->p_data;
1021 
1022   log::verbose("addr:{}", p_cb->pairing_bda);
1023 
1024   if (smp_command_has_invalid_parameters(p_cb)) {
1025     tSMP_INT_DATA smp_int_data;
1026     smp_int_data.status = SMP_INVALID_PARAMETERS;
1027     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1028     return;
1029   }
1030 
1031   STREAM_TO_ARRAY(p_cb->tk.data(), p, OCTET16_LEN); /* reuse TK for IRK */
1032   smp_key_distribution_by_transport(p_cb, NULL);
1033 }
1034 
1035 /** process identity address from peer device */
smp_proc_id_addr(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1036 void smp_proc_id_addr(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1037   const uint8_t* p = p_data->p_data;
1038 
1039   log::verbose("addr:{}", p_cb->pairing_bda);
1040 
1041   if (smp_command_has_invalid_parameters(p_cb)) {
1042     tSMP_INT_DATA smp_int_data;
1043     smp_int_data.status = SMP_INVALID_PARAMETERS;
1044     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1045     return;
1046   }
1047 
1048   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ID, true);
1049 
1050   tBTM_LE_KEY_VALUE pid_key = {
1051           .pid_key = {},
1052   };
1053 
1054   STREAM_TO_UINT8(pid_key.pid_key.identity_addr_type, p);
1055   STREAM_TO_BDADDR(pid_key.pid_key.identity_addr, p);
1056   pid_key.pid_key.irk = p_cb->tk;
1057 
1058   /* to use as BD_ADDR for lk derived from ltk */
1059   p_cb->id_addr_rcvd = true;
1060   p_cb->id_addr_type = pid_key.pid_key.identity_addr_type;
1061   p_cb->id_addr = pid_key.pid_key.identity_addr;
1062 
1063   /* store the ID key from peer device */
1064   if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) {
1065     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PID, &pid_key, true);
1066     p_cb->cb_evt = SMP_LE_ADDR_ASSOC_EVT;
1067     smp_send_app_cback(p_cb, NULL);
1068   }
1069   smp_key_distribution_by_transport(p_cb, NULL);
1070 }
1071 
1072 /* process security information from peer device */
smp_proc_srk_info(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1073 void smp_proc_srk_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1074   log::verbose("addr:{}", p_cb->pairing_bda);
1075 
1076   if (smp_command_has_invalid_parameters(p_cb)) {
1077     tSMP_INT_DATA smp_int_data;
1078     smp_int_data.status = SMP_INVALID_PARAMETERS;
1079     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1080     return;
1081   }
1082 
1083   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_CSRK, true);
1084 
1085   if (com::android::bluetooth::flags::save_peer_csrk_after_ltk_gen()) {
1086     smp_key_distribution_by_transport(p_cb, NULL);
1087   }
1088 
1089   /* save CSRK to security record */
1090   tBTM_LE_KEY_VALUE le_key = {
1091           .pcsrk_key =
1092                   {
1093                           .sec_level = p_cb->sec_level,
1094                   },
1095   };
1096 
1097   /* get peer CSRK */
1098   maybe_non_aligned_memcpy(le_key.pcsrk_key.csrk.data(), p_data->p_data, OCTET16_LEN);
1099 
1100   /* initialize the peer counter */
1101   le_key.pcsrk_key.counter = 0;
1102 
1103   if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) {
1104     btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PCSRK, &le_key, true);
1105   }
1106 
1107   if (!com::android::bluetooth::flags::save_peer_csrk_after_ltk_gen()) {
1108     smp_key_distribution_by_transport(p_cb, NULL);
1109   }
1110 }
1111 
1112 /*******************************************************************************
1113  * Function     smp_proc_compare
1114  * Description  process compare value
1115  ******************************************************************************/
smp_proc_compare(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1116 void smp_proc_compare(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1117   log::verbose("addr:{}", p_cb->pairing_bda);
1118   if (!memcmp(p_cb->rconfirm.data(), p_data->key.p_data, OCTET16_LEN)) {
1119     /* compare the max encryption key size, and save the smaller one for the
1120      * link */
1121     if (p_cb->peer_enc_size < p_cb->loc_enc_size) {
1122       p_cb->loc_enc_size = p_cb->peer_enc_size;
1123     }
1124 
1125     if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1126       smp_sm_event(p_cb, SMP_RAND_EVT, NULL);
1127     } else {
1128       /* central device always use received i/r key as keys to distribute */
1129       p_cb->local_i_key = p_cb->peer_i_key;
1130       p_cb->local_r_key = p_cb->peer_r_key;
1131 
1132       smp_sm_event(p_cb, SMP_ENC_REQ_EVT, NULL);
1133     }
1134 
1135   } else {
1136     tSMP_INT_DATA smp_int_data;
1137     smp_int_data.status = SMP_CONFIRM_VALUE_ERR;
1138     p_cb->failure = SMP_CONFIRM_VALUE_ERR;
1139     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1140   }
1141 }
1142 
1143 /*******************************************************************************
1144  * Function     smp_proc_sl_key
1145  * Description  process key ready events.
1146  ******************************************************************************/
smp_proc_sl_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1147 void smp_proc_sl_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1148   uint8_t key_type = p_data->key.key_type;
1149 
1150   log::verbose("addr:{}", p_cb->pairing_bda);
1151   if (key_type == SMP_KEY_TYPE_TK) {
1152     smp_generate_srand_mrand_confirm(p_cb, NULL);
1153   } else if (key_type == SMP_KEY_TYPE_CFM) {
1154     smp_set_state(SMP_STATE_WAIT_CONFIRM);
1155 
1156     if (p_cb->flags & SMP_PAIR_FLAGS_CMD_CONFIRM_RCVD) {
1157       smp_sm_event(p_cb, SMP_CONFIRM_EVT, NULL);
1158     }
1159   }
1160 }
1161 
1162 /*******************************************************************************
1163  * Function     smp_start_enc
1164  * Description  start encryption
1165  ******************************************************************************/
smp_start_enc(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1166 void smp_start_enc(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1167   tBTM_STATUS cmd;
1168 
1169   log::verbose("addr:{}", p_cb->pairing_bda);
1170   if (p_data != NULL) {
1171     cmd = btm_ble_start_encrypt(p_cb->pairing_bda, true, (Octet16*)p_data->key.p_data);
1172   } else {
1173     cmd = btm_ble_start_encrypt(p_cb->pairing_bda, false, NULL);
1174   }
1175 
1176   if (cmd != tBTM_STATUS::BTM_CMD_STARTED && cmd != tBTM_STATUS::BTM_BUSY) {
1177     tSMP_INT_DATA smp_int_data;
1178     smp_int_data.status = SMP_ENC_FAIL;
1179     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1180   }
1181 }
1182 
1183 /*******************************************************************************
1184  * Function     smp_proc_discard
1185  * Description   processing for discard security request
1186  ******************************************************************************/
smp_proc_discard(tSMP_CB * p_cb,tSMP_INT_DATA *)1187 void smp_proc_discard(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1188   log::verbose("addr:{}", p_cb->pairing_bda);
1189   if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) {
1190     smp_reset_control_value(p_cb);
1191   }
1192 }
1193 
1194 /*******************************************************************************
1195  * Function     smp_enc_cmpl
1196  * Description   encryption success
1197  ******************************************************************************/
smp_enc_cmpl(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1198 void smp_enc_cmpl(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1199   uint8_t enc_enable = p_data->status;
1200 
1201   log::verbose("addr:{}", p_cb->pairing_bda);
1202   tSMP_INT_DATA smp_int_data;
1203   smp_int_data.status = enc_enable ? SMP_SUCCESS : SMP_ENC_FAIL;
1204   smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1205 }
1206 
1207 /*******************************************************************************
1208  * Function     smp_sirk_verify
1209  * Description   verify if device belongs to csis group.
1210  ******************************************************************************/
smp_sirk_verify(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1211 void smp_sirk_verify(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1212   tBTM_STATUS callback_rc;
1213   log::debug("addr:{}", p_cb->pairing_bda);
1214 
1215   if (p_data->status != SMP_SUCCESS) {
1216     log::debug("Cancel device verification due to invalid status({}) while bonding.",
1217                p_data->status);
1218 
1219     tSMP_INT_DATA smp_int_data;
1220     smp_int_data.status = SMP_SIRK_DEVICE_INVALID;
1221 
1222     BTM_LogHistory(kBtmLogTag, p_cb->pairing_bda, "SIRK verification",
1223                    base::StringPrintf("Verification failed, smp_status:%s",
1224                                       smp_status_text(smp_int_data.status).c_str()));
1225 
1226     smp_sm_event(p_cb, SMP_SIRK_DEVICE_VALID_EVT, &smp_int_data);
1227 
1228     return;
1229   }
1230 
1231   if (p_cb->p_callback) {
1232     p_cb->cb_evt = SMP_SIRK_VERIFICATION_REQ_EVT;
1233     callback_rc = (*p_cb->p_callback)(p_cb->cb_evt, p_cb->pairing_bda, nullptr);
1234 
1235     /* There is no member validator callback - device is by default valid */
1236     if (callback_rc == tBTM_STATUS::BTM_SUCCESS_NO_SECURITY) {
1237       BTM_LogHistory(kBtmLogTag, p_cb->pairing_bda, "SIRK verification",
1238                      base::StringPrintf("Device validated due to no security"));
1239 
1240       tSMP_INT_DATA smp_int_data;
1241       smp_int_data.status = SMP_SUCCESS;
1242       smp_sm_event(p_cb, SMP_SIRK_DEVICE_VALID_EVT, &smp_int_data);
1243     }
1244   } else {
1245     log::error("There are no registrated callbacks for SMP");
1246   }
1247 }
1248 
1249 /*******************************************************************************
1250  * Function     smp_check_auth_req
1251  * Description  check authentication request
1252  ******************************************************************************/
smp_check_auth_req(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1253 void smp_check_auth_req(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1254   uint8_t enc_enable = p_data->status;
1255 
1256   log::verbose("rcvs enc_enable={} i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)",
1257                enc_enable, p_cb->local_i_key, p_cb->local_r_key);
1258   if (enc_enable == 1) {
1259     if (p_cb->sc_mode_required_by_peer) {
1260       /* In LE SC mode LTK is used instead of STK and has to be always saved */
1261       p_cb->local_i_key |= SMP_SEC_KEY_TYPE_ENC;
1262       p_cb->local_r_key |= SMP_SEC_KEY_TYPE_ENC;
1263 
1264       /* In LE SC mode LK is derived from LTK only if both sides request it */
1265       if (!(p_cb->local_i_key & SMP_SEC_KEY_TYPE_LK) ||
1266           !(p_cb->local_r_key & SMP_SEC_KEY_TYPE_LK)) {
1267         p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
1268         p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
1269       }
1270 
1271       /* In LE SC mode only IRK, IAI, CSRK are exchanged with the peer.
1272       ** Set local_r_key on central to expect only these keys.
1273       */
1274       if (p_cb->role == HCI_ROLE_CENTRAL) {
1275         p_cb->local_r_key &= (SMP_SEC_KEY_TYPE_ID | SMP_SEC_KEY_TYPE_CSRK);
1276       }
1277     } else {
1278       /* in legacy mode derivation of BR/EDR LK is not supported */
1279       p_cb->local_i_key &= ~SMP_SEC_KEY_TYPE_LK;
1280       p_cb->local_r_key &= ~SMP_SEC_KEY_TYPE_LK;
1281     }
1282     log::verbose("rcvs upgrades:i_keys=0x{:x} r_keys=0x{:x} (i-initiator r-responder)",
1283                  p_cb->local_i_key, p_cb->local_r_key);
1284 
1285     if (/*((p_cb->peer_auth_req & SMP_AUTH_BOND) ||
1286          (p_cb->loc_auth_req & SMP_AUTH_BOND)) &&*/
1287         p_cb->local_i_key || p_cb->local_r_key) {
1288       smp_sm_event(p_cb, SMP_BOND_REQ_EVT, NULL);
1289     } else {
1290       tSMP_INT_DATA smp_int_data;
1291       smp_int_data.status = enc_enable ? SMP_SUCCESS : SMP_ENC_FAIL;
1292       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1293     }
1294   } else if (enc_enable == 0) {
1295     tSMP_INT_DATA smp_int_data;
1296     smp_int_data.status = enc_enable ? SMP_SUCCESS : SMP_ENC_FAIL;
1297     /* if failed for encryption after pairing, send callback */
1298     if (p_cb->flags & SMP_PAIR_FLAG_ENC_AFTER_PAIR) {
1299       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1300     } else if (p_cb->role == HCI_ROLE_CENTRAL) {
1301       /* if enc failed for old security information */
1302       /* if central device, clean up and abck to idle; peripheral device do
1303        * nothing */
1304       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1305     }
1306   }
1307 }
1308 
1309 /*******************************************************************************
1310  * Function     smp_key_pick_key
1311  * Description  Pick a key distribution function based on the key mask.
1312  ******************************************************************************/
smp_key_pick_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1313 void smp_key_pick_key(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1314   uint8_t key_to_dist = (p_cb->role == HCI_ROLE_PERIPHERAL) ? p_cb->local_r_key : p_cb->local_i_key;
1315   uint8_t i = 0;
1316 
1317   log::verbose("key_to_dist=0x{:x}", key_to_dist);
1318   while (i < SMP_KEY_DIST_TYPE_MAX) {
1319     log::verbose("key to send=0x{:02x}, i={}", key_to_dist, i);
1320 
1321     if (key_to_dist & (1 << i)) {
1322       log::verbose("smp_distribute_act[{}]", i);
1323       (*smp_distribute_act[i])(p_cb, p_data);
1324       break;
1325     }
1326     i++;
1327   }
1328 }
1329 /*******************************************************************************
1330  * Function     smp_key_distribution
1331  * Description  start key distribution if required.
1332  ******************************************************************************/
smp_key_distribution(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1333 void smp_key_distribution(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1334   log::verbose("role={} (0-central) r_keys=0x{:x} i_keys=0x{:x}", p_cb->role, p_cb->local_r_key,
1335                p_cb->local_i_key);
1336 
1337   if (p_cb->role == HCI_ROLE_PERIPHERAL || (!p_cb->local_r_key && p_cb->role == HCI_ROLE_CENTRAL)) {
1338     smp_key_pick_key(p_cb, p_data);
1339   }
1340 
1341   if (!p_cb->local_i_key && !p_cb->local_r_key) {
1342     /* state check to prevent re-entrant */
1343     if (smp_get_state() == SMP_STATE_BOND_PENDING) {
1344       if (p_cb->derive_lk) {
1345         tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
1346         if (!(p_dev_rec->sec_rec.sec_flags & BTM_SEC_LE_LINK_KEY_AUTHED) &&
1347             (p_dev_rec->sec_rec.sec_flags & BTM_SEC_LINK_KEY_AUTHED)) {
1348           log::verbose("BR key is higher security than existing LE keys, don't derive LK from LTK");
1349         } else {
1350           smp_derive_link_key_from_long_term_key(p_cb, NULL);
1351         }
1352         p_cb->derive_lk = false;
1353       }
1354 
1355       if (p_cb->total_tx_unacked == 0) {
1356         /*
1357          * Instead of declaring authorization complete immediately,
1358          * delay the event from being sent by SMP_DELAYED_AUTH_TIMEOUT_MS.
1359          * This allows the peripheral to send over Pairing Failed if the
1360          * last key is rejected.  During this waiting window, the
1361          * state should remain in SMP_STATE_BOND_PENDING.
1362          */
1363         if (!alarm_is_scheduled(p_cb->delayed_auth_timer_ent)) {
1364           log::verbose("delaying auth complete");
1365           alarm_set_on_mloop(p_cb->delayed_auth_timer_ent, SMP_DELAYED_AUTH_TIMEOUT_MS,
1366                              smp_delayed_auth_complete_timeout, NULL);
1367         }
1368       } else {
1369         p_cb->wait_for_authorization_complete = true;
1370       }
1371     }
1372   }
1373 }
1374 
1375 /*******************************************************************************
1376  * Function         smp_decide_association_model
1377  * Description      This function is called to select assoc model to be used for
1378  *                  STK generation and to start STK generation process.
1379  *
1380  ******************************************************************************/
smp_decide_association_model(tSMP_CB * p_cb,tSMP_INT_DATA *)1381 void smp_decide_association_model(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1382   tSMP_EVENT int_evt = SMP_NOP_EVT;
1383   tSMP_INT_DATA smp_int_data;
1384 
1385   log::verbose("Association Model={}", p_cb->selected_association_model);
1386 
1387   switch (p_cb->selected_association_model) {
1388     case SMP_MODEL_ENCRYPTION_ONLY: /* TK = 0, go calculate Confirm */
1389       if (p_cb->role == HCI_ROLE_CENTRAL && ((p_cb->peer_auth_req & SMP_AUTH_YN_BIT) != 0) &&
1390           ((p_cb->loc_auth_req & SMP_AUTH_YN_BIT) == 0)) {
1391         log::error("IO capability does not meet authentication requirement");
1392         smp_int_data.status = SMP_PAIR_AUTH_FAIL;
1393         int_evt = SMP_AUTH_CMPL_EVT;
1394       } else {
1395         if (!GetInterfaceToProfiles()->config->isAndroidTVDevice() &&
1396             (p_cb->local_io_capability == SMP_IO_CAP_IO ||
1397              p_cb->local_io_capability == SMP_IO_CAP_KBDISP)) {
1398           /* display consent dialog if this device has a display */
1399           log::verbose("ENCRYPTION_ONLY showing Consent Dialog");
1400           p_cb->cb_evt = SMP_CONSENT_REQ_EVT;
1401           smp_set_state(SMP_STATE_WAIT_NONCE);
1402           smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, NULL);
1403         } else {
1404           p_cb->sec_level = SMP_SEC_UNAUTHENTICATE;
1405           log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", p_cb->sec_level);
1406 
1407           tSMP_KEY key;
1408           key.key_type = SMP_KEY_TYPE_TK;
1409           key.p_data = p_cb->tk.data();
1410           smp_int_data.key = key;
1411 
1412           p_cb->tk = {0};
1413           /* TK, ready  */
1414           int_evt = SMP_KEY_READY_EVT;
1415         }
1416       }
1417       break;
1418 
1419     case SMP_MODEL_PASSKEY:
1420       p_cb->sec_level = SMP_SEC_AUTHENTICATED;
1421       log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", p_cb->sec_level);
1422 
1423       p_cb->cb_evt = SMP_PASSKEY_REQ_EVT;
1424       int_evt = SMP_TK_REQ_EVT;
1425       break;
1426 
1427     case SMP_MODEL_OOB:
1428       log::error("Association Model=SMP_MODEL_OOB");
1429       p_cb->sec_level = SMP_SEC_AUTHENTICATED;
1430       log::verbose("p_cb->sec_level={}(SMP_SEC_AUTHENTICATED)", p_cb->sec_level);
1431 
1432       p_cb->cb_evt = SMP_OOB_REQ_EVT;
1433       int_evt = SMP_TK_REQ_EVT;
1434       break;
1435 
1436     case SMP_MODEL_KEY_NOTIF:
1437       p_cb->sec_level = SMP_SEC_AUTHENTICATED;
1438       log::verbose("Need to generate Passkey");
1439 
1440       /* generate passkey and notify application */
1441       smp_generate_passkey(p_cb, NULL);
1442       break;
1443 
1444     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1445     case SMP_MODEL_SEC_CONN_NUM_COMP:
1446     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1447     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1448     case SMP_MODEL_SEC_CONN_OOB:
1449       int_evt = SMP_PUBL_KEY_EXCH_REQ_EVT;
1450       break;
1451 
1452     case SMP_MODEL_OUT_OF_RANGE:
1453       log::error("Association Model=SMP_MODEL_OUT_OF_RANGE (failed)");
1454       smp_int_data.status = SMP_UNKNOWN_IO_CAP;
1455       int_evt = SMP_AUTH_CMPL_EVT;
1456       break;
1457 
1458     default:
1459       log::error("Association Model={} (SOMETHING IS WRONG WITH THE CODE)",
1460                  p_cb->selected_association_model);
1461       smp_int_data.status = SMP_UNKNOWN_IO_CAP;
1462       int_evt = SMP_AUTH_CMPL_EVT;
1463   }
1464 
1465   log::verbose("sec_level={}", p_cb->sec_level);
1466   if (int_evt) {
1467     smp_sm_event(p_cb, int_evt, &smp_int_data);
1468   }
1469 }
1470 
1471 /*******************************************************************************
1472  * Function     smp_process_io_response
1473  * Description  process IO response for a peripheral device.
1474  ******************************************************************************/
smp_process_io_response(tSMP_CB * p_cb,tSMP_INT_DATA *)1475 void smp_process_io_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1476   log::verbose("addr:{}", p_cb->pairing_bda);
1477   if (p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD) {
1478     /* pairing started by local (peripheral) Security Request */
1479     smp_set_state(SMP_STATE_SEC_REQ_PENDING);
1480     smp_send_cmd(SMP_OPCODE_SEC_REQ, p_cb);
1481   } else /* plan to send pairing respond */
1482   {
1483     /* pairing started by peer (central) Pairing Request */
1484     p_cb->selected_association_model = smp_select_association_model(p_cb);
1485 
1486     if (p_cb->sc_only_mode_locally_required &&
1487         (!(p_cb->sc_mode_required_by_peer) ||
1488          (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) {
1489       log::error(
1490               "Peripheral requires secure connection only mode but it can't be "
1491               "provided -> Peripheral fails pairing");
1492       tSMP_INT_DATA smp_int_data;
1493       smp_int_data.status = SMP_PAIR_AUTH_FAIL;
1494       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1495       return;
1496     }
1497 
1498     // If we are doing SMP_MODEL_SEC_CONN_OOB we don't need to request OOB data
1499     // locally if loc_oob_flag == 0x00 b/c there is no OOB data to give.  In the
1500     // event the loc_oob_flag is present value, we should request the OOB data
1501     // locally; otherwise fail.
1502     // If we are the initiator the OOB data has already been stored and will be
1503     // collected in the statemachine later.
1504     //
1505     // loc_oob_flag could be one of the following tSMP_OOB_FLAG enum values:
1506     // SMP_OOB_NONE = 0
1507     // SMP_OOB_PRESENT = 1
1508     // SMP_OOB_UNKNOWN = 2
1509     //
1510     // The only time Android cares about needing to provide the peer oob data
1511     // here would be in the advertiser situation or role.  If the
1512     // device is doing the connecting it will not need to get the data again as
1513     // it was already provided in the initiation call.
1514     //
1515     // loc_oob_flag should only equal SMP_OOB_PRESENT when PEER DATA exists and
1516     // device is the advertiser as opposed to being the connector.
1517     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
1518       switch (p_cb->loc_oob_flag) {
1519         case SMP_OOB_NONE:
1520           log::info("SMP_MODEL_SEC_CONN_OOB with SMP_OOB_NONE");
1521           if (!com::android::bluetooth::flags::remove_dup_pairing_response_in_oob_pairing()) {
1522             smp_send_pair_rsp(p_cb, NULL);
1523           }
1524           break;
1525         case SMP_OOB_PRESENT:
1526           log::info("SMP_MODEL_SEC_CONN_OOB with SMP_OOB_PRESENT");
1527           if (smp_request_oob_data(p_cb)) {
1528             return;
1529           }
1530           break;
1531         case SMP_OOB_UNKNOWN:
1532           log::warn("SMP_MODEL_SEC_CONN_OOB with SMP_OOB_UNKNOWN");
1533           tSMP_INT_DATA smp_int_data;
1534           smp_int_data.status = SMP_PAIR_AUTH_FAIL;
1535           smp_send_pair_fail(p_cb, &smp_int_data);
1536           return;
1537       }
1538     }
1539 
1540     // PTS Testing failure modes
1541     if (pts_test_send_authentication_complete_failure(p_cb)) {
1542       return;
1543     }
1544 
1545     smp_send_pair_rsp(p_cb, NULL);
1546   }
1547 }
1548 
1549 /*******************************************************************************
1550  * Function     smp_br_process_peripheral_keys_response
1551  * Description  process application keys response for a peripheral device
1552  *              (BR/EDR transport).
1553  ******************************************************************************/
smp_br_process_peripheral_keys_response(tSMP_CB * p_cb,tSMP_INT_DATA *)1554 void smp_br_process_peripheral_keys_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1555   smp_br_send_pair_response(p_cb, NULL);
1556 }
1557 
1558 /*******************************************************************************
1559  * Function     smp_br_send_pair_response
1560  * Description  actions related to sending pairing response over BR/EDR
1561  *              transport.
1562  ******************************************************************************/
smp_br_send_pair_response(tSMP_CB * p_cb,tSMP_INT_DATA *)1563 void smp_br_send_pair_response(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1564   log::verbose("addr:{}", p_cb->pairing_bda);
1565 
1566   p_cb->local_i_key &= p_cb->peer_i_key;
1567   p_cb->local_r_key &= p_cb->peer_r_key;
1568 
1569   smp_send_cmd(SMP_OPCODE_PAIRING_RSP, p_cb);
1570 }
1571 
1572 /*******************************************************************************
1573  * Function         smp_pairing_cmpl
1574  * Description      This function is called to send the pairing complete
1575  *                  callback and remove the connection if needed.
1576  ******************************************************************************/
smp_pairing_cmpl(tSMP_CB * p_cb,tSMP_INT_DATA *)1577 void smp_pairing_cmpl(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1578   if (p_cb->total_tx_unacked == 0) {
1579     /* process the pairing complete */
1580     smp_proc_pairing_cmpl(p_cb);
1581   }
1582 }
1583 
1584 /*******************************************************************************
1585  * Function         smp_pair_terminate
1586  * Description      This function is called to send the pairing complete
1587  *                  callback and remove the connection if needed.
1588  ******************************************************************************/
smp_pair_terminate(tSMP_CB * p_cb,tSMP_INT_DATA *)1589 void smp_pair_terminate(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1590   log::verbose("addr:{}", p_cb->pairing_bda);
1591   p_cb->status = SMP_CONN_TOUT;
1592   smp_proc_pairing_cmpl(p_cb);
1593 }
1594 
1595 /*******************************************************************************
1596  * Function         smp_idle_terminate
1597  * Description      This function calledin idle state to determine to send
1598  *                  authentication complete or not.
1599  ******************************************************************************/
smp_idle_terminate(tSMP_CB * p_cb,tSMP_INT_DATA *)1600 void smp_idle_terminate(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1601   if (p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD) {
1602     log::verbose("Pairing terminated at IDLE state.");
1603     p_cb->status = SMP_FAIL;
1604     smp_proc_pairing_cmpl(p_cb);
1605   }
1606 }
1607 
1608 /*******************************************************************************
1609  * Function     smp_both_have_public_keys
1610  * Description  The function is called when both local and peer public keys are
1611  *              saved.
1612  *              Actions:
1613  *              - invokes DHKey computation;
1614  *              - on peripheral side invokes sending local public key to the
1615  *peer.
1616  *              - invokes SC phase 1 process.
1617  ******************************************************************************/
smp_both_have_public_keys(tSMP_CB * p_cb,tSMP_INT_DATA *)1618 void smp_both_have_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1619   log::verbose("addr:{}", p_cb->pairing_bda);
1620 
1621   /* invokes DHKey computation */
1622   smp_compute_dhkey(p_cb);
1623 
1624   /* on peripheral side invokes sending local public key to the peer */
1625   if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1626     smp_send_pair_public_key(p_cb, NULL);
1627   }
1628 
1629   smp_sm_event(p_cb, SMP_SC_DHKEY_CMPLT_EVT, NULL);
1630 }
1631 
1632 /*******************************************************************************
1633  * Function     smp_start_secure_connection_phase1
1634  * Description  Start Secure Connection phase1 i.e. invokes initialization of
1635  *              Secure Connection phase 1 parameters and starts building/sending
1636  *              to the peer messages appropriate for the role and association
1637  *              model.
1638  ******************************************************************************/
smp_start_secure_connection_phase1(tSMP_CB * p_cb,tSMP_INT_DATA *)1639 void smp_start_secure_connection_phase1(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1640   log::verbose("addr:{}", p_cb->pairing_bda);
1641 
1642   if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS) {
1643     p_cb->sec_level = SMP_SEC_UNAUTHENTICATE;
1644     log::verbose("p_cb->sec_level={} (SMP_SEC_UNAUTHENTICATE)", p_cb->sec_level);
1645   } else {
1646     p_cb->sec_level = SMP_SEC_AUTHENTICATED;
1647     log::verbose("p_cb->sec_level={} (SMP_SEC_AUTHENTICATED)", p_cb->sec_level);
1648   }
1649 
1650   switch (p_cb->selected_association_model) {
1651     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1652     case SMP_MODEL_SEC_CONN_NUM_COMP:
1653       p_cb->local_random = {0};
1654       smp_start_nonce_generation(p_cb);
1655       break;
1656     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1657       /* user has to provide passkey */
1658       p_cb->cb_evt = SMP_PASSKEY_REQ_EVT;
1659       smp_sm_event(p_cb, SMP_TK_REQ_EVT, NULL);
1660       break;
1661     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1662       /* passkey has to be provided to user */
1663       log::verbose("Need to generate SC Passkey");
1664       smp_generate_passkey(p_cb, NULL);
1665       break;
1666     case SMP_MODEL_SEC_CONN_OOB:
1667       /* use the available OOB information */
1668       smp_process_secure_connection_oob_data(p_cb, NULL);
1669       break;
1670     default:
1671       log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model);
1672       break;
1673   }
1674 }
1675 
1676 /*******************************************************************************
1677  * Function     smp_process_local_nonce
1678  * Description  The function processes new local nonce.
1679  *
1680  * Note         It is supposed to be called in SC phase1.
1681  ******************************************************************************/
smp_process_local_nonce(tSMP_CB * p_cb,tSMP_INT_DATA *)1682 void smp_process_local_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1683   log::verbose("addr:{}", p_cb->pairing_bda);
1684 
1685   switch (p_cb->selected_association_model) {
1686     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1687     case SMP_MODEL_SEC_CONN_NUM_COMP:
1688       if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1689         /* peripheral calculates and sends local commitment */
1690         smp_calculate_local_commitment(p_cb);
1691         smp_send_commitment(p_cb, NULL);
1692         /* peripheral has to wait for peer nonce */
1693         smp_set_state(SMP_STATE_WAIT_NONCE);
1694       } else /* i.e. central */
1695       {
1696         if (p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_COMM) {
1697           /* peripheral commitment is already received, send local nonce, wait
1698            * for remote nonce*/
1699           log::verbose(
1700                   "central in assoc mode={} already rcvd peripheral commitment - race condition",
1701                   p_cb->selected_association_model);
1702           p_cb->flags &= ~SMP_PAIR_FLAG_HAVE_PEER_COMM;
1703           smp_send_rand(p_cb, NULL);
1704           smp_set_state(SMP_STATE_WAIT_NONCE);
1705         }
1706       }
1707       break;
1708     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1709     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1710       smp_calculate_local_commitment(p_cb);
1711 
1712       if (p_cb->role == HCI_ROLE_CENTRAL) {
1713         smp_send_commitment(p_cb, NULL);
1714       } else /* peripheral */
1715       {
1716         if (p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_COMM) {
1717           /* central commitment is already received */
1718           smp_send_commitment(p_cb, NULL);
1719           smp_set_state(SMP_STATE_WAIT_NONCE);
1720         }
1721       }
1722       break;
1723     case SMP_MODEL_SEC_CONN_OOB:
1724       if (p_cb->role == HCI_ROLE_CENTRAL) {
1725         smp_send_rand(p_cb, NULL);
1726       }
1727 
1728       smp_set_state(SMP_STATE_WAIT_NONCE);
1729       break;
1730     default:
1731       log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model);
1732       break;
1733   }
1734 }
1735 
1736 /*******************************************************************************
1737  * Function     smp_process_peer_nonce
1738  * Description  The function processes newly received and saved in CB peer
1739  *              nonce. The actions depend on the selected association model and
1740  *              the role.
1741  *
1742  * Note         It is supposed to be called in SC phase1.
1743  ******************************************************************************/
smp_process_peer_nonce(tSMP_CB * p_cb,tSMP_INT_DATA *)1744 void smp_process_peer_nonce(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1745   log::verbose("addr:{}, selected_association_model:{}", p_cb->pairing_bda,
1746                p_cb->selected_association_model);
1747 
1748   // PTS Testing failure modes
1749   if (p_cb->cert_failure == SMP_CONFIRM_VALUE_ERR) {
1750     log::error("failure case={}", p_cb->cert_failure);
1751     tSMP_INT_DATA smp_int_data;
1752     smp_int_data.status = SMP_CONFIRM_VALUE_ERR;
1753     p_cb->failure = SMP_CONFIRM_VALUE_ERR;
1754     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1755     return;
1756   }
1757   // PTS Testing failure modes (for LT)
1758   if ((p_cb->cert_failure == SMP_NUMERIC_COMPAR_FAIL) &&
1759       (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS) &&
1760       (p_cb->role == HCI_ROLE_PERIPHERAL)) {
1761     log::error("failure case={}", p_cb->cert_failure);
1762     tSMP_INT_DATA smp_int_data;
1763     smp_int_data.status = SMP_NUMERIC_COMPAR_FAIL;
1764     p_cb->failure = SMP_NUMERIC_COMPAR_FAIL;
1765     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1766     return;
1767   }
1768 
1769   switch (p_cb->selected_association_model) {
1770     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1771     case SMP_MODEL_SEC_CONN_NUM_COMP:
1772       /* in these models only central receives commitment */
1773       if (p_cb->role == HCI_ROLE_CENTRAL) {
1774         if (!smp_check_commitment(p_cb)) {
1775           tSMP_INT_DATA smp_int_data;
1776           smp_int_data.status = SMP_CONFIRM_VALUE_ERR;
1777           p_cb->failure = SMP_CONFIRM_VALUE_ERR;
1778           smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1779           break;
1780         }
1781       } else {
1782         /* peripheral sends local nonce */
1783         smp_send_rand(p_cb, NULL);
1784       }
1785 
1786       if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS) {
1787         if (!GetInterfaceToProfiles()->config->isAndroidTVDevice() &&
1788             (p_cb->local_io_capability == SMP_IO_CAP_IO ||
1789              p_cb->local_io_capability == SMP_IO_CAP_KBDISP)) {
1790           /* display consent dialog */
1791           log::verbose("JUST WORKS showing Consent Dialog");
1792           p_cb->cb_evt = SMP_CONSENT_REQ_EVT;
1793           smp_set_state(SMP_STATE_WAIT_NONCE);
1794           smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, NULL);
1795         } else {
1796           /* go directly to phase 2 */
1797           smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL);
1798         }
1799       } else /* numeric comparison */
1800       {
1801         smp_set_state(SMP_STATE_WAIT_NONCE);
1802         smp_sm_event(p_cb, SMP_SC_CALC_NC_EVT, NULL);
1803       }
1804       break;
1805     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1806     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1807       if (!smp_check_commitment(p_cb) && p_cb->cert_failure != SMP_NUMERIC_COMPAR_FAIL) {
1808         tSMP_INT_DATA smp_int_data;
1809         smp_int_data.status = SMP_CONFIRM_VALUE_ERR;
1810         p_cb->failure = SMP_CONFIRM_VALUE_ERR;
1811         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1812         break;
1813       }
1814 
1815       if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1816         smp_send_rand(p_cb, NULL);
1817       }
1818 
1819       if (++p_cb->round < 20) {
1820         smp_set_state(SMP_STATE_SEC_CONN_PHS1_START);
1821         p_cb->flags &= ~SMP_PAIR_FLAG_HAVE_PEER_COMM;
1822         smp_start_nonce_generation(p_cb);
1823         break;
1824       }
1825 
1826       smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL);
1827       break;
1828     case SMP_MODEL_SEC_CONN_OOB:
1829       if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1830         smp_send_rand(p_cb, NULL);
1831       }
1832 
1833       smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL);
1834       break;
1835     default:
1836       log::error("Association Model={} is not used in LE SC", p_cb->selected_association_model);
1837       break;
1838   }
1839 }
1840 
1841 /*******************************************************************************
1842  * Function     smp_match_dhkey_checks
1843  * Description  checks if the calculated peer DHKey Check value is the same as
1844  *              received from the peer DHKey check value.
1845  ******************************************************************************/
smp_match_dhkey_checks(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1846 void smp_match_dhkey_checks(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1847   log::verbose("addr:{}", p_cb->pairing_bda);
1848 
1849   if (memcmp(p_data->key.p_data, p_cb->remote_dhkey_check.data(), OCTET16_LEN)) {
1850     log::warn("dhkey chcks do no match");
1851     tSMP_INT_DATA smp_int_data;
1852     smp_int_data.status = SMP_DHKEY_CHK_FAIL;
1853     p_cb->failure = SMP_DHKEY_CHK_FAIL;
1854     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1855     return;
1856   }
1857 
1858   /* compare the max encryption key size, and save the smaller one for the link
1859    */
1860   if (p_cb->peer_enc_size < p_cb->loc_enc_size) {
1861     p_cb->loc_enc_size = p_cb->peer_enc_size;
1862   }
1863 
1864   if (p_cb->role == HCI_ROLE_PERIPHERAL) {
1865     smp_sm_event(p_cb, SMP_PAIR_DHKEY_CHCK_EVT, NULL);
1866   } else {
1867     /* central device always use received i/r key as keys to distribute */
1868     p_cb->local_i_key = p_cb->peer_i_key;
1869     p_cb->local_r_key = p_cb->peer_r_key;
1870     smp_sm_event(p_cb, SMP_ENC_REQ_EVT, NULL);
1871   }
1872 }
1873 
1874 /*******************************************************************************
1875  * Function     smp_move_to_secure_connections_phase2
1876  * Description  Signal State Machine to start SC phase 2 initialization (to
1877  *              compute local DHKey Check value).
1878  *
1879  * Note         SM is supposed to be in the state SMP_STATE_SEC_CONN_PHS2_START.
1880  ******************************************************************************/
smp_move_to_secure_connections_phase2(tSMP_CB * p_cb,tSMP_INT_DATA *)1881 void smp_move_to_secure_connections_phase2(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1882   log::verbose("addr:{}", p_cb->pairing_bda);
1883   smp_sm_event(p_cb, SMP_SC_PHASE1_CMPLT_EVT, NULL);
1884 }
1885 
1886 /*******************************************************************************
1887  * Function     smp_phase_2_dhkey_checks_are_present
1888  * Description  generates event if dhkey check from the peer is already
1889  *              received.
1890  *
1891  * Note         It is supposed to be used on peripheral to prevent race
1892  *condition. It is supposed to be called after peripheral dhkey check is
1893  *              calculated.
1894  ******************************************************************************/
smp_phase_2_dhkey_checks_are_present(tSMP_CB * p_cb,tSMP_INT_DATA *)1895 void smp_phase_2_dhkey_checks_are_present(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1896   log::verbose("addr:{}", p_cb->pairing_bda);
1897 
1898   if (p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_DHK_CHK) {
1899     smp_sm_event(p_cb, SMP_SC_2_DHCK_CHKS_PRES_EVT, NULL);
1900   }
1901 }
1902 
1903 /*******************************************************************************
1904  * Function     smp_wait_for_both_public_keys
1905  * Description  generates SMP_BOTH_PUBL_KEYS_RCVD_EVT event when both local and
1906  *              central public keys are available.
1907  *
1908  * Note         on the peripheral it is used to prevent race condition.
1909  *
1910  ******************************************************************************/
smp_wait_for_both_public_keys(tSMP_CB * p_cb,tSMP_INT_DATA *)1911 void smp_wait_for_both_public_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1912   log::verbose("addr:{}", p_cb->pairing_bda);
1913 
1914   if ((p_cb->flags & SMP_PAIR_FLAG_HAVE_PEER_PUBL_KEY) &&
1915       (p_cb->flags & SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY)) {
1916     if ((p_cb->role == HCI_ROLE_PERIPHERAL) &&
1917         ((p_cb->req_oob_type == SMP_OOB_LOCAL) || (p_cb->req_oob_type == SMP_OOB_BOTH))) {
1918       smp_set_state(SMP_STATE_PUBLIC_KEY_EXCH);
1919     }
1920     smp_sm_event(p_cb, SMP_BOTH_PUBL_KEYS_RCVD_EVT, NULL);
1921   }
1922 }
1923 
1924 /*******************************************************************************
1925  * Function     smp_start_passkey_verification
1926  * Description  Starts SC passkey entry verification.
1927  ******************************************************************************/
smp_start_passkey_verification(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1928 void smp_start_passkey_verification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
1929   uint8_t* p = NULL;
1930 
1931   log::verbose("addr:{}", p_cb->pairing_bda);
1932   p = p_cb->local_random.data();
1933   UINT32_TO_STREAM(p, p_data->passkey);
1934 
1935   p = p_cb->peer_random.data();
1936   UINT32_TO_STREAM(p, p_data->passkey);
1937 
1938   p_cb->round = 0;
1939   smp_start_nonce_generation(p_cb);
1940 }
1941 
1942 /*******************************************************************************
1943  * Function     smp_process_secure_connection_oob_data
1944  * Description  Processes local/peer SC OOB data received from somewhere.
1945  ******************************************************************************/
smp_process_secure_connection_oob_data(tSMP_CB * p_cb,tSMP_INT_DATA *)1946 void smp_process_secure_connection_oob_data(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
1947   log::verbose("addr:{}", p_cb->pairing_bda);
1948 
1949   tSMP_SC_OOB_DATA* p_sc_oob_data = &p_cb->sc_oob_data;
1950   if (p_sc_oob_data->loc_oob_data.present) {
1951     p_cb->local_random = p_sc_oob_data->loc_oob_data.randomizer;
1952   } else {
1953     log::verbose("local OOB randomizer is absent");
1954     p_cb->local_random = {0};
1955   }
1956 
1957   if (com::android::bluetooth::flags::btsec_le_oob_pairing()) {
1958     if (p_cb->peer_oob_flag == SMP_OOB_PRESENT && !p_sc_oob_data->loc_oob_data.present) {
1959       log::warn(
1960               "local OOB data is not present but peer claims to have received it; dropping "
1961               "connection");
1962       tSMP_INT_DATA smp_int_data{};
1963       smp_int_data.status = SMP_OOB_FAIL;
1964       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1965       return;
1966     }
1967   }
1968 
1969   if (!p_sc_oob_data->peer_oob_data.present) {
1970     log::verbose("peer OOB data is absent");
1971     p_cb->peer_random = {0};
1972   } else {
1973     p_cb->peer_random = p_sc_oob_data->peer_oob_data.randomizer;
1974     p_cb->remote_commitment = p_sc_oob_data->peer_oob_data.commitment;
1975 
1976     /* check commitment */
1977     if (!smp_check_commitment(p_cb)) {
1978       tSMP_INT_DATA smp_int_data;
1979       smp_int_data.status = SMP_CONFIRM_VALUE_ERR;
1980       p_cb->failure = SMP_CONFIRM_VALUE_ERR;
1981       smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
1982       return;
1983     }
1984 
1985     if (p_cb->peer_oob_flag != SMP_OOB_PRESENT) {
1986       /* the peer doesn't have local randomiser */
1987       log::verbose("peer didn't receive local OOB data, set local randomizer to 0");
1988       p_cb->local_random = {0};
1989     }
1990   }
1991 
1992   print128(p_cb->local_random, "local OOB randomizer");
1993   print128(p_cb->peer_random, "peer OOB randomizer");
1994   smp_start_nonce_generation(p_cb);
1995 }
1996 
1997 /*******************************************************************************
1998  * Function     smp_set_local_oob_keys
1999  * Description  Saves calculated private/public keys in
2000  *              sc_oob_data.loc_oob_data, starts nonce generation
2001  *              (to be saved in sc_oob_data.loc_oob_data.randomizer).
2002  ******************************************************************************/
smp_set_local_oob_keys(tSMP_CB * p_cb,tSMP_INT_DATA *)2003 void smp_set_local_oob_keys(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2004   log::verbose("addr:{}", p_cb->pairing_bda);
2005 
2006   memcpy(p_cb->sc_oob_data.loc_oob_data.private_key_used, p_cb->private_key, BT_OCTET32_LEN);
2007   p_cb->sc_oob_data.loc_oob_data.publ_key_used = p_cb->loc_publ_key;
2008   smp_start_nonce_generation(p_cb);
2009 }
2010 
2011 /*******************************************************************************
2012  * Function     smp_set_local_oob_random_commitment
2013  * Description  Saves calculated randomizer and commitment in
2014  *              sc_oob_data.loc_oob_data, passes sc_oob_data.loc_oob_data up
2015  *              for safekeeping.
2016  ******************************************************************************/
smp_set_local_oob_random_commitment(tSMP_CB * p_cb,tSMP_INT_DATA *)2017 void smp_set_local_oob_random_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2018   log::verbose("{}", p_cb->pairing_bda);
2019   p_cb->sc_oob_data.loc_oob_data.randomizer = p_cb->rand;
2020 
2021   p_cb->sc_oob_data.loc_oob_data.commitment =
2022           crypto_toolbox::f4(p_cb->sc_oob_data.loc_oob_data.publ_key_used.x,
2023                              p_cb->sc_oob_data.loc_oob_data.publ_key_used.x,
2024                              p_cb->sc_oob_data.loc_oob_data.randomizer, 0);
2025 
2026   p_cb->sc_oob_data.loc_oob_data.present = true;
2027 
2028   /* pass created OOB data up */
2029   p_cb->cb_evt = SMP_SC_LOC_OOB_DATA_UP_EVT;
2030   smp_send_app_cback(p_cb, NULL);
2031 
2032   // Store the data for later use when we are paired with
2033   // Event though the doc above says to pass up for safe keeping it never gets
2034   // kept safe. Additionally, when we need the data to make a decision we
2035   // wouldn't have it.  This will save the sc_oob_data in the smp_keys.cc such
2036   // that when we receive a request to create new keys we check to see if the
2037   // sc_oob_data exists and utilize the keys that are stored there otherwise the
2038   // connector will fail commitment check and dhkey exchange.
2039   smp_save_local_oob_data(p_cb);
2040 
2041   p_cb->reset();
2042 }
2043 
2044 /*******************************************************************************
2045  *
2046  * Function         smp_link_encrypted
2047  *
2048  * Description      This function is called when link is encrypted and notified
2049  *                  to the peripheral device. Proceed to to send LTK, DIV and ER
2050  *to central if bonding the devices.
2051  *
2052  *
2053  * Returns          void
2054  *
2055  ******************************************************************************/
smp_link_encrypted(const RawAddress & bda,uint8_t encr_enable)2056 void smp_link_encrypted(const RawAddress& bda, uint8_t encr_enable) {
2057   tSMP_CB* p_cb = &smp_cb;
2058 
2059   if (smp_cb.pairing_bda == bda) {
2060     log::debug("SMP encryption enable:{} device:{}", encr_enable, bda);
2061 
2062     /* encryption completed with STK, remember the key size now, could be
2063      * overwritten when key exchange happens                                 */
2064     if (p_cb->loc_enc_size != 0 && encr_enable) {
2065       /* update the link encryption key size if a SMP pairing just performed */
2066       btm_ble_update_sec_key_size(bda, p_cb->loc_enc_size);
2067     }
2068 
2069     tSMP_INT_DATA smp_int_data = {
2070             // TODO This is not a tSMP_STATUS
2071             .status = static_cast<tSMP_STATUS>(encr_enable),
2072     };
2073 
2074     smp_sm_event(&smp_cb, SMP_ENCRYPTED_EVT, &smp_int_data);
2075   } else {
2076     log::warn("SMP state machine busy so skipping encryption enable:{} device:{}", encr_enable,
2077               bda);
2078   }
2079 }
2080 
smp_cancel_start_encryption_attempt()2081 void smp_cancel_start_encryption_attempt() {
2082   log::error("Encryption request cancelled");
2083   smp_sm_event(&smp_cb, SMP_DISCARD_SEC_REQ_EVT, NULL);
2084 }
2085 
2086 /*******************************************************************************
2087  *
2088  * Function         smp_proc_ltk_request
2089  *
2090  * Description      This function is called when LTK request is received from
2091  *                  controller.
2092  *
2093  * Returns          void
2094  *
2095  ******************************************************************************/
smp_proc_ltk_request(const RawAddress & bda)2096 bool smp_proc_ltk_request(const RawAddress& bda) {
2097   log::verbose("addr:{},state={}", bda, smp_cb.state);
2098   bool match = false;
2099 
2100   if (bda == smp_cb.pairing_bda) {
2101     match = true;
2102   } else {
2103     tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bda);
2104     if (p_dev_rec != NULL && p_dev_rec->ble.pseudo_addr == smp_cb.pairing_bda &&
2105         p_dev_rec->ble.pseudo_addr != RawAddress::kEmpty) {
2106       match = true;
2107     }
2108   }
2109 
2110   if (match && smp_cb.state == SMP_STATE_ENCRYPTION_PENDING) {
2111     smp_sm_event(&smp_cb, SMP_ENC_REQ_EVT, NULL);
2112     return true;
2113   }
2114 
2115   return false;
2116 }
2117 
2118 /*******************************************************************************
2119  *
2120  * Function         smp_process_secure_connection_long_term_key
2121  *
2122  * Description      This function is called to process SC LTK.
2123  *                  SC LTK is calculated and used instead of STK.
2124  *                  Here SC LTK is saved in BLE DB.
2125  *
2126  * Returns          void
2127  *
2128  ******************************************************************************/
smp_process_secure_connection_long_term_key(void)2129 void smp_process_secure_connection_long_term_key(void) {
2130   tSMP_CB* p_cb = &smp_cb;
2131 
2132   log::verbose("addr:{}", p_cb->pairing_bda);
2133   smp_save_secure_connections_long_term_key(p_cb);
2134 
2135   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, false);
2136   smp_key_distribution(p_cb, NULL);
2137 }
2138 
2139 /*******************************************************************************
2140  *
2141  * Function         smp_set_derive_link_key
2142  *
2143  * Description      This function is called to set flag that indicates that
2144  *                  BR/EDR LK has to be derived from LTK after all keys are
2145  *                  distributed.
2146  *
2147  * Returns          void
2148  *
2149  ******************************************************************************/
smp_set_derive_link_key(tSMP_CB * p_cb,tSMP_INT_DATA *)2150 void smp_set_derive_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2151   log::verbose("addr:{}", p_cb->pairing_bda);
2152   p_cb->derive_lk = true;
2153   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_LK, false);
2154   smp_key_distribution(p_cb, NULL);
2155 }
2156 
2157 /*******************************************************************************
2158  *
2159  * Function         smp_derive_link_key_from_long_term_key
2160  *
2161  * Description      This function is called to derive BR/EDR LK from LTK.
2162  *
2163  * Returns          void
2164  *
2165  ******************************************************************************/
smp_derive_link_key_from_long_term_key(tSMP_CB * p_cb,tSMP_INT_DATA *)2166 void smp_derive_link_key_from_long_term_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2167   tSMP_STATUS status = SMP_PAIR_FAIL_UNKNOWN;
2168 
2169   log::verbose("addr:{}", p_cb->pairing_bda);
2170   if (!smp_calculate_link_key_from_long_term_key(p_cb)) {
2171     log::error("calc link key failed");
2172     tSMP_INT_DATA smp_int_data;
2173     smp_int_data.status = status;
2174     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
2175     return;
2176   }
2177 }
2178 
2179 /*******************************************************************************
2180  *
2181  * Function         smp_br_process_link_key
2182  *
2183  * Description      This function is called to process BR/EDR LK:
2184  *                  - to derive SMP LTK from BR/EDR LK;
2185  *                  - to save SMP LTK.
2186  *
2187  * Returns          void
2188  *
2189  ******************************************************************************/
smp_br_process_link_key(tSMP_CB * p_cb,tSMP_INT_DATA *)2190 void smp_br_process_link_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2191   tSMP_STATUS status = SMP_PAIR_FAIL_UNKNOWN;
2192 
2193   log::verbose("addr:{}", p_cb->pairing_bda);
2194   if (!smp_calculate_long_term_key_from_link_key(p_cb)) {
2195     log::error("calc LTK failed");
2196     tSMP_INT_DATA smp_int_data;
2197     smp_int_data.status = status;
2198     smp_sm_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &smp_int_data);
2199     return;
2200   }
2201 
2202   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda);
2203   if (p_dev_rec) {
2204     log::verbose("dev_type={}", p_dev_rec->device_type);
2205     p_dev_rec->device_type |= BT_DEVICE_TYPE_BLE;
2206   } else {
2207     log::error("failed to find Security Record");
2208   }
2209 
2210   log::verbose("LTK derivation from LK successfully completed");
2211   smp_save_secure_connections_long_term_key(p_cb);
2212   smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, false);
2213   smp_br_select_next_key(p_cb, NULL);
2214 }
2215 
2216 /*******************************************************************************
2217  * Function     smp_key_distribution_by_transport
2218  * Description  depending on the transport used at the moment calls either
2219  *              smp_key_distribution(...) or smp_br_key_distribution(...).
2220  ******************************************************************************/
smp_key_distribution_by_transport(tSMP_CB * p_cb,tSMP_INT_DATA *)2221 static void smp_key_distribution_by_transport(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2222   log::verbose("addr:{}", p_cb->pairing_bda);
2223   if (p_cb->smp_over_br) {
2224     smp_br_select_next_key(p_cb, NULL);
2225   } else {
2226     smp_key_distribution(p_cb, NULL);
2227   }
2228 }
2229 
2230 /*******************************************************************************
2231  * Function         smp_br_pairing_complete
2232  * Description      This function is called to send the pairing complete
2233  *                  callback and remove the connection if needed.
2234  ******************************************************************************/
smp_br_pairing_complete(tSMP_CB * p_cb,tSMP_INT_DATA *)2235 void smp_br_pairing_complete(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
2236   log::verbose("addr:{}", p_cb->pairing_bda);
2237 
2238   if (p_cb->total_tx_unacked == 0) {
2239     /* process the pairing complete */
2240     smp_proc_pairing_cmpl(p_cb);
2241   }
2242 }
2243