1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  This file contains security manager protocol utility functions
22  *
23  ******************************************************************************/
24 #define LOG_TAG "smp"
25 
26 #include <base/functional/bind.h>
27 #include <base/functional/callback.h>
28 #include <bluetooth/log.h>
29 
30 #include <algorithm>
31 #include <cstdint>
32 #include <cstring>
33 
34 #include "crypto_toolbox/crypto_toolbox.h"
35 #include "hci/controller_interface.h"
36 #include "main/shim/entry.h"
37 #include "p_256_ecc_pp.h"
38 #include "smp_int.h"
39 #include "stack/btm/btm_ble_sec.h"
40 #include "stack/btm/btm_dev.h"
41 #include "stack/btm/btm_sec.h"
42 #include "stack/include/acl_api.h"
43 #include "stack/include/bt_octets.h"
44 #include "stack/include/bt_types.h"
45 #include "stack/include/btm_ble_api.h"
46 #include "stack/include/btm_ble_sec_api.h"
47 #include "stack/include/main_thread.h"
48 #include "types/raw_address.h"
49 
50 using bluetooth::common::BindOnce;
51 using bluetooth::common::OnceCallback;
52 using crypto_toolbox::aes_128;
53 using namespace bluetooth;
54 
55 #ifndef SMP_MAX_ENC_REPEAT
56 #define SMP_MAX_ENC_REPEAT 3
57 #endif
58 
59 static void smp_process_stk(tSMP_CB* p_cb, Octet16* p);
60 static Octet16 smp_calculate_legacy_short_term_key(tSMP_CB* p_cb);
61 static void smp_process_private_key(tSMP_CB* p_cb);
62 
63 static void send_ble_rand(OnceCallback<void(uint64_t)> callback);
64 
65 #define SMP_PASSKEY_MASK 0x000fffff
66 
67 // If there is data saved here, then use its info instead
68 // This needs to be cleared on a successfult pairing using the oob data
69 static tSMP_LOC_OOB_DATA saved_local_oob_data = {};
70 
smp_save_local_oob_data(tSMP_CB * p_cb)71 void smp_save_local_oob_data(tSMP_CB* p_cb) {
72   saved_local_oob_data = p_cb->sc_oob_data.loc_oob_data;
73 }
74 
smp_clear_local_oob_data()75 void smp_clear_local_oob_data() { saved_local_oob_data = {}; }
76 
is_oob_data_empty(tSMP_LOC_OOB_DATA * data)77 static bool is_oob_data_empty(tSMP_LOC_OOB_DATA* data) {
78   tSMP_LOC_OOB_DATA empty_data = {};
79   return memcmp(data, &empty_data, sizeof(tSMP_LOC_OOB_DATA)) == 0;
80 }
81 
smp_has_local_oob_data()82 bool smp_has_local_oob_data() {
83   return !is_oob_data_empty(&saved_local_oob_data);
84 }
85 
smp_debug_print_nbyte_little_endian(uint8_t *,const char *,uint8_t)86 void smp_debug_print_nbyte_little_endian(uint8_t* /* p */,
87                                          const char* /* key_name */,
88                                          uint8_t /* len */) {}
89 
smp_debug_print_nbyte_little_endian(const Octet16 & p,const char * key_name,uint8_t len)90 inline void smp_debug_print_nbyte_little_endian(const Octet16& p,
91                                                 const char* key_name,
92                                                 uint8_t len) {
93   smp_debug_print_nbyte_little_endian(const_cast<uint8_t*>(p.data()), key_name,
94                                       len);
95 }
96 
smp_debug_print_nbyte_big_endian(uint8_t *,const char *,uint8_t)97 void smp_debug_print_nbyte_big_endian(uint8_t* /* p */,
98                                       const char* /* key_name */,
99                                       uint8_t /* len */) {}
100 
101 /** This function is called to process a passkey. */
smp_proc_passkey(tSMP_CB * p_cb,uint64_t rand)102 void smp_proc_passkey(tSMP_CB* p_cb, uint64_t rand) {
103   uint8_t* tt = p_cb->tk.data();
104   uint32_t passkey = static_cast<uint32_t>(rand & SMP_PASSKEY_MASK);
105 
106   log::verbose("addr:{}", p_cb->pairing_bda);
107 
108   /* truncate by maximum value */
109   while (passkey > BTM_MAX_PASSKEY_VAL) passkey >>= 1;
110 
111   /* save the TK */
112   p_cb->tk = {0};
113   UINT32_TO_STREAM(tt, passkey);
114 
115   if (p_cb->p_callback) {
116     tSMP_EVT_DATA smp_evt_data = {
117         .passkey = passkey,
118     };
119     (*p_cb->p_callback)(SMP_PASSKEY_NOTIF_EVT, p_cb->pairing_bda,
120                         &smp_evt_data);
121   }
122 
123   if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_PASSKEY_DISP) {
124     tSMP_INT_DATA smp_int_data;
125     smp_int_data.passkey = passkey;
126     smp_sm_event(&smp_cb, SMP_KEY_READY_EVT, &smp_int_data);
127   } else {
128     tSMP_KEY key;
129     key.key_type = SMP_KEY_TYPE_TK;
130     key.p_data = p_cb->tk.data();
131     tSMP_INT_DATA smp_int_data;
132     smp_int_data.key = key;
133     smp_sm_event(p_cb, SMP_KEY_READY_EVT, &smp_int_data);
134   }
135 }
136 
137 /*******************************************************************************
138  *
139  * Function         smp_generate_passkey
140  *
141  * Description      This function is called to generate passkey.
142  *
143  * Returns          void
144  *
145  ******************************************************************************/
smp_generate_passkey(tSMP_CB * p_cb,tSMP_INT_DATA *)146 void smp_generate_passkey(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
147   log::verbose("addr:{}", p_cb->pairing_bda);
148   /* generate MRand or SRand */
149   send_ble_rand(BindOnce(&smp_proc_passkey, p_cb));
150 }
151 
152 /*******************************************************************************
153  *
154  * Function         smp_generate_stk
155  *
156  * Description      This function is called to generate STK calculated by
157  *                  running AES with the TK value as key and a concatenation of
158  *                  the random values.
159  *
160  * Returns          void
161  *
162  ******************************************************************************/
smp_generate_stk(tSMP_CB * p_cb,tSMP_INT_DATA *)163 void smp_generate_stk(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
164   Octet16 output;
165 
166   log::verbose("addr:{}", p_cb->pairing_bda);
167 
168   if (p_cb->sc_mode_required_by_peer) {
169     log::verbose("FOR LE SC LTK IS USED INSTEAD OF STK");
170     output = p_cb->ltk;
171   } else {
172     output = smp_calculate_legacy_short_term_key(p_cb);
173   }
174 
175   smp_process_stk(p_cb, &output);
176 }
177 
178 /**
179  * This function is called to calculate CSRK
180  */
smp_compute_csrk(uint16_t div,tSMP_CB * p_cb)181 void smp_compute_csrk(uint16_t div, tSMP_CB* p_cb) {
182   Octet16 buffer{}; /* for (r || DIV)  r=1*/
183   uint16_t r = 1;
184   uint8_t* p = buffer.data();
185 
186   p_cb->div = div;
187 
188   log::verbose("div=0x{:x}", p_cb->div);
189   const Octet16& er = BTM_GetDeviceEncRoot();
190   /* CSRK = d1(ER, DIV, 1) */
191   UINT16_TO_STREAM(p, p_cb->div);
192   UINT16_TO_STREAM(p, r);
193 
194   p_cb->csrk = aes_128(er, buffer);
195   smp_send_csrk_info(p_cb, NULL);
196 }
197 
198 /**
199  * This function is called to calculate CSRK, starting with DIV generation.
200  */
smp_generate_csrk(tSMP_CB * p_cb,tSMP_INT_DATA *)201 void smp_generate_csrk(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
202   bool div_status;
203 
204   log::verbose("addr:{}", p_cb->pairing_bda);
205 
206   div_status = btm_get_local_div(p_cb->pairing_bda, &p_cb->div);
207   if (div_status) {
208     smp_compute_csrk(p_cb->div, p_cb);
209   } else {
210     log::verbose("Generate DIV for CSRK");
211     send_ble_rand(BindOnce(
212         [](tSMP_CB* p_cb, uint64_t rand) {
213           uint16_t div = static_cast<uint16_t>(rand);
214           smp_compute_csrk(div, p_cb);
215         },
216         p_cb));
217   }
218 }
219 
220 /*******************************************************************************
221  * Function         smp_concatenate_peer - LSB first
222  *                  add pairing command sent from local device into p1.
223  ******************************************************************************/
smp_concatenate_local(tSMP_CB * p_cb,uint8_t ** p_data,uint8_t op_code)224 void smp_concatenate_local(tSMP_CB* p_cb, uint8_t** p_data, uint8_t op_code) {
225   uint8_t* p = *p_data;
226 
227   log::verbose("addr:{}", p_cb->pairing_bda);
228   UINT8_TO_STREAM(p, op_code);
229   UINT8_TO_STREAM(p, p_cb->local_io_capability);
230   UINT8_TO_STREAM(p, p_cb->loc_oob_flag);
231   UINT8_TO_STREAM(p, p_cb->loc_auth_req);
232   UINT8_TO_STREAM(p, p_cb->loc_enc_size);
233   UINT8_TO_STREAM(p, p_cb->local_i_key);
234   UINT8_TO_STREAM(p, p_cb->local_r_key);
235 
236   *p_data = p;
237 }
238 
239 /*******************************************************************************
240  * Function         smp_concatenate_peer - LSB first
241  *                  add pairing command received from peer device into p1.
242  ******************************************************************************/
smp_concatenate_peer(tSMP_CB * p_cb,uint8_t ** p_data,uint8_t op_code)243 void smp_concatenate_peer(tSMP_CB* p_cb, uint8_t** p_data, uint8_t op_code) {
244   uint8_t* p = *p_data;
245 
246   log::verbose("addr:{}", p_cb->pairing_bda);
247   UINT8_TO_STREAM(p, op_code);
248   UINT8_TO_STREAM(p, p_cb->peer_io_caps);
249   UINT8_TO_STREAM(p, p_cb->peer_oob_flag);
250   UINT8_TO_STREAM(p, p_cb->peer_auth_req);
251   UINT8_TO_STREAM(p, p_cb->peer_enc_size);
252   UINT8_TO_STREAM(p, p_cb->peer_i_key);
253   UINT8_TO_STREAM(p, p_cb->peer_r_key);
254 
255   *p_data = p;
256 }
257 
258 /** Generate Confirm/Compare Step1:
259  *                  p1 = (MSB) pres || preq || rat' || iat' (LSB)
260  *                  Fill in values LSB first thus
261  *                  p1 = iat' || rat' || preq || pres
262  */
smp_gen_p1_4_confirm(tSMP_CB * p_cb,tBLE_ADDR_TYPE remote_bd_addr_type)263 Octet16 smp_gen_p1_4_confirm(tSMP_CB* p_cb,
264                              tBLE_ADDR_TYPE remote_bd_addr_type) {
265   log::verbose("pairing_addr:{}, rmt_addr_type:{}", p_cb->pairing_bda,
266                AddressTypeText(remote_bd_addr_type));
267   Octet16 p1;
268   uint8_t* p = p1.data();
269   if (p_cb->role == HCI_ROLE_CENTRAL) {
270     /* iat': initiator's (local) address type */
271     UINT8_TO_STREAM(p, p_cb->addr_type);
272     /* rat': responder's (remote) address type */
273     UINT8_TO_STREAM(p, remote_bd_addr_type);
274     /* preq : Pairing Request (local) command */
275     smp_concatenate_local(p_cb, &p, SMP_OPCODE_PAIRING_REQ);
276     /* pres : Pairing Response (remote) command */
277     smp_concatenate_peer(p_cb, &p, SMP_OPCODE_PAIRING_RSP);
278   } else {
279     /* iat': initiator's (remote) address type */
280     UINT8_TO_STREAM(p, remote_bd_addr_type);
281     /* rat': responder's (local) address type */
282     UINT8_TO_STREAM(p, p_cb->addr_type);
283     /* preq : Pairing Request (remote) command */
284     smp_concatenate_peer(p_cb, &p, SMP_OPCODE_PAIRING_REQ);
285     /* pres : Pairing Response (local) command */
286     smp_concatenate_local(p_cb, &p, SMP_OPCODE_PAIRING_RSP);
287   }
288   smp_debug_print_nbyte_little_endian(p1, "p1 = iat' || rat' || preq || pres",
289                                       16);
290 
291   return p1;
292 }
293 
294 /** Generate Confirm/Compare Step2:
295  *                  p2 = (MSB) padding || ia || ra (LSB)
296  *                  Fill values LSB first and thus:
297  *                  p2 = ra || ia || padding
298  */
smp_gen_p2_4_confirm(tSMP_CB * p_cb,const RawAddress & remote_bda)299 Octet16 smp_gen_p2_4_confirm(tSMP_CB* p_cb, const RawAddress& remote_bda) {
300   log::verbose("addr:{}", p_cb->pairing_bda);
301   Octet16 p2{0};
302   uint8_t* p = p2.data();
303   /* 32-bit Padding */
304   memset(p, 0, OCTET16_LEN);
305   if (p_cb->role == HCI_ROLE_CENTRAL) {
306     /* ra : Responder's (remote) address */
307     BDADDR_TO_STREAM(p, remote_bda);
308     /* ia : Initiator's (local) address */
309     BDADDR_TO_STREAM(p, p_cb->local_bda);
310   } else {
311     /* ra : Responder's (local) address */
312     BDADDR_TO_STREAM(p, p_cb->local_bda);
313     /* ia : Initiator's (remote) address */
314     BDADDR_TO_STREAM(p, remote_bda);
315   }
316   smp_debug_print_nbyte_little_endian(p2, "p2 = ra || ia || padding", 16);
317   return p2;
318 }
319 
320 /*******************************************************************************
321  *
322  * Function         smp_calculate_comfirm
323  *
324  * Description      This function (c1) is called to calculate Confirm value.
325  *
326  * Returns          tSMP_STATUS status of confirmation calculation
327  *
328  ******************************************************************************/
smp_calculate_comfirm(tSMP_CB * p_cb,const Octet16 & rand,Octet16 * output)329 tSMP_STATUS smp_calculate_comfirm(tSMP_CB* p_cb, const Octet16& rand,
330                                   Octet16* output) {
331   log::verbose("addr:{}", p_cb->pairing_bda);
332   RawAddress remote_bda;
333   tBLE_ADDR_TYPE remote_bd_addr_type = BLE_ADDR_PUBLIC;
334   /* get remote connection specific bluetooth address */
335   if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, remote_bda,
336                                     &remote_bd_addr_type, true)) {
337     log::error("cannot obtain remote device address");
338     return SMP_PAIR_FAIL_UNKNOWN;
339   }
340   /* get local connection specific bluetooth address */
341   BTM_ReadConnectionAddr(p_cb->pairing_bda, p_cb->local_bda, &p_cb->addr_type,
342                          true);
343   /* generate p1 = pres || preq || rat' || iat' */
344   Octet16 p1 = smp_gen_p1_4_confirm(p_cb, remote_bd_addr_type);
345   /* p1' = rand XOR p1 */
346   smp_xor_128(&p1, rand);
347   smp_debug_print_nbyte_little_endian(p1, "p1' = p1 XOR r", 16);
348   /* calculate e1 = e(k, p1'), where k = TK */
349   smp_debug_print_nbyte_little_endian(p_cb->tk.data(), "TK", 16);
350   Octet16 e1 = aes_128(p_cb->tk, p1);
351   smp_debug_print_nbyte_little_endian(e1.data(), "e1 = e(k, p1')", 16);
352   /* generate p2 = padding || ia || ra */
353   Octet16 p2 = smp_gen_p2_4_confirm(p_cb, remote_bda);
354   /* calculate p2' = (p2 XOR e1) */
355   smp_xor_128(&p2, e1);
356   smp_debug_print_nbyte_little_endian(p2, "p2' = p2 XOR e1", 16);
357   /* calculate: c1 = e(k, p2') */
358   *output = aes_128(p_cb->tk, p2);
359   return SMP_SUCCESS;
360 }
361 
362 /*******************************************************************************
363  *
364  * Function         smp_generate_confirm
365  *
366  * Description      This function is called when random number (MRand or SRand)
367  *                  is generated by the controller and the stack needs to
368  *                  calculate c1 value (MConfirm or SConfirm) for the first time
369  *
370  * Returns          void
371  *
372  ******************************************************************************/
smp_generate_confirm(tSMP_CB * p_cb)373 static void smp_generate_confirm(tSMP_CB* p_cb) {
374   log::verbose("addr:{}", p_cb->pairing_bda);
375   smp_debug_print_nbyte_little_endian(p_cb->rand.data(), "local_rand", 16);
376   Octet16 output;
377   tSMP_STATUS status = smp_calculate_comfirm(p_cb, p_cb->rand, &output);
378   if (status != SMP_SUCCESS) {
379     tSMP_INT_DATA smp_int_data;
380     smp_int_data.status = status;
381     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
382     return;
383   }
384   tSMP_KEY key;
385   p_cb->confirm = output;
386   smp_debug_print_nbyte_little_endian(p_cb->confirm, "Local Confirm generated",
387                                       16);
388   key.key_type = SMP_KEY_TYPE_CFM;
389   key.p_data = output.data();
390   tSMP_INT_DATA smp_int_data;
391   smp_int_data.key = key;
392   smp_sm_event(p_cb, SMP_KEY_READY_EVT, &smp_int_data);
393 }
394 
395 /*******************************************************************************
396  *
397  * Function         smp_generate_srand_mrand_confirm
398  *
399  * Description      This function is called to start the second pairing phase by
400  *                  start generating random number.
401  *
402  *
403  * Returns          void
404  *
405  ******************************************************************************/
smp_generate_srand_mrand_confirm(tSMP_CB * p_cb,tSMP_INT_DATA *)406 void smp_generate_srand_mrand_confirm(tSMP_CB* p_cb,
407                                       tSMP_INT_DATA* /* p_data */) {
408   log::verbose("addr:{}", p_cb->pairing_bda);
409   /* generate MRand or SRand */
410   send_ble_rand(BindOnce(
411       [](tSMP_CB* p_cb, uint64_t rand) {
412         memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t));
413         /* generate 64 MSB of MRand or SRand */
414         send_ble_rand(BindOnce(
415             [](tSMP_CB* p_cb, uint64_t rand) {
416               memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand,
417                      sizeof(uint64_t));
418               smp_generate_confirm(p_cb);
419             },
420             p_cb));
421       },
422       p_cb));
423 }
424 
425 /*******************************************************************************
426  *
427  * Function         smp_generate_compare
428  *
429  * Description      This function is called when random number (MRand or SRand)
430  *                  is received from remote device and the c1 value (MConfirm
431  *                  or SConfirm) needs to be generated to authenticate remote
432  *                  device.
433  *
434  * Returns          void
435  *
436  ******************************************************************************/
smp_generate_compare(tSMP_CB * p_cb,tSMP_INT_DATA *)437 void smp_generate_compare(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
438   log::verbose("addr:{}", p_cb->pairing_bda);
439   smp_debug_print_nbyte_little_endian(p_cb->rrand, "peer rand", 16);
440   Octet16 output;
441   tSMP_STATUS status = smp_calculate_comfirm(p_cb, p_cb->rrand, &output);
442   if (status != SMP_SUCCESS) {
443     tSMP_INT_DATA smp_int_data;
444     smp_int_data.status = status;
445     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
446     return;
447   }
448   tSMP_KEY key;
449   smp_debug_print_nbyte_little_endian(output.data(), "Remote Confirm generated",
450                                       16);
451   key.key_type = SMP_KEY_TYPE_CMP;
452   key.p_data = output.data();
453   tSMP_INT_DATA smp_int_data;
454   smp_int_data.key = key;
455   smp_sm_event(p_cb, SMP_KEY_READY_EVT, &smp_int_data);
456 }
457 
458 /** This function is called when STK is generated proceed to send the encrypt
459  * the link using STK. */
smp_process_stk(tSMP_CB * p_cb,Octet16 * p)460 static void smp_process_stk(tSMP_CB* p_cb, Octet16* p) {
461   tSMP_KEY key;
462 
463   log::verbose("addr:{}", p_cb->pairing_bda);
464   smp_mask_enc_key(p_cb->loc_enc_size, p);
465 
466   key.key_type = SMP_KEY_TYPE_STK;
467   key.p_data = p->data();
468 
469   tSMP_INT_DATA smp_int_data;
470   smp_int_data.key = key;
471   smp_sm_event(p_cb, SMP_KEY_READY_EVT, &smp_int_data);
472 }
473 
474 /** This function calculates EDIV = Y xor DIV */
smp_process_ediv(tSMP_CB * p_cb,Octet16 & p)475 static void smp_process_ediv(tSMP_CB* p_cb, Octet16& p) {
476   tSMP_KEY key;
477   uint8_t* pp = p.data();
478   uint16_t y;
479 
480   log::verbose("addr:{}", p_cb->pairing_bda);
481   STREAM_TO_UINT16(y, pp);
482 
483   /* EDIV = Y xor DIV */
484   p_cb->ediv = p_cb->div ^ y;
485   /* send LTK ready */
486   key.key_type = SMP_KEY_TYPE_LTK;
487   key.p_data = p.data();
488 
489   tSMP_INT_DATA smp_int_data;
490   smp_int_data.key = key;
491   smp_sm_event(p_cb, SMP_KEY_READY_EVT, &smp_int_data);
492 }
493 
494 /**
495  * This function is to proceed generate Y = E(DHK, Rand)
496  */
smp_generate_y(tSMP_CB * p_cb,uint64_t rand)497 static void smp_generate_y(tSMP_CB* p_cb, uint64_t rand) {
498   log::verbose("addr:{}", p_cb->pairing_bda);
499 
500   const Octet16& dhk = BTM_GetDeviceDHK();
501 
502   memcpy(p_cb->enc_rand, (uint8_t*)&rand, sizeof(uint64_t));
503   Octet16 rand16{};
504   memcpy(rand16.data(), (uint8_t*)&rand, sizeof(uint64_t));
505   Octet16 output = aes_128(dhk, rand16);
506   smp_process_ediv(p_cb, output);
507 }
508 
509 /**
510  * Calculate LTK = d1(ER, DIV, 0)= e(ER, DIV)
511  */
smp_generate_ltk_cont(uint16_t div,tSMP_CB * p_cb)512 static void smp_generate_ltk_cont(uint16_t div, tSMP_CB* p_cb) {
513   p_cb->div = div;
514 
515   log::verbose("addr:{}", p_cb->pairing_bda);
516   const Octet16& er = BTM_GetDeviceEncRoot();
517 
518   /* LTK = d1(ER, DIV, 0)= e(ER, DIV)*/
519   Octet16 div16{};
520   div16.data()[0] = div & 0xff;
521   div16.data()[1] = div >> 8u;
522   Octet16 ltk = aes_128(er, div16);
523   /* mask the LTK */
524   smp_mask_enc_key(p_cb->loc_enc_size, &ltk);
525   p_cb->ltk = ltk;
526 
527   /* generate EDIV and rand now */
528   send_ble_rand(BindOnce(&smp_generate_y, p_cb));
529 }
530 
531 /*******************************************************************************
532  *
533  * Function         smp_generate_ltk
534  *
535  * Description      This function is called:
536  *                  - in legacy pairing - to calculate LTK, starting with DIV
537  *                    generation;
538  *                  - in LE Secure Connections pairing over LE transport - to
539  *                    process LTK already generated to encrypt LE link;
540  *                  - in LE Secure Connections pairing over BR/EDR transport -
541  *                    to start BR/EDR Link Key processing.
542  *
543  * Returns          void
544  *
545  ******************************************************************************/
smp_generate_ltk(tSMP_CB * p_cb,tSMP_INT_DATA *)546 void smp_generate_ltk(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
547   log::verbose("addr:{}", p_cb->pairing_bda);
548 
549   if (smp_get_br_state() == SMP_BR_STATE_BOND_PENDING) {
550     smp_br_process_link_key(p_cb, NULL);
551     return;
552   } else if (p_cb->sc_mode_required_by_peer) {
553     smp_process_secure_connection_long_term_key();
554     return;
555   }
556 
557   bool div_status = btm_get_local_div(p_cb->pairing_bda, &p_cb->div);
558 
559   if (div_status) {
560     smp_generate_ltk_cont(p_cb->div, p_cb);
561   } else {
562     log::verbose("Generate DIV for LTK");
563 
564     /* generate MRand or SRand */
565     send_ble_rand(BindOnce(
566         [](tSMP_CB* p_cb, uint64_t rand) {
567           uint16_t div = static_cast<uint16_t>(rand);
568           smp_generate_ltk_cont(div, p_cb);
569         },
570         p_cb));
571   }
572 }
573 
574 /* The function calculates legacy STK */
smp_calculate_legacy_short_term_key(tSMP_CB * p_cb)575 Octet16 smp_calculate_legacy_short_term_key(tSMP_CB* p_cb) {
576   log::verbose("addr:{}", p_cb->pairing_bda);
577 
578   Octet16 text{};
579   if (p_cb->role == HCI_ROLE_CENTRAL) {
580     memcpy(text.data(), p_cb->rand.data(), BT_OCTET8_LEN);
581     memcpy(text.data() + BT_OCTET8_LEN, p_cb->rrand.data(), BT_OCTET8_LEN);
582   } else {
583     memcpy(text.data(), p_cb->rrand.data(), BT_OCTET8_LEN);
584     memcpy(text.data() + BT_OCTET8_LEN, p_cb->rand.data(), BT_OCTET8_LEN);
585   }
586 
587   /* generate STK = Etk(rand|rrand)*/
588   return aes_128(p_cb->tk, text);
589 }
590 
591 /*******************************************************************************
592  *
593  * Function         smp_create_private_key
594  *
595  * Description      This function is called to create private key used to
596  *                  calculate public key and DHKey.
597  *                  The function starts private key creation requesting
598  *                  for the controller to generate [0-7] octets of private key.
599  *
600  * Returns          void
601  *
602  ******************************************************************************/
smp_create_private_key(tSMP_CB * p_cb,tSMP_INT_DATA *)603 void smp_create_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
604   log::verbose("addr:{}", p_cb->pairing_bda);
605 
606   // Only use the stored OOB data if we are in an oob association model
607   if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
608     log::warn("OOB Association Model");
609     // Make sure our data isn't empty, otherwise we generate new and eventually
610     // pairing will fail Not much we can do about it at this point, just have to
611     // generate new data The data will be cleared after the advertiser times
612     // out, so if the advertiser times out we want the pairing to fail anyway.
613     if (!is_oob_data_empty(&saved_local_oob_data)) {
614       log::warn("Found OOB data, loading keys");
615       for (int i = 0; i < BT_OCTET32_LEN; i++) {
616         p_cb->private_key[i] = saved_local_oob_data.private_key_used[i];
617         p_cb->loc_publ_key.x[i] = saved_local_oob_data.publ_key_used.x[i];
618         p_cb->loc_publ_key.y[i] = saved_local_oob_data.publ_key_used.y[i];
619       }
620       p_cb->sc_oob_data.loc_oob_data = saved_local_oob_data;
621       p_cb->local_random = saved_local_oob_data.randomizer;
622       smp_process_private_key(p_cb);
623       return;
624     }
625     log::warn("OOB Association Model with no saved data present");
626   }
627 
628   send_ble_rand(BindOnce(
629       [](tSMP_CB* p_cb, uint64_t rand) {
630         memcpy(p_cb->private_key, (uint8_t*)&rand, sizeof(uint64_t));
631         send_ble_rand(BindOnce(
632             [](tSMP_CB* p_cb, uint64_t rand) {
633               memcpy(&p_cb->private_key[8], (uint8_t*)&rand, sizeof(uint64_t));
634               send_ble_rand(BindOnce(
635                   [](tSMP_CB* p_cb, uint64_t rand) {
636                     memcpy(&p_cb->private_key[16], (uint8_t*)&rand,
637                            sizeof(uint64_t));
638                     send_ble_rand(BindOnce(
639                         [](tSMP_CB* p_cb, uint64_t rand) {
640                           memcpy(&p_cb->private_key[24], (uint8_t*)&rand,
641                                  sizeof(uint64_t));
642                           smp_process_private_key(p_cb);
643                         },
644                         p_cb));
645                   },
646                   p_cb));
647             },
648             p_cb));
649       },
650       p_cb));
651 }
652 
653 /*******************************************************************************
654  *
655  * Function         smp_use_oob_private_key
656  *
657  * Description      This function is called
658  *                  - to save the secret key used to calculate the public key
659  *                    used in calculations of commitment sent OOB to a peer
660  *                  - to use this secret key to recalculate the public key and
661  *                    start the process of sending this public key to the peer
662  *                  if secret/public keys have to be reused.
663  *                  If the keys aren't supposed to be reused, continue from the
664  *                  point from which request for OOB data was issued.
665  *
666  * Returns          void
667  *
668  ******************************************************************************/
smp_use_oob_private_key(tSMP_CB * p_cb,tSMP_INT_DATA *)669 void smp_use_oob_private_key(tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
670   log::info("req_oob_type:{}, role:{}", p_cb->req_oob_type, p_cb->role);
671 
672   switch (p_cb->req_oob_type) {
673     case SMP_OOB_BOTH:
674     case SMP_OOB_LOCAL:
675       log::info("restore secret key");
676       // Only use the stored OOB data if we are in an oob association model
677       if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
678         log::info("OOB Association Model");
679         // Make sure our data isn't empty, otherwise we generate new and
680         // eventually pairing will fail Not much we can do about it at this
681         // point, just have to generate new data The data will be cleared after
682         // the advertiser times out, so if the advertiser times out we want the
683         // pairing to fail anyway.
684         if (!is_oob_data_empty(&saved_local_oob_data)) {
685           log::info("Found OOB data, loading keys");
686           for (int i = 0; i < BT_OCTET32_LEN; i++) {
687             p_cb->private_key[i] = saved_local_oob_data.private_key_used[i];
688             p_cb->loc_publ_key.x[i] = saved_local_oob_data.publ_key_used.x[i];
689             p_cb->loc_publ_key.y[i] = saved_local_oob_data.publ_key_used.y[i];
690           }
691           p_cb->sc_oob_data.loc_oob_data = saved_local_oob_data;
692           p_cb->local_random = saved_local_oob_data.randomizer;
693           smp_process_private_key(p_cb);
694           return;
695         }
696         log::info("OOB Association Model with no saved data present");
697       }
698 
699       memcpy(p_cb->private_key, p_cb->sc_oob_data.loc_oob_data.private_key_used,
700              BT_OCTET32_LEN);
701       smp_process_private_key(p_cb);
702       break;
703     default:
704       log::info("create secret key anew");
705       smp_set_state(SMP_STATE_PAIR_REQ_RSP);
706       smp_decide_association_model(p_cb, NULL);
707       break;
708   }
709 }
710 
711 /*******************************************************************************
712  *
713  * Function         smp_process_private_key
714  *
715  * Description      This function processes private key.
716  *                  It calculates public key and notifies SM that private key /
717  *                  public key pair is created.
718  *
719  * Returns          void
720  *
721  ******************************************************************************/
smp_process_private_key(tSMP_CB * p_cb)722 void smp_process_private_key(tSMP_CB* p_cb) {
723   Point public_key;
724   BT_OCTET32 private_key;
725 
726   log::verbose("addr:{}", p_cb->pairing_bda);
727 
728   memcpy(private_key, p_cb->private_key, BT_OCTET32_LEN);
729   ECC_PointMult(&public_key, &(curve_p256.G), (uint32_t*)private_key);
730   memcpy(p_cb->loc_publ_key.x, public_key.x, BT_OCTET32_LEN);
731   memcpy(p_cb->loc_publ_key.y, public_key.y, BT_OCTET32_LEN);
732 
733   smp_debug_print_nbyte_little_endian(p_cb->private_key, "private",
734                                       BT_OCTET32_LEN);
735   smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.x, "local public(x)",
736                                       BT_OCTET32_LEN);
737   smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.y, "local public(y)",
738                                       BT_OCTET32_LEN);
739   p_cb->flags |= SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY;
740   smp_sm_event(p_cb, SMP_LOC_PUBL_KEY_CRTD_EVT, NULL);
741 }
742 
743 /*******************************************************************************
744  *
745  * Function         smp_compute_dhkey
746  *
747  * Description      The function:
748  *                  - calculates a new public key using as input local private
749  *                    key and peer public key;
750  *                  - saves the new public key x-coordinate as DHKey.
751  *
752  * Returns          void
753  *
754  ******************************************************************************/
smp_compute_dhkey(tSMP_CB * p_cb)755 void smp_compute_dhkey(tSMP_CB* p_cb) {
756   Point peer_publ_key, new_publ_key;
757   BT_OCTET32 private_key;
758 
759   log::verbose("addr:{}", p_cb->pairing_bda);
760 
761   memcpy(private_key, p_cb->private_key, BT_OCTET32_LEN);
762   memcpy(peer_publ_key.x, p_cb->peer_publ_key.x, BT_OCTET32_LEN);
763   memcpy(peer_publ_key.y, p_cb->peer_publ_key.y, BT_OCTET32_LEN);
764 
765   ECC_PointMult(&new_publ_key, &peer_publ_key, (uint32_t*)private_key);
766 
767   memcpy(p_cb->dhkey, new_publ_key.x, BT_OCTET32_LEN);
768 
769   smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Old DHKey", BT_OCTET32_LEN);
770 
771   smp_debug_print_nbyte_little_endian(p_cb->private_key, "private",
772                                       BT_OCTET32_LEN);
773   smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.x, "rem public(x)",
774                                       BT_OCTET32_LEN);
775   smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.y, "rem public(y)",
776                                       BT_OCTET32_LEN);
777   smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Reverted DHKey",
778                                       BT_OCTET32_LEN);
779 }
780 
781 /** The function calculates and saves local commmitment in CB. */
smp_calculate_local_commitment(tSMP_CB * p_cb)782 void smp_calculate_local_commitment(tSMP_CB* p_cb) {
783   uint8_t random_input;
784 
785   log::verbose("addr:{}", p_cb->pairing_bda);
786 
787   switch (p_cb->selected_association_model) {
788     case SMP_MODEL_SEC_CONN_JUSTWORKS:
789     case SMP_MODEL_SEC_CONN_NUM_COMP:
790       if (p_cb->role == HCI_ROLE_CENTRAL)
791         log::warn(
792             "local commitment calc on central is not expected for Just "
793             "Works/Numeric Comparison models");
794       p_cb->commitment = crypto_toolbox::f4(
795           p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, 0);
796       break;
797     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
798     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
799       random_input =
800           smp_calculate_random_input(p_cb->local_random.data(), p_cb->round);
801       p_cb->commitment =
802           crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x,
803                              p_cb->rand, random_input);
804       break;
805     case SMP_MODEL_SEC_CONN_OOB:
806       log::warn(
807           "local commitment calc is expected for OOB model BEFORE pairing");
808       p_cb->commitment = crypto_toolbox::f4(
809           p_cb->loc_publ_key.x, p_cb->loc_publ_key.x, p_cb->local_random, 0);
810       break;
811     default:
812       log::error("Association Model={} is not used in LE SC",
813                  p_cb->selected_association_model);
814       return;
815   }
816 }
817 
818 /** The function calculates peer commmitment */
smp_calculate_peer_commitment(tSMP_CB * p_cb)819 Octet16 smp_calculate_peer_commitment(tSMP_CB* p_cb) {
820   uint8_t ri;
821 
822   log::verbose("addr:{}", p_cb->pairing_bda);
823   Octet16 output{0};
824   switch (p_cb->selected_association_model) {
825     case SMP_MODEL_SEC_CONN_JUSTWORKS:
826     case SMP_MODEL_SEC_CONN_NUM_COMP:
827       if (p_cb->role == HCI_ROLE_PERIPHERAL)
828         log::warn(
829             "peer commitment calc on peripheral is not expected for Just "
830             "Works/Numeric Comparison models");
831       output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x,
832                                   p_cb->rrand, 0);
833       break;
834     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
835     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
836       ri = smp_calculate_random_input(p_cb->peer_random.data(), p_cb->round);
837       output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x,
838                                   p_cb->rrand, ri);
839       break;
840     case SMP_MODEL_SEC_CONN_OOB:
841       output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->peer_publ_key.x,
842                                   p_cb->peer_random, 0);
843       break;
844     default:
845       log::error("Association Model={} is not used in LE SC",
846                  p_cb->selected_association_model);
847       return output;
848   }
849 
850   return output;
851 }
852 
853 /*******************************************************************************
854  *
855  * Function         smp_calculate_numeric_comparison_display_number
856  *
857  * Description      The function calculates and saves number to display in
858  *                  numeric comparison association mode.
859  *
860  * Returns          void
861  *
862  ******************************************************************************/
smp_calculate_numeric_comparison_display_number(tSMP_CB * p_cb,tSMP_INT_DATA *)863 void smp_calculate_numeric_comparison_display_number(
864     tSMP_CB* p_cb, tSMP_INT_DATA* /* p_data */) {
865   log::verbose("addr:{}", p_cb->pairing_bda);
866 
867   if (p_cb->role == HCI_ROLE_CENTRAL) {
868     p_cb->number_to_display = crypto_toolbox::g2(
869         p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, p_cb->rrand);
870   } else {
871     p_cb->number_to_display = crypto_toolbox::g2(
872         p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, p_cb->rand);
873   }
874 
875   if (p_cb->number_to_display >= (BTM_MAX_PASSKEY_VAL + 1)) {
876     tSMP_INT_DATA smp_int_data;
877     smp_int_data.status = SMP_PAIR_FAIL_UNKNOWN;
878     p_cb->failure = SMP_PAIR_FAIL_UNKNOWN;
879     log::verbose("Number to display in numeric comparison={} too large",
880                  p_cb->number_to_display);
881     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
882     return;
883   }
884 
885   p_cb->cb_evt = SMP_NC_REQ_EVT;
886   tSMP_INT_DATA smp_int_data;
887   smp_int_data.passkey = p_cb->number_to_display;
888   smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, &smp_int_data);
889 }
890 
891 /*******************************************************************************
892  *
893  * Function         smp_calculate_local_dhkey_check
894  *
895  * Description      The function calculates and saves local device DHKey check
896  *                  value in CB.
897  *                  Before doing this it calls
898  *                  smp_calculate_f5_mackey_and_long_term_key(...).
899  *                  to calculate MacKey and LTK.
900  *                  MacKey is used in dhkey calculation.
901  *
902  * Returns          void
903  *
904  ******************************************************************************/
smp_calculate_local_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA *)905 void smp_calculate_local_dhkey_check(tSMP_CB* p_cb,
906                                      tSMP_INT_DATA* /* p_data */) {
907   uint8_t iocap[3], a[7], b[7];
908 
909   log::verbose("addr:{}", p_cb->pairing_bda);
910 
911   smp_calculate_f5_mackey_and_long_term_key(p_cb);
912 
913   smp_collect_local_io_capabilities(iocap, p_cb);
914 
915   smp_collect_local_ble_address(a, p_cb);
916   smp_collect_peer_ble_address(b, p_cb);
917   p_cb->dhkey_check = crypto_toolbox::f6(p_cb->mac_key, p_cb->rand, p_cb->rrand,
918                                          p_cb->peer_random, iocap, a, b);
919 }
920 
921 /*******************************************************************************
922  *
923  * Function         smp_calculate_peer_dhkey_check
924  *
925  * Description      The function calculates peer device DHKey check value.
926  *
927  * Returns          void
928  *
929  ******************************************************************************/
smp_calculate_peer_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA *)930 void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb,
931                                     tSMP_INT_DATA* /* p_data */) {
932   uint8_t iocap[3], a[7], b[7];
933   tSMP_KEY key;
934 
935   log::verbose("addr:{}", p_cb->pairing_bda);
936 
937   smp_collect_peer_io_capabilities(iocap, p_cb);
938 
939   smp_collect_local_ble_address(a, p_cb);
940   smp_collect_peer_ble_address(b, p_cb);
941   Octet16 param_buf = crypto_toolbox::f6(p_cb->mac_key, p_cb->rrand, p_cb->rand,
942                                          p_cb->local_random, iocap, b, a);
943   key.key_type = SMP_KEY_TYPE_PEER_DHK_CHCK;
944   key.p_data = param_buf.data();
945   tSMP_INT_DATA smp_int_data;
946   smp_int_data.key = key;
947   smp_sm_event(p_cb, SMP_SC_KEY_READY_EVT, &smp_int_data);
948 }
949 
950 /*******************************************************************************
951  *
952  * Function         smp_calculate_link_key_from_long_term_key
953  *
954  * Description      The function calculates and saves BR/EDR link key derived
955  *                  from LE SC LTK.
956  *
957  * Returns          false if out of resources, true in other cases.
958  *
959  ******************************************************************************/
smp_calculate_link_key_from_long_term_key(tSMP_CB * p_cb)960 bool smp_calculate_link_key_from_long_term_key(tSMP_CB* p_cb) {
961   tBTM_SEC_DEV_REC* p_dev_rec;
962   RawAddress bda_for_lk;
963   tBLE_ADDR_TYPE conn_addr_type;
964 
965   log::verbose("addr:{}", p_cb->pairing_bda);
966 
967   if (p_cb->id_addr_rcvd && p_cb->id_addr_type == BLE_ADDR_PUBLIC) {
968     log::verbose(
969         "Use rcvd identity address as BD_ADDR of LK rcvd identity address");
970     bda_for_lk = p_cb->id_addr;
971   } else if ((BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda_for_lk,
972                                            &conn_addr_type, true)) &&
973              conn_addr_type == BLE_ADDR_PUBLIC) {
974     log::verbose("Use rcvd connection address as BD_ADDR of LK");
975   } else {
976     log::warn("Don't have peer public address to associate with LK");
977     return false;
978   }
979 
980   p_dev_rec = btm_find_dev(p_cb->pairing_bda);
981   if (p_dev_rec == NULL) {
982     log::error("failed to find Security Record");
983     return false;
984   }
985 
986   Octet16 link_key =
987       crypto_toolbox::ltk_to_link_key(p_cb->ltk, p_cb->key_derivation_h7_used);
988 
989   uint8_t link_key_type;
990   if (p_cb->init_security_mode == BTM_SEC_MODE_SC) {
991     /* Secure Connections Only Mode */
992     link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
993   } else if (bluetooth::shim::GetController()->SupportsSecureConnections()) {
994     /* both transports are SC capable */
995     if (p_cb->sec_level == SMP_SEC_AUTHENTICATED)
996       link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
997     else
998       link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB_P_256;
999   } else if (p_cb->init_security_mode == BTM_SEC_MODE_SP) {
1000     /* BR/EDR transport is SSP capable */
1001     if (p_cb->sec_level == SMP_SEC_AUTHENTICATED)
1002       link_key_type = BTM_LKEY_TYPE_AUTH_COMB;
1003     else
1004       link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB;
1005   } else {
1006     log::error("failed to update link_key. Sec Mode={}, sm4=0x{:02x}",
1007                p_cb->init_security_mode, p_dev_rec->sm4);
1008     return false;
1009   }
1010 
1011   link_key_type += BTM_LTK_DERIVED_LKEY_OFFSET;
1012 
1013   Octet16 notif_link_key;
1014   std::reverse_copy(link_key.begin(), link_key.end(), notif_link_key.begin());
1015   btm_sec_link_key_notification(bda_for_lk, notif_link_key, link_key_type);
1016 
1017   return true;
1018 }
1019 
1020 /** The function calculates and saves SC LTK derived from BR/EDR link key. */
smp_calculate_long_term_key_from_link_key(tSMP_CB * p_cb)1021 bool smp_calculate_long_term_key_from_link_key(tSMP_CB* p_cb) {
1022   tBTM_SEC_DEV_REC* p_dev_rec;
1023 
1024   log::verbose("addr:{}", p_cb->pairing_bda);
1025 
1026   p_dev_rec = btm_find_dev(p_cb->pairing_bda);
1027   if (p_dev_rec == NULL) {
1028     log::error("ailed to find Security Record");
1029     return false;
1030   }
1031 
1032   uint8_t br_link_key_type;
1033   br_link_key_type = BTM_SecGetDeviceLinkKeyType(p_cb->pairing_bda);
1034   if (br_link_key_type == BTM_LKEY_TYPE_IGNORE) {
1035     log::error("failed to retrieve BR link type");
1036     return false;
1037   }
1038 
1039   if ((br_link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256) &&
1040       (br_link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) {
1041     log::error("LE SC LTK can't be derived from LK {}", br_link_key_type);
1042     return false;
1043   }
1044 
1045   Octet16 rev_link_key;
1046   std::reverse_copy(p_dev_rec->sec_rec.link_key.begin(),
1047                     p_dev_rec->sec_rec.link_key.end(), rev_link_key.begin());
1048   p_cb->ltk = crypto_toolbox::link_key_to_ltk(rev_link_key,
1049                                               p_cb->key_derivation_h7_used);
1050 
1051   p_cb->sec_level = (br_link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)
1052                         ? SMP_SEC_AUTHENTICATED
1053                         : SMP_SEC_UNAUTHENTICATE;
1054   return true;
1055 }
1056 
1057 /**
1058  * This function generates nonce.
1059  */
smp_start_nonce_generation(tSMP_CB * p_cb)1060 void smp_start_nonce_generation(tSMP_CB* p_cb) {
1061   log::verbose("start generating nonce");
1062   send_ble_rand(BindOnce(
1063       [](tSMP_CB* p_cb, uint64_t rand) {
1064         memcpy(p_cb->rand.data(), (uint8_t*)&rand, sizeof(uint64_t));
1065         send_ble_rand(BindOnce(
1066             [](tSMP_CB* p_cb, uint64_t rand) {
1067               memcpy(p_cb->rand.data() + sizeof(uint64_t), (uint8_t*)&rand,
1068                      sizeof(uint64_t));
1069               log::verbose("round {}, done", p_cb->round);
1070               /* notifies SM that it has new nonce. */
1071               smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL);
1072             },
1073             p_cb));
1074       },
1075       p_cb));
1076 }
1077 
send_ble_rand(OnceCallback<void (uint64_t)> callback)1078 static void send_ble_rand(OnceCallback<void(uint64_t)> callback) {
1079   bluetooth::shim::GetController()->LeRand(
1080       get_main_thread()->BindOnce(std::move(callback)));
1081 }
1082