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