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_DEBUG("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 memcpy(p_cb->loc_publ_key.x, public_key.x, BT_OCTET32_LEN);
696 memcpy(p_cb->loc_publ_key.y, public_key.y, BT_OCTET32_LEN);
697
698 smp_debug_print_nbyte_little_endian(p_cb->private_key, "private",
699 BT_OCTET32_LEN);
700 smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.x, "local public(x)",
701 BT_OCTET32_LEN);
702 smp_debug_print_nbyte_little_endian(p_cb->loc_publ_key.y, "local public(y)",
703 BT_OCTET32_LEN);
704 p_cb->flags |= SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY;
705 smp_sm_event(p_cb, SMP_LOC_PUBL_KEY_CRTD_EVT, NULL);
706 }
707
708 /*******************************************************************************
709 *
710 * Function smp_compute_dhkey
711 *
712 * Description The function:
713 * - calculates a new public key using as input local private
714 * key and peer public key;
715 * - saves the new public key x-coordinate as DHKey.
716 *
717 * Returns void
718 *
719 ******************************************************************************/
smp_compute_dhkey(tSMP_CB * p_cb)720 void smp_compute_dhkey(tSMP_CB* p_cb) {
721 Point peer_publ_key, new_publ_key;
722 BT_OCTET32 private_key;
723
724 SMP_TRACE_DEBUG("%s", __func__);
725
726 memcpy(private_key, p_cb->private_key, BT_OCTET32_LEN);
727 memcpy(peer_publ_key.x, p_cb->peer_publ_key.x, BT_OCTET32_LEN);
728 memcpy(peer_publ_key.y, p_cb->peer_publ_key.y, BT_OCTET32_LEN);
729
730 ECC_PointMult(&new_publ_key, &peer_publ_key, (uint32_t*)private_key);
731
732 memcpy(p_cb->dhkey, new_publ_key.x, BT_OCTET32_LEN);
733
734 smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Old DHKey", BT_OCTET32_LEN);
735
736 smp_debug_print_nbyte_little_endian(p_cb->private_key, "private",
737 BT_OCTET32_LEN);
738 smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.x, "rem public(x)",
739 BT_OCTET32_LEN);
740 smp_debug_print_nbyte_little_endian(p_cb->peer_publ_key.y, "rem public(y)",
741 BT_OCTET32_LEN);
742 smp_debug_print_nbyte_little_endian(p_cb->dhkey, "Reverted DHKey",
743 BT_OCTET32_LEN);
744 }
745
746 /** The function calculates and saves local commmitment in CB. */
smp_calculate_local_commitment(tSMP_CB * p_cb)747 void smp_calculate_local_commitment(tSMP_CB* p_cb) {
748 uint8_t random_input;
749
750 SMP_TRACE_DEBUG("%s", __func__);
751
752 switch (p_cb->selected_association_model) {
753 case SMP_MODEL_SEC_CONN_JUSTWORKS:
754 case SMP_MODEL_SEC_CONN_NUM_COMP:
755 if (p_cb->role == HCI_ROLE_MASTER)
756 SMP_TRACE_WARNING(
757 "local commitment calc on master is not expected "
758 "for Just Works/Numeric Comparison models");
759 p_cb->commitment = crypto_toolbox::f4(
760 p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, 0);
761 break;
762 case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
763 case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
764 random_input =
765 smp_calculate_random_input(p_cb->local_random.data(), p_cb->round);
766 p_cb->commitment =
767 crypto_toolbox::f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x,
768 p_cb->rand, random_input);
769 break;
770 case SMP_MODEL_SEC_CONN_OOB:
771 SMP_TRACE_WARNING(
772 "local commitment calc is expected for OOB model BEFORE pairing");
773 p_cb->commitment = crypto_toolbox::f4(
774 p_cb->loc_publ_key.x, p_cb->loc_publ_key.x, p_cb->local_random, 0);
775 break;
776 default:
777 SMP_TRACE_ERROR("Association Model = %d is not used in LE SC",
778 p_cb->selected_association_model);
779 return;
780 }
781
782 SMP_TRACE_EVENT("local commitment calculation is completed");
783 }
784
785 /** The function calculates peer commmitment */
smp_calculate_peer_commitment(tSMP_CB * p_cb)786 Octet16 smp_calculate_peer_commitment(tSMP_CB* p_cb) {
787 uint8_t ri;
788
789 SMP_TRACE_DEBUG("%s", __func__);
790 Octet16 output;
791 switch (p_cb->selected_association_model) {
792 case SMP_MODEL_SEC_CONN_JUSTWORKS:
793 case SMP_MODEL_SEC_CONN_NUM_COMP:
794 if (p_cb->role == HCI_ROLE_SLAVE)
795 SMP_TRACE_WARNING(
796 "peer commitment calc on slave is not expected "
797 "for Just Works/Numeric Comparison models");
798 output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x,
799 p_cb->rrand, 0);
800 break;
801 case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
802 case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
803 ri = smp_calculate_random_input(p_cb->peer_random.data(), p_cb->round);
804 output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x,
805 p_cb->rrand, ri);
806 break;
807 case SMP_MODEL_SEC_CONN_OOB:
808 output = crypto_toolbox::f4(p_cb->peer_publ_key.x, p_cb->peer_publ_key.x,
809 p_cb->peer_random, 0);
810 break;
811 default:
812 SMP_TRACE_ERROR("Association Model = %d is not used in LE SC",
813 p_cb->selected_association_model);
814 return output;
815 }
816
817 SMP_TRACE_EVENT("peer commitment calculation is completed");
818 return output;
819 }
820
821 /*******************************************************************************
822 *
823 * Function smp_calculate_numeric_comparison_display_number
824 *
825 * Description The function calculates and saves number to display in
826 * numeric comparison association mode.
827 *
828 * Returns void
829 *
830 ******************************************************************************/
smp_calculate_numeric_comparison_display_number(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)831 void smp_calculate_numeric_comparison_display_number(tSMP_CB* p_cb,
832 tSMP_INT_DATA* p_data) {
833 SMP_TRACE_DEBUG("%s", __func__);
834
835 if (p_cb->role == HCI_ROLE_MASTER) {
836 p_cb->number_to_display = crypto_toolbox::g2(
837 p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, p_cb->rrand);
838 } else {
839 p_cb->number_to_display = crypto_toolbox::g2(
840 p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, p_cb->rand);
841 }
842
843 if (p_cb->number_to_display >= (BTM_MAX_PASSKEY_VAL + 1)) {
844 tSMP_INT_DATA smp_int_data;
845 smp_int_data.status = SMP_PAIR_FAIL_UNKNOWN;
846 p_cb->failure = SMP_PAIR_FAIL_UNKNOWN;
847 smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data);
848 return;
849 }
850
851 SMP_TRACE_EVENT("Number to display in numeric comparison = %d",
852 p_cb->number_to_display);
853 p_cb->cb_evt = SMP_NC_REQ_EVT;
854 tSMP_INT_DATA smp_int_data;
855 smp_int_data.passkey = p_cb->number_to_display;
856 smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, &smp_int_data);
857 return;
858 }
859
860
861 /*******************************************************************************
862 *
863 * Function smp_calculate_local_dhkey_check
864 *
865 * Description The function calculates and saves local device DHKey check
866 * value in CB.
867 * Before doing this it calls
868 * smp_calculate_f5_mackey_and_long_term_key(...).
869 * to calculate MacKey and LTK.
870 * MacKey is used in dhkey calculation.
871 *
872 * Returns void
873 *
874 ******************************************************************************/
smp_calculate_local_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)875 void smp_calculate_local_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
876 uint8_t iocap[3], a[7], b[7];
877
878 SMP_TRACE_DEBUG("%s", __func__);
879
880 smp_calculate_f5_mackey_and_long_term_key(p_cb);
881
882 smp_collect_local_io_capabilities(iocap, p_cb);
883
884 smp_collect_local_ble_address(a, p_cb);
885 smp_collect_peer_ble_address(b, p_cb);
886 p_cb->dhkey_check = crypto_toolbox::f6(p_cb->mac_key, p_cb->rand, p_cb->rrand,
887 p_cb->peer_random, iocap, a, b);
888
889 SMP_TRACE_EVENT("local DHKey check calculation is completed");
890 }
891
892 /*******************************************************************************
893 *
894 * Function smp_calculate_peer_dhkey_check
895 *
896 * Description The function calculates peer device DHKey check value.
897 *
898 * Returns void
899 *
900 ******************************************************************************/
smp_calculate_peer_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)901 void smp_calculate_peer_dhkey_check(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
902 uint8_t iocap[3], a[7], b[7];
903 tSMP_KEY key;
904
905 SMP_TRACE_DEBUG("%s", __func__);
906
907 smp_collect_peer_io_capabilities(iocap, p_cb);
908
909 smp_collect_local_ble_address(a, p_cb);
910 smp_collect_peer_ble_address(b, p_cb);
911 Octet16 param_buf = crypto_toolbox::f6(p_cb->mac_key, p_cb->rrand, p_cb->rand,
912 p_cb->local_random, iocap, b, a);
913
914 SMP_TRACE_EVENT("peer DHKey check calculation is completed");
915 #if (SMP_DEBUG == TRUE)
916 smp_debug_print_nbyte_little_endian(param_buf, "peer DHKey check",
917 OCTET16_LEN);
918 #endif
919 key.key_type = SMP_KEY_TYPE_PEER_DHK_CHCK;
920 key.p_data = param_buf.data();
921 tSMP_INT_DATA smp_int_data;
922 smp_int_data.key = key;
923 smp_sm_event(p_cb, SMP_SC_KEY_READY_EVT, &smp_int_data);
924 }
925
926
927 /*******************************************************************************
928 *
929 * Function smp_calculate_link_key_from_long_term_key
930 *
931 * Description The function calculates and saves BR/EDR link key derived
932 * from LE SC LTK.
933 *
934 * Returns false if out of resources, true in other cases.
935 *
936 ******************************************************************************/
smp_calculate_link_key_from_long_term_key(tSMP_CB * p_cb)937 bool smp_calculate_link_key_from_long_term_key(tSMP_CB* p_cb) {
938 tBTM_SEC_DEV_REC* p_dev_rec;
939 RawAddress bda_for_lk;
940 tBLE_ADDR_TYPE conn_addr_type;
941
942 SMP_TRACE_DEBUG("%s", __func__);
943
944 if (p_cb->id_addr_rcvd && p_cb->id_addr_type == BLE_ADDR_PUBLIC) {
945 SMP_TRACE_DEBUG(
946 "Use rcvd identity address as BD_ADDR of LK rcvd identity address");
947 bda_for_lk = p_cb->id_addr;
948 } else if ((BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda_for_lk,
949 &conn_addr_type)) &&
950 conn_addr_type == BLE_ADDR_PUBLIC) {
951 SMP_TRACE_DEBUG("Use rcvd connection address as BD_ADDR of LK");
952 } else {
953 SMP_TRACE_WARNING("Don't have peer public address to associate with LK");
954 return false;
955 }
956
957 p_dev_rec = btm_find_dev(p_cb->pairing_bda);
958 if (p_dev_rec == NULL) {
959 SMP_TRACE_ERROR("%s failed to find Security Record", __func__);
960 return false;
961 }
962
963 Octet16 link_key =
964 crypto_toolbox::ltk_to_link_key(p_cb->ltk, p_cb->key_derivation_h7_used);
965
966 uint8_t link_key_type;
967 if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
968 /* Secure Connections Only Mode */
969 link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
970 } else if (controller_get_interface()->supports_secure_connections()) {
971 /* both transports are SC capable */
972 if (p_cb->sec_level == SMP_SEC_AUTHENTICATED)
973 link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
974 else
975 link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB_P_256;
976 } else if (btm_cb.security_mode == BTM_SEC_MODE_SP) {
977 /* BR/EDR transport is SSP capable */
978 if (p_cb->sec_level == SMP_SEC_AUTHENTICATED)
979 link_key_type = BTM_LKEY_TYPE_AUTH_COMB;
980 else
981 link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB;
982 } else {
983 SMP_TRACE_ERROR("%s failed to update link_key. Sec Mode = %d, sm4 = 0x%02x",
984 __func__, btm_cb.security_mode, p_dev_rec->sm4);
985 return false;
986 }
987
988 link_key_type += BTM_LTK_DERIVED_LKEY_OFFSET;
989
990 Octet16 notif_link_key;
991 std::reverse_copy(link_key.begin(), link_key.end(), notif_link_key.begin());
992 btm_sec_link_key_notification(bda_for_lk, notif_link_key, link_key_type);
993
994 SMP_TRACE_EVENT("%s is completed", __func__);
995
996 return true;
997 }
998
999 /** 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)1000 bool smp_calculate_long_term_key_from_link_key(tSMP_CB* p_cb) {
1001 tBTM_SEC_DEV_REC* p_dev_rec;
1002
1003 SMP_TRACE_DEBUG("%s", __func__);
1004
1005 p_dev_rec = btm_find_dev(p_cb->pairing_bda);
1006 if (p_dev_rec == NULL) {
1007 SMP_TRACE_ERROR("%s failed to find Security Record", __func__);
1008 return false;
1009 }
1010
1011 uint8_t br_link_key_type;
1012 br_link_key_type = BTM_SecGetDeviceLinkKeyType(p_cb->pairing_bda);
1013 if (br_link_key_type == BTM_LKEY_TYPE_IGNORE) {
1014 SMP_TRACE_ERROR("%s failed to retrieve BR link type", __func__);
1015 return false;
1016 }
1017
1018 if ((br_link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256) &&
1019 (br_link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) {
1020 SMP_TRACE_ERROR("%s LE SC LTK can't be derived from LK %d", __func__,
1021 br_link_key_type);
1022 return false;
1023 }
1024
1025 Octet16 rev_link_key;
1026 std::reverse_copy(p_dev_rec->link_key.begin(), p_dev_rec->link_key.end(),
1027 rev_link_key.begin());
1028 p_cb->ltk = crypto_toolbox::link_key_to_ltk(rev_link_key,
1029 p_cb->key_derivation_h7_used);
1030
1031 p_cb->sec_level = (br_link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)
1032 ? SMP_SEC_AUTHENTICATED
1033 : SMP_SEC_UNAUTHENTICATE;
1034 SMP_TRACE_EVENT("%s is completed", __func__);
1035 return true;
1036 }
1037
1038 /**
1039 * This function generates nonce.
1040 */
smp_start_nonce_generation(tSMP_CB * p_cb)1041 void smp_start_nonce_generation(tSMP_CB* p_cb) {
1042 SMP_TRACE_DEBUG("%s", __func__);
1043 btsnd_hcic_ble_rand(Bind(
1044 [](tSMP_CB* p_cb, BT_OCTET8 rand) {
1045 memcpy(p_cb->rand.data(), rand, BT_OCTET8_LEN);
1046 btsnd_hcic_ble_rand(Bind(
1047 [](tSMP_CB* p_cb, BT_OCTET8 rand) {
1048 memcpy(p_cb->rand.data() + 8, rand, BT_OCTET8_LEN);
1049 SMP_TRACE_DEBUG("%s round %d", __func__, p_cb->round);
1050 /* notifies SM that it has new nonce. */
1051 smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL);
1052 },
1053 p_cb));
1054 },
1055 p_cb));
1056 }
1057