1 /******************************************************************************
2  *
3  *  Copyright (C) 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 "common/bt_target.h"
25 
26 #if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE)
27 #if SMP_DEBUG == TRUE
28 #include <stdio.h>
29 #endif
30 #include <string.h>
31 //#include "bt_utils.h"
32 #include "stack/btm_ble_api.h"
33 #include "smp_int.h"
34 #include "btm_int.h"
35 #include "btm_ble_int.h"
36 #include "stack/hcimsgs.h"
37 #include "aes.h"
38 #include "p_256_ecc_pp.h"
39 #include "device/controller.h"
40 
41 #ifndef SMP_MAX_ENC_REPEAT
42 #define SMP_MAX_ENC_REPEAT  3
43 #endif
44 
45 static void smp_rand_back(tBTM_RAND_ENC *p);
46 static void smp_generate_confirm(tSMP_CB *p_cb, tSMP_INT_DATA *p_data);
47 static void smp_generate_ltk_cont(tSMP_CB *p_cb, tSMP_INT_DATA *p_data);
48 static void smp_generate_y(tSMP_CB *p_cb, tSMP_INT_DATA *p);
49 static void smp_generate_rand_vector (tSMP_CB *p_cb, tSMP_INT_DATA *p);
50 static void smp_process_stk(tSMP_CB *p_cb, tSMP_ENC *p);
51 static void smp_calculate_comfirm_cont(tSMP_CB *p_cb, tSMP_ENC *p);
52 static void smp_process_confirm(tSMP_CB *p_cb, tSMP_ENC *p);
53 static void smp_process_compare(tSMP_CB *p_cb, tSMP_ENC *p);
54 static void smp_process_ediv(tSMP_CB *p_cb, tSMP_ENC *p);
55 static BOOLEAN smp_calculate_legacy_short_term_key(tSMP_CB *p_cb, tSMP_ENC *output);
56 static void smp_continue_private_key_creation(tSMP_CB *p_cb, tBTM_RAND_ENC *p);
57 static void smp_process_private_key(tSMP_CB *p_cb);
58 static void smp_finish_nonce_generation(tSMP_CB *p_cb);
59 static void smp_process_new_nonce(tSMP_CB *p_cb);
60 
61 static const tSMP_ACT smp_encrypt_action[] = {
62     smp_generate_compare,           /* SMP_GEN_COMPARE */
63     smp_generate_confirm,          /* SMP_GEN_CONFIRM*/
64     smp_generate_stk,               /* SMP_GEN_STK*/
65     smp_generate_ltk_cont,          /* SMP_GEN_LTK */
66     smp_generate_ltk,               /* SMP_GEN_DIV_LTK */
67     smp_generate_rand_vector,        /* SMP_GEN_RAND_V */
68     smp_generate_y,                  /* SMP_GEN_EDIV */
69     smp_generate_passkey,           /* SMP_GEN_TK */
70     smp_generate_srand_mrand_confirm, /* SMP_GEN_SRAND_MRAND */
71     smp_generate_rand_cont         /* SMP_GEN_SRAND_MRAND_CONT */
72 };
73 
74 /* If there is data saved here, then use its info instead
75  * This needs to be cleared on a successful pairing using the oob data
76  */
77 static tSMP_LOC_OOB_DATA saved_local_oob_data = {};
78 
smp_save_local_oob_data(tSMP_CB * p_cb)79 void smp_save_local_oob_data(tSMP_CB *p_cb)
80 {
81     memcpy(&saved_local_oob_data, &p_cb->sc_oob_data.loc_oob_data, sizeof(tSMP_LOC_OOB_DATA));
82 }
83 
smp_clear_local_oob_data(void)84 void smp_clear_local_oob_data(void)
85 {
86     memset(&saved_local_oob_data, 0, sizeof(tSMP_LOC_OOB_DATA));
87 }
88 
oob_data_is_empty(tSMP_LOC_OOB_DATA * data)89 static BOOLEAN oob_data_is_empty(tSMP_LOC_OOB_DATA *data)
90 {
91     tSMP_LOC_OOB_DATA empty_data = {0};
92     return (memcmp(data, &empty_data, sizeof(tSMP_LOC_OOB_DATA)) == 0);
93 }
94 
smp_get_local_oob_data(void)95 tSMP_LOC_OOB_DATA *smp_get_local_oob_data(void)
96 {
97     return &saved_local_oob_data;
98 }
99 
smp_debug_print_nbyte_little_endian(UINT8 * p,const UINT8 * key_name,UINT8 len)100 void smp_debug_print_nbyte_little_endian(UINT8 *p, const UINT8 *key_name, UINT8 len)
101 {
102 #if SMP_DEBUG == TRUE
103     int     ind, x;
104     int     col_count = 32;
105     int     row_count;
106     UINT8   p_buf[512];
107 
108     SMP_TRACE_WARNING("%s(LSB ~ MSB):\n", key_name);
109     memset(p_buf, 0, sizeof(p_buf));
110     row_count = len % col_count ? len / col_count + 1 : len / col_count;
111 
112     ind = 0;
113     for (int row = 0; row <  row_count; row++) {
114         for (int column = 0, x = 0; (ind < len) && (column < col_count); column++, ind++) {
115             x += sprintf((char *)&p_buf[x], "%02x ", p[ind]);
116         }
117         SMP_TRACE_WARNING("  [%03d]: %s", row * col_count, p_buf);
118     }
119 #endif
120 }
121 
122 #if 0 //Unused
123 void smp_debug_print_nbyte_big_endian (UINT8 *p, const UINT8 *key_name, UINT8 len)
124 {
125 #if SMP_DEBUG == TRUE
126     UINT8  p_buf[512];
127 
128     SMP_TRACE_WARNING("%s(MSB ~ LSB):", key_name);
129     memset(p_buf, 0, sizeof(p_buf));
130     nrows = len % ncols ? len / ncols + 1 : len / ncols;
131 
132     int ind = 0;
133     int  ncols = 32; /* num entries in one line */
134     int  nrows;      /* num lines */
135     int  x;
136 
137     for (int row = 0; row <  nrows; row++) {
138         for (int col = 0, x = 0; (ind < len) && (col < ncols); col++, ind++) {
139             x += sprintf ((char *)&p_buf[len - x - 1], "%02x ", p[ind]);
140         }
141         SMP_TRACE_WARNING("[%03d]: %s", row * ncols, p_buf);
142     }
143 #endif
144 }
145 #endif
146 
147 /*******************************************************************************
148 **
149 ** Function         smp_encrypt_data
150 **
151 ** Description      This function is called to encrypt data.
152 **                  It uses AES-128 encryption algorithm.
153 **                  Plain_text is encrypted using key, the result is at p_out.
154 **
155 ** Returns          void
156 **
157 *******************************************************************************/
smp_encrypt_data(UINT8 * key,UINT8 key_len,UINT8 * plain_text,UINT8 pt_len,tSMP_ENC * p_out)158 BOOLEAN smp_encrypt_data (UINT8 *key, UINT8 key_len,
159                           UINT8 *plain_text, UINT8 pt_len,
160                           tSMP_ENC *p_out)
161 {
162     aes_context ctx;
163     UINT8 *p_start = NULL;
164     UINT8 *p = NULL;
165     UINT8 *p_rev_data = NULL;    /* input data in big endilan format */
166     UINT8 *p_rev_key = NULL;     /* input key in big endilan format */
167     UINT8 *p_rev_output = NULL;  /* encrypted output in big endilan format */
168 
169     SMP_TRACE_DEBUG ("%s\n", __func__);
170     if ( (p_out == NULL ) || (key_len != SMP_ENCRYT_KEY_SIZE) ) {
171         SMP_TRACE_ERROR ("%s failed\n", __func__);
172         return FALSE;
173     }
174 
175     if ((p_start = (UINT8 *)osi_malloc((SMP_ENCRYT_DATA_SIZE * 4))) == NULL) {
176         SMP_TRACE_ERROR ("%s failed unable to allocate buffer\n", __func__);
177         return FALSE;
178     }
179 
180     if (pt_len > SMP_ENCRYT_DATA_SIZE) {
181         pt_len = SMP_ENCRYT_DATA_SIZE;
182     }
183 
184     memset(p_start, 0, SMP_ENCRYT_DATA_SIZE * 4);
185     p = p_start;
186     ARRAY_TO_STREAM (p, plain_text, pt_len); /* byte 0 to byte 15 */
187     p_rev_data = p = p_start + SMP_ENCRYT_DATA_SIZE; /* start at byte 16 */
188     REVERSE_ARRAY_TO_STREAM (p, p_start, SMP_ENCRYT_DATA_SIZE);  /* byte 16 to byte 31 */
189     p_rev_key = p; /* start at byte 32 */
190     REVERSE_ARRAY_TO_STREAM (p, key, SMP_ENCRYT_KEY_SIZE); /* byte 32 to byte 47 */
191 
192 #if SMP_DEBUG == TRUE && SMP_DEBUG_VERBOSE == TRUE
193     smp_debug_print_nbyte_little_endian(key, (const UINT8 *)"Key", SMP_ENCRYT_KEY_SIZE);
194     smp_debug_print_nbyte_little_endian(p_start, (const UINT8 *)"Plain text", SMP_ENCRYT_DATA_SIZE);
195 #endif
196     p_rev_output = p;
197     aes_set_key(p_rev_key, SMP_ENCRYT_KEY_SIZE, &ctx);
198     bluedroid_aes_encrypt(p_rev_data, p, &ctx);  /* outputs in byte 48 to byte 63 */
199 
200     p = p_out->param_buf;
201     REVERSE_ARRAY_TO_STREAM (p, p_rev_output, SMP_ENCRYT_DATA_SIZE);
202 #if SMP_DEBUG == TRUE && SMP_DEBUG_VERBOSE == TRUE
203     smp_debug_print_nbyte_little_endian(p_out->param_buf, (const UINT8 *)"Encrypted text", SMP_ENCRYT_KEY_SIZE);
204 #endif
205 
206     p_out->param_len = SMP_ENCRYT_KEY_SIZE;
207     p_out->status = HCI_SUCCESS;
208     p_out->opcode =  HCI_BLE_ENCRYPT;
209 
210     osi_free(p_start);
211 
212     return TRUE;
213 }
214 
smp_use_static_passkey(void)215 void smp_use_static_passkey(void)
216 {
217     tSMP_CB *p_cb = &smp_cb;
218     UINT8   *tt = p_cb->tk;
219     tSMP_KEY    key;
220     UINT32  passkey = p_cb->static_passkey;
221     /* save the TK */
222     memset(p_cb->tk, 0, BT_OCTET16_LEN);
223     UINT32_TO_STREAM(tt, passkey);
224 
225     key.key_type = SMP_KEY_TYPE_TK;
226     key.p_data  = p_cb->tk;
227 
228     if (p_cb->p_callback) {
229         (*p_cb->p_callback)(SMP_PASSKEY_NOTIF_EVT, p_cb->pairing_bda, (tSMP_EVT_DATA *)&passkey);
230     }
231 
232     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_PASSKEY_DISP) {
233         smp_sm_event(&smp_cb, SMP_KEY_READY_EVT, &passkey);
234     } else {
235         smp_sm_event(p_cb, SMP_KEY_READY_EVT, (tSMP_INT_DATA *)&key);
236     }
237 }
238 /*******************************************************************************
239 **
240 ** Function         smp_generate_passkey
241 **
242 ** Description      This function is called to generate passkey.
243 **
244 ** Returns          void
245 **
246 *******************************************************************************/
smp_generate_passkey(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)247 void smp_generate_passkey(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
248 {
249     UNUSED(p_data);
250 
251     if(p_cb->use_static_passkey) {
252         SMP_TRACE_DEBUG ("%s use static passkey %6d", __func__, p_cb->static_passkey);
253         smp_use_static_passkey();
254         return;
255     }
256     SMP_TRACE_DEBUG ("%s generate rand passkey", __func__);
257     p_cb->rand_enc_proc_state = SMP_GEN_TK;
258 
259     /* generate MRand or SRand */
260     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
261         smp_rand_back(NULL);
262     }
263 }
264 
265 /*******************************************************************************
266 **
267 ** Function         smp_proc_passkey
268 **
269 ** Description      This function is called to process a passkey.
270 **
271 ** Returns          void
272 **
273 *******************************************************************************/
smp_proc_passkey(tSMP_CB * p_cb,tBTM_RAND_ENC * p)274 void smp_proc_passkey(tSMP_CB *p_cb , tBTM_RAND_ENC *p)
275 {
276     UINT8   *tt = p_cb->tk;
277     tSMP_KEY    key;
278     UINT32  passkey; /* 19655 test number; */
279     UINT8 *pp = p->param_buf;
280 
281     SMP_TRACE_DEBUG ("%s", __func__);
282     STREAM_TO_UINT32(passkey, pp);
283     passkey &= ~SMP_PASSKEY_MASK;
284 
285     /* truncate by maximum value */
286     while (passkey > BTM_MAX_PASSKEY_VAL) {
287         passkey >>= 1;
288     }
289 
290     /* save the TK */
291     memset(p_cb->tk, 0, BT_OCTET16_LEN);
292     UINT32_TO_STREAM(tt, passkey);
293 
294     key.key_type = SMP_KEY_TYPE_TK;
295     key.p_data  = p_cb->tk;
296 
297     if (p_cb->p_callback) {
298         (*p_cb->p_callback)(SMP_PASSKEY_NOTIF_EVT, p_cb->pairing_bda, (tSMP_EVT_DATA *)&passkey);
299     }
300 
301     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_PASSKEY_DISP) {
302         smp_sm_event(&smp_cb, SMP_KEY_READY_EVT, &passkey);
303     } else {
304         smp_sm_event(p_cb, SMP_KEY_READY_EVT, (tSMP_INT_DATA *)&key);
305     }
306 }
307 
308 /*******************************************************************************
309 **
310 ** Function         smp_generate_stk
311 **
312 ** Description      This function is called to generate STK calculated by running
313 **                  AES with the TK value as key and a concatenation of the random
314 **                  values.
315 **
316 ** Returns          void
317 **
318 *******************************************************************************/
smp_generate_stk(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)319 void smp_generate_stk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
320 {
321     UNUSED(p_data);
322 
323     tSMP_ENC output;
324     tSMP_STATUS status = SMP_PAIR_FAIL_UNKNOWN;
325 
326     SMP_TRACE_DEBUG ("%s\n", __func__);
327 
328     if (p_cb->le_secure_connections_mode_is_used) {
329         SMP_TRACE_WARNING ("FOR LE SC LTK IS USED INSTEAD OF STK");
330         output.param_len = SMP_ENCRYT_KEY_SIZE;
331         output.status = HCI_SUCCESS;
332         output.opcode =  HCI_BLE_ENCRYPT;
333         memcpy(output.param_buf, p_cb->ltk, SMP_ENCRYT_DATA_SIZE);
334     } else if (!smp_calculate_legacy_short_term_key(p_cb, &output)) {
335         SMP_TRACE_ERROR("%s failed", __func__);
336         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
337         return;
338     }
339 
340     smp_process_stk(p_cb, &output);
341 }
342 
343 /*******************************************************************************
344 **
345 ** Function         smp_generate_srand_mrand_confirm
346 **
347 ** Description      This function is called to start the second pairing phase by
348 **                  start generating random number.
349 **
350 **
351 ** Returns          void
352 **
353 *******************************************************************************/
smp_generate_srand_mrand_confirm(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)354 void smp_generate_srand_mrand_confirm(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
355 {
356     UNUSED(p_data);
357 
358     SMP_TRACE_DEBUG ("%s\n", __func__);
359     p_cb->rand_enc_proc_state = SMP_GEN_SRAND_MRAND;
360     /* generate MRand or SRand */
361     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
362         smp_rand_back(NULL);
363     }
364 }
365 
366 /*******************************************************************************
367 **
368 ** Function         smp_generate_rand_cont
369 **
370 ** Description      This function is called to generate another 64 bits random for
371 **                  MRand or Srand.
372 **
373 ** Returns          void
374 **
375 *******************************************************************************/
smp_generate_rand_cont(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)376 void smp_generate_rand_cont(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
377 {
378     UNUSED(p_data);
379 
380     SMP_TRACE_DEBUG ("%s\n", __func__);
381     p_cb->rand_enc_proc_state = SMP_GEN_SRAND_MRAND_CONT;
382     /* generate 64 MSB of MRand or SRand */
383     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
384         smp_rand_back(NULL);
385     }
386 }
387 
388 /*******************************************************************************
389 **
390 ** Function         smp_generate_ltk
391 **
392 ** Description      This function is called:
393 **                  - in legacy pairing - to calculate LTK, starting with DIV
394 **                    generation;
395 **                  - in LE Secure Connections pairing over LE transport - to process LTK
396 **                    already generated to encrypt LE link;
397 **                  - in LE Secure Connections pairing over BR/EDR transport - to start
398 **                    BR/EDR Link Key processing.
399 **
400 ** Returns          void
401 **
402 *******************************************************************************/
smp_generate_ltk(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)403 void smp_generate_ltk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
404 {
405     UNUSED(p_data);
406 
407     BOOLEAN div_status;
408     SMP_TRACE_DEBUG ("%s\n", __FUNCTION__);
409 #if (CLASSIC_BT_INCLUDED == TRUE)
410     if (smp_get_br_state() == SMP_BR_STATE_BOND_PENDING) {
411         smp_br_process_link_key(p_cb, NULL);
412         return;
413     }
414 #endif  ///CLASSIC_BT_INCLUDED == TRUE
415     if (p_cb->le_secure_connections_mode_is_used) {
416         smp_process_secure_connection_long_term_key();
417         return;
418     }
419 
420     div_status = btm_get_local_div(p_cb->pairing_bda, &p_cb->div);
421 
422     if (div_status) {
423         smp_generate_ltk_cont(p_cb, NULL);
424     } else {
425         SMP_TRACE_DEBUG ("Generate DIV for LTK\n");
426         p_cb->rand_enc_proc_state = SMP_GEN_DIV_LTK;
427         /* generate MRand or SRand */
428         if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
429             smp_rand_back(NULL);
430         }
431     }
432 }
433 
434 /*******************************************************************************
435 **
436 ** Function         smp_compute_csrk
437 **
438 ** Description      This function is called to calculate CSRK
439 **
440 **
441 ** Returns          void
442 **
443 *******************************************************************************/
smp_compute_csrk(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)444 void smp_compute_csrk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
445 {
446     UNUSED(p_data);
447 
448     BT_OCTET16  er;
449     UINT8       buffer[4]; /* for (r || DIV)  r=1*/
450     UINT16      r = 1;
451     UINT8       *p = buffer;
452     tSMP_ENC    output;
453     tSMP_STATUS   status = SMP_PAIR_FAIL_UNKNOWN;
454 
455     SMP_TRACE_DEBUG ("smp_compute_csrk div=%x\n", p_cb->div);
456     BTM_GetDeviceEncRoot(er);
457     /* CSRK = d1(ER, DIV, 1) */
458     UINT16_TO_STREAM(p, p_cb->div);
459     UINT16_TO_STREAM(p, r);
460 
461     if (!SMP_Encrypt(er, BT_OCTET16_LEN, buffer, 4, &output)) {
462         SMP_TRACE_ERROR("smp_generate_csrk failed\n");
463         if (p_cb->smp_over_br) {
464 #if (CLASSIC_BT_INCLUDED == TRUE)
465             smp_br_state_machine_event(p_cb, SMP_BR_AUTH_CMPL_EVT, &status);
466 #endif  ///CLASSIC_BT_INCLUDED == TRUE
467         } else {
468             smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
469         }
470     } else {
471         memcpy((void *)p_cb->csrk, output.param_buf, BT_OCTET16_LEN);
472         smp_send_csrk_info(p_cb, NULL);
473     }
474 }
475 
476 /*******************************************************************************
477 **
478 ** Function         smp_generate_csrk
479 **
480 ** Description      This function is called to calculate CSRK, starting with DIV
481 **                  generation.
482 **
483 **
484 ** Returns          void
485 **
486 *******************************************************************************/
smp_generate_csrk(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)487 void smp_generate_csrk(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
488 {
489     UNUSED(p_data);
490 
491     BOOLEAN     div_status;
492 
493     SMP_TRACE_DEBUG ("smp_generate_csrk");
494 
495     div_status = btm_get_local_div(p_cb->pairing_bda, &p_cb->div);
496     if (div_status) {
497         smp_compute_csrk(p_cb, NULL);
498     } else {
499         SMP_TRACE_DEBUG ("Generate DIV for CSRK");
500         p_cb->rand_enc_proc_state = SMP_GEN_DIV_CSRK;
501         if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
502             smp_rand_back(NULL);
503         }
504     }
505 }
506 
507 /*******************************************************************************
508 ** Function         smp_concatenate_peer
509 **                  add pairing command sent from local device into p1.
510 *******************************************************************************/
smp_concatenate_local(tSMP_CB * p_cb,UINT8 ** p_data,UINT8 op_code)511 void smp_concatenate_local( tSMP_CB *p_cb, UINT8 **p_data, UINT8 op_code)
512 {
513     UINT8   *p = *p_data;
514 
515     SMP_TRACE_DEBUG ("%s\n", __func__);
516     UINT8_TO_STREAM(p, op_code);
517     UINT8_TO_STREAM(p, p_cb->local_io_capability);
518     UINT8_TO_STREAM(p, p_cb->loc_oob_flag);
519     UINT8_TO_STREAM(p, p_cb->loc_auth_req);
520     UINT8_TO_STREAM(p, p_cb->loc_enc_size);
521     UINT8_TO_STREAM(p, p_cb->local_i_key);
522     UINT8_TO_STREAM(p, p_cb->local_r_key);
523 
524     *p_data = p;
525 }
526 
527 /*******************************************************************************
528 ** Function         smp_concatenate_peer
529 **                  add pairing command received from peer device into p1.
530 *******************************************************************************/
smp_concatenate_peer(tSMP_CB * p_cb,UINT8 ** p_data,UINT8 op_code)531 void smp_concatenate_peer( tSMP_CB *p_cb, UINT8 **p_data, UINT8 op_code)
532 {
533     UINT8   *p = *p_data;
534 
535     SMP_TRACE_DEBUG ("smp_concatenate_peer \n");
536     UINT8_TO_STREAM(p, op_code);
537     UINT8_TO_STREAM(p, p_cb->peer_io_caps);
538     UINT8_TO_STREAM(p, p_cb->peer_oob_flag);
539     UINT8_TO_STREAM(p, p_cb->peer_auth_req);
540     UINT8_TO_STREAM(p, p_cb->peer_enc_size);
541     UINT8_TO_STREAM(p, p_cb->peer_i_key);
542     UINT8_TO_STREAM(p, p_cb->peer_r_key);
543 
544     *p_data = p;
545 }
546 
547 /*******************************************************************************
548 **
549 ** Function         smp_gen_p1_4_confirm
550 **
551 ** Description      Generate Confirm/Compare Step1:
552 **                  p1 = pres || preq || rat' || iat'
553 **
554 ** Returns          void
555 **
556 *******************************************************************************/
smp_gen_p1_4_confirm(tSMP_CB * p_cb,BT_OCTET16 p1)557 void smp_gen_p1_4_confirm( tSMP_CB *p_cb, BT_OCTET16 p1)
558 {
559     UINT8 *p = (UINT8 *)p1;
560     tBLE_ADDR_TYPE    addr_type = 0;
561     BD_ADDR           remote_bda;
562 
563     SMP_TRACE_DEBUG ("smp_gen_p1_4_confirm\n");
564 
565     if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, remote_bda, &addr_type)) {
566         SMP_TRACE_ERROR("can not generate confirm for unknown device\n");
567         return;
568     }
569 
570     BTM_ReadConnectionAddr( p_cb->pairing_bda, p_cb->local_bda, &p_cb->addr_type);
571 
572     if (p_cb->role == HCI_ROLE_MASTER) {
573         /* LSB : rat': initiator's(local) address type */
574         UINT8_TO_STREAM(p, p_cb->addr_type);
575         /* LSB : iat': responder's address type */
576         UINT8_TO_STREAM(p, addr_type);
577         /* concatinate preq */
578         smp_concatenate_local(p_cb, &p, SMP_OPCODE_PAIRING_REQ);
579         /* concatinate pres */
580         smp_concatenate_peer(p_cb, &p, SMP_OPCODE_PAIRING_RSP);
581     } else {
582         /* LSB : iat': initiator's address type */
583         UINT8_TO_STREAM(p, addr_type);
584         /* LSB : rat': responder's(local) address type */
585         UINT8_TO_STREAM(p, p_cb->addr_type);
586         /* concatinate preq */
587         smp_concatenate_peer(p_cb, &p, SMP_OPCODE_PAIRING_REQ);
588         /* concatinate pres */
589         smp_concatenate_local(p_cb, &p, SMP_OPCODE_PAIRING_RSP);
590     }
591 #if SMP_DEBUG == TRUE
592     SMP_TRACE_DEBUG("p1 = pres || preq || rat' || iat'\n");
593     smp_debug_print_nbyte_little_endian ((UINT8 *)p1, (const UINT8 *)"P1", 16);
594 #endif
595 }
596 
597 /*******************************************************************************
598 **
599 ** Function         smp_gen_p2_4_confirm
600 **
601 ** Description      Generate Confirm/Compare Step2:
602 **                  p2 = padding || ia || ra
603 **
604 ** Returns          void
605 **
606 *******************************************************************************/
smp_gen_p2_4_confirm(tSMP_CB * p_cb,BT_OCTET16 p2)607 void smp_gen_p2_4_confirm( tSMP_CB *p_cb, BT_OCTET16 p2)
608 {
609     UINT8       *p = (UINT8 *)p2;
610     BD_ADDR     remote_bda;
611     tBLE_ADDR_TYPE  addr_type = 0;
612     SMP_TRACE_DEBUG ("smp_gen_p2_4_confirm\n");
613     if (!BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, remote_bda, &addr_type)) {
614         SMP_TRACE_ERROR("can not generate confirm p2 for unknown device\n");
615         return;
616     }
617 
618     SMP_TRACE_DEBUG ("smp_gen_p2_4_confirm\n");
619 
620     memset(p, 0, sizeof(BT_OCTET16));
621 
622     if (p_cb->role == HCI_ROLE_MASTER) {
623         /* LSB ra */
624         BDADDR_TO_STREAM(p, remote_bda);
625         /* ia */
626         BDADDR_TO_STREAM(p, p_cb->local_bda);
627     } else {
628         /* LSB ra */
629         BDADDR_TO_STREAM(p, p_cb->local_bda);
630         /* ia */
631         BDADDR_TO_STREAM(p, remote_bda);
632     }
633 #if SMP_DEBUG == TRUE
634     SMP_TRACE_DEBUG("p2 = padding || ia || ra");
635     smp_debug_print_nbyte_little_endian(p2, (const UINT8 *)"p2", 16);
636 #endif
637 }
638 
639 /*******************************************************************************
640 **
641 ** Function         smp_calculate_comfirm
642 **
643 ** Description      This function is called to calculate Confirm value.
644 **
645 ** Returns          void
646 **
647 *******************************************************************************/
smp_calculate_comfirm(tSMP_CB * p_cb,BT_OCTET16 rand,BD_ADDR bda)648 void smp_calculate_comfirm (tSMP_CB *p_cb, BT_OCTET16 rand, BD_ADDR bda)
649 {
650     UNUSED(bda);
651 
652     BT_OCTET16      p1;
653     tSMP_ENC       output;
654     tSMP_STATUS     status = SMP_PAIR_FAIL_UNKNOWN;
655 
656     SMP_TRACE_DEBUG ("smp_calculate_comfirm \n");
657     /* generate p1 = pres || preq || rat' || iat' */
658     smp_gen_p1_4_confirm(p_cb, p1);
659 
660     /* p1 = rand XOR p1 */
661     smp_xor_128(p1, rand);
662 
663     smp_debug_print_nbyte_little_endian ((UINT8 *)p1, (const UINT8 *)"P1' = r XOR p1", 16);
664 
665     /* calculate e(k, r XOR p1), where k = TK */
666     if (!SMP_Encrypt(p_cb->tk, BT_OCTET16_LEN, p1, BT_OCTET16_LEN, &output)) {
667         SMP_TRACE_ERROR("smp_generate_csrk failed");
668         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
669     } else {
670         smp_calculate_comfirm_cont(p_cb, &output);
671     }
672 }
673 
674 /*******************************************************************************
675 **
676 ** Function         smp_calculate_comfirm_cont
677 **
678 ** Description      This function is called when SConfirm/MConfirm is generated
679 **                  proceed to send the Confirm request/response to peer device.
680 **
681 ** Returns          void
682 **
683 *******************************************************************************/
smp_calculate_comfirm_cont(tSMP_CB * p_cb,tSMP_ENC * p)684 static void smp_calculate_comfirm_cont(tSMP_CB *p_cb, tSMP_ENC *p)
685 {
686     BT_OCTET16    p2;
687     tSMP_ENC      output;
688     tSMP_STATUS     status = SMP_PAIR_FAIL_UNKNOWN;
689 
690     SMP_TRACE_DEBUG ("smp_calculate_comfirm_cont \n");
691 #if SMP_DEBUG == TRUE
692     SMP_TRACE_DEBUG("Confirm step 1 p1' = e(k, r XOR p1)  Generated\n");
693     smp_debug_print_nbyte_little_endian (p->param_buf, (const UINT8 *)"C1", 16);
694 #endif
695 
696     smp_gen_p2_4_confirm(p_cb, p2);
697 
698     /* calculate p2 = (p1' XOR p2) */
699     smp_xor_128(p2, p->param_buf);
700     smp_debug_print_nbyte_little_endian ((UINT8 *)p2, (const UINT8 *)"p2' = C1 xor p2", 16);
701 
702     /* calculate: Confirm = E(k, p1' XOR p2) */
703     if (!SMP_Encrypt(p_cb->tk, BT_OCTET16_LEN, p2, BT_OCTET16_LEN, &output)) {
704         SMP_TRACE_ERROR("smp_calculate_comfirm_cont failed\n");
705         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
706     } else {
707         SMP_TRACE_DEBUG("p_cb->rand_enc_proc_state=%d\n", p_cb->rand_enc_proc_state);
708         switch (p_cb->rand_enc_proc_state) {
709         case SMP_GEN_CONFIRM:
710             smp_process_confirm(p_cb, &output);
711             break;
712 
713         case SMP_GEN_COMPARE:
714             smp_process_compare(p_cb, &output);
715             break;
716         }
717     }
718 }
719 
720 /*******************************************************************************
721 **
722 ** Function         smp_generate_confirm
723 **
724 ** Description      This function is called when a 48 bits random number is generated
725 **                  as SRand or MRand, continue to calculate Sconfirm or MConfirm.
726 **
727 ** Returns          void
728 **
729 *******************************************************************************/
smp_generate_confirm(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)730 static void smp_generate_confirm(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
731 {
732     UNUSED(p_data);
733 
734     SMP_TRACE_DEBUG ("%s\n", __func__);
735     p_cb->rand_enc_proc_state = SMP_GEN_CONFIRM;
736     smp_debug_print_nbyte_little_endian ((UINT8 *)p_cb->rand,  (const UINT8 *)"local rand", 16);
737     smp_calculate_comfirm(p_cb, p_cb->rand, p_cb->pairing_bda);
738 }
739 
740 /*******************************************************************************
741 **
742 ** Function         smp_generate_compare
743 **
744 ** Description      This function is called to generate SConfirm for Slave device,
745 **                  or MSlave for Master device. This function can be also used for
746 **                  generating Compare number for confirm value check.
747 **
748 ** Returns          void
749 **
750 *******************************************************************************/
smp_generate_compare(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)751 void smp_generate_compare (tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
752 {
753     UNUSED(p_data);
754 
755     SMP_TRACE_DEBUG ("smp_generate_compare \n");
756     p_cb->rand_enc_proc_state = SMP_GEN_COMPARE;
757     smp_debug_print_nbyte_little_endian ((UINT8 *)p_cb->rrand,  (const UINT8 *)"peer rand", 16);
758     smp_calculate_comfirm(p_cb, p_cb->rrand, p_cb->local_bda);
759 }
760 
761 /*******************************************************************************
762 **
763 ** Function         smp_process_confirm
764 **
765 ** Description      This function is called when SConfirm/MConfirm is generated
766 **                  proceed to send the Confirm request/response to peer device.
767 **
768 ** Returns          void
769 **
770 *******************************************************************************/
smp_process_confirm(tSMP_CB * p_cb,tSMP_ENC * p)771 static void smp_process_confirm(tSMP_CB *p_cb, tSMP_ENC *p)
772 {
773     tSMP_KEY    key;
774 
775     SMP_TRACE_DEBUG ("%s\n", __FUNCTION__);
776     memcpy(p_cb->confirm, p->param_buf, BT_OCTET16_LEN);
777 
778 #if (SMP_DEBUG == TRUE)
779     SMP_TRACE_DEBUG("Confirm  Generated");
780     smp_debug_print_nbyte_little_endian ((UINT8 *)p_cb->confirm,  (const UINT8 *)"Confirm", 16);
781 #endif
782 
783     key.key_type = SMP_KEY_TYPE_CFM;
784     key.p_data = p->param_buf;
785 
786     smp_sm_event(p_cb, SMP_KEY_READY_EVT, &key);
787 
788 }
789 
790 /*******************************************************************************
791 **
792 ** Function         smp_process_compare
793 **
794 ** Description      This function is called when Compare is generated using the
795 **                  RRand and local BDA, TK information.
796 **
797 ** Returns          void
798 **
799 *******************************************************************************/
smp_process_compare(tSMP_CB * p_cb,tSMP_ENC * p)800 static void smp_process_compare(tSMP_CB *p_cb, tSMP_ENC *p)
801 {
802     tSMP_KEY    key;
803 
804     SMP_TRACE_DEBUG ("smp_process_compare \n");
805 #if (SMP_DEBUG == TRUE)
806     SMP_TRACE_DEBUG("Compare Generated\n");
807     smp_debug_print_nbyte_little_endian (p->param_buf,  (const UINT8 *)"Compare", 16);
808 #endif
809     key.key_type = SMP_KEY_TYPE_CMP;
810     key.p_data   = p->param_buf;
811     //smp_set_state(SMP_STATE_CONFIRM);
812     smp_sm_event(p_cb, SMP_KEY_READY_EVT, &key);
813 }
814 
815 /*******************************************************************************
816 **
817 ** Function         smp_process_stk
818 **
819 ** Description      This function is called when STK is generated
820 **                  proceed to send the encrypt the link using STK.
821 **
822 ** Returns          void
823 **
824 *******************************************************************************/
smp_process_stk(tSMP_CB * p_cb,tSMP_ENC * p)825 static void smp_process_stk(tSMP_CB *p_cb, tSMP_ENC *p)
826 {
827     tSMP_KEY    key;
828 
829     SMP_TRACE_DEBUG ("smp_process_stk ");
830 #if (SMP_DEBUG == TRUE)
831     SMP_TRACE_ERROR("STK Generated");
832 #endif
833     smp_mask_enc_key(p_cb->loc_enc_size, p->param_buf);
834 
835     key.key_type = SMP_KEY_TYPE_STK;
836     key.p_data   = p->param_buf;
837 
838     smp_sm_event(p_cb, SMP_KEY_READY_EVT, &key);
839 }
840 
841 /*******************************************************************************
842 **
843 ** Function         smp_generate_ltk_cont
844 **
845 ** Description      This function is to calculate LTK = d1(ER, DIV, 0)= e(ER, DIV)
846 **
847 ** Returns          void
848 **
849 *******************************************************************************/
smp_generate_ltk_cont(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)850 static void smp_generate_ltk_cont(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
851 {
852     UNUSED(p_data);
853 
854     BT_OCTET16  er;
855     tSMP_ENC    output;
856     tSMP_STATUS     status = SMP_PAIR_FAIL_UNKNOWN;
857 
858     SMP_TRACE_DEBUG ("%s\n", __func__);
859     BTM_GetDeviceEncRoot(er);
860 
861     /* LTK = d1(ER, DIV, 0)= e(ER, DIV)*/
862     if (!SMP_Encrypt(er, BT_OCTET16_LEN, (UINT8 *)&p_cb->div,
863                      sizeof(UINT16), &output)) {
864         SMP_TRACE_ERROR("%s failed\n", __func__);
865         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
866     } else {
867         /* mask the LTK */
868         smp_mask_enc_key(p_cb->loc_enc_size, output.param_buf);
869         memcpy((void *)p_cb->ltk, output.param_buf, BT_OCTET16_LEN);
870         smp_generate_rand_vector(p_cb, NULL);
871     }
872 }
873 
874 /*******************************************************************************
875 **
876 ** Function         smp_generate_y
877 **
878 ** Description      This function is to proceed generate Y = E(DHK, Rand)
879 **
880 ** Returns          void
881 **
882 *******************************************************************************/
smp_generate_y(tSMP_CB * p_cb,tSMP_INT_DATA * p)883 static void smp_generate_y(tSMP_CB *p_cb, tSMP_INT_DATA *p)
884 {
885     UNUSED(p);
886 
887     BT_OCTET16  dhk;
888     tSMP_ENC   output;
889     tSMP_STATUS     status = SMP_PAIR_FAIL_UNKNOWN;
890 
891 
892     SMP_TRACE_DEBUG ("smp_generate_y \n");
893     BTM_GetDeviceDHK(dhk);
894 
895     if (!SMP_Encrypt(dhk, BT_OCTET16_LEN, p_cb->enc_rand,
896                      BT_OCTET8_LEN, &output)) {
897         SMP_TRACE_ERROR("smp_generate_y failed");
898         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
899     } else {
900         smp_process_ediv(p_cb, &output);
901     }
902 }
903 
904 /*******************************************************************************
905 **
906 ** Function         smp_generate_rand_vector
907 **
908 ** Description      This function is called when LTK is generated, send state machine
909 **                  event to SMP.
910 **
911 ** Returns          void
912 **
913 *******************************************************************************/
smp_generate_rand_vector(tSMP_CB * p_cb,tSMP_INT_DATA * p)914 static void smp_generate_rand_vector (tSMP_CB *p_cb, tSMP_INT_DATA *p)
915 {
916     UNUSED(p);
917 
918     /* generate EDIV and rand now */
919     /* generate random vector */
920     SMP_TRACE_DEBUG ("smp_generate_rand_vector\n");
921     p_cb->rand_enc_proc_state = SMP_GEN_RAND_V;
922     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
923         smp_rand_back(NULL);
924     }
925 }
926 
927 /*******************************************************************************
928 **
929 ** Function         smp_process_ediv
930 **
931 ** Description      This function is to calculate EDIV = Y xor DIV
932 **
933 ** Returns          void
934 **
935 *******************************************************************************/
smp_process_ediv(tSMP_CB * p_cb,tSMP_ENC * p)936 static void smp_process_ediv(tSMP_CB *p_cb, tSMP_ENC *p)
937 {
938     tSMP_KEY    key;
939     UINT8 *pp = p->param_buf;
940     UINT16  y;
941 
942     SMP_TRACE_DEBUG ("smp_process_ediv ");
943     STREAM_TO_UINT16(y, pp);
944 
945     /* EDIV = Y xor DIV */
946     p_cb->ediv = p_cb->div ^ y;
947     /* send LTK ready */
948     SMP_TRACE_DEBUG("LTK ready");
949     key.key_type = SMP_KEY_TYPE_LTK;
950     key.p_data   = p->param_buf;
951 
952     smp_sm_event(p_cb, SMP_KEY_READY_EVT, &key);
953 }
954 
955 /*******************************************************************************
956 **
957 ** Function         smp_calculate_legacy_short_term_key
958 **
959 ** Description      The function calculates legacy STK.
960 **
961 ** Returns          FALSE if out of resources, TRUE in other cases.
962 **
963 *******************************************************************************/
smp_calculate_legacy_short_term_key(tSMP_CB * p_cb,tSMP_ENC * output)964 BOOLEAN smp_calculate_legacy_short_term_key(tSMP_CB *p_cb, tSMP_ENC *output)
965 {
966     BT_OCTET16 ptext;
967     UINT8 *p = ptext;
968 
969     SMP_TRACE_DEBUG ("%s\n", __func__);
970     memset(p, 0, BT_OCTET16_LEN);
971     if (p_cb->role == HCI_ROLE_MASTER) {
972         memcpy(p, p_cb->rand, BT_OCTET8_LEN);
973         memcpy(&p[BT_OCTET8_LEN], p_cb->rrand, BT_OCTET8_LEN);
974     } else {
975         memcpy(p, p_cb->rrand, BT_OCTET8_LEN);
976         memcpy(&p[BT_OCTET8_LEN], p_cb->rand, BT_OCTET8_LEN);
977     }
978 
979     BOOLEAN encrypted;
980     /* generate STK = Etk(rand|rrand)*/
981     encrypted = SMP_Encrypt( p_cb->tk, BT_OCTET16_LEN, ptext, BT_OCTET16_LEN, output);
982     if (!encrypted) {
983         SMP_TRACE_ERROR("%s failed\n", __func__);
984     }
985     return encrypted;
986 }
987 
988 /*******************************************************************************
989 **
990 ** Function         smp_create_private_key
991 **
992 ** Description      This function is called to create private key used to
993 **                  calculate public key and DHKey.
994 **                  The function starts private key creation requesting controller
995 **                  to generate [0-7] octets of private key.
996 **
997 ** Returns          void
998 **
999 *******************************************************************************/
smp_create_private_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1000 void smp_create_private_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
1001 {
1002     SMP_TRACE_DEBUG("%s", __func__);
1003 
1004     if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) {
1005         SMP_TRACE_EVENT("OOB Association Model");
1006         if (!oob_data_is_empty(&saved_local_oob_data)) {
1007             SMP_TRACE_EVENT("Found OOB data, loading keys");
1008             memcpy(&p_cb->sc_oob_data.loc_oob_data, &saved_local_oob_data, sizeof(tSMP_LOC_OOB_DATA));
1009             smp_process_private_key(p_cb);
1010             return;
1011         }
1012         SMP_TRACE_EVENT("OOB Association Model with no saved data");
1013     }
1014 
1015     p_cb->rand_enc_proc_state = SMP_GENERATE_PRIVATE_KEY_0_7;
1016     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
1017         smp_rand_back(NULL);
1018     }
1019 }
1020 
1021 /*******************************************************************************
1022 **
1023 ** Function         smp_use_oob_private_key
1024 **
1025 ** Description      This function is called
1026 **                  - to save the secret key used to calculate the public key used
1027 **                    in calculations of commitment sent OOB to a peer
1028 **                  - to use this secret key to recalculate the public key and
1029 **                    start the process of sending this public key to the peer
1030 **                  if secret/public keys have to be reused.
1031 **                  If the keys aren't supposed to be reused, continue from the
1032 **                  point from which request for OOB data was issued.
1033 **
1034 ** Returns          void
1035 **
1036 *******************************************************************************/
smp_use_oob_private_key(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1037 void smp_use_oob_private_key(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
1038 {
1039     SMP_TRACE_DEBUG ("%s req_oob_type: %d, role: %d\n",
1040                      __func__, p_cb->req_oob_type, p_cb->role);
1041 
1042     switch (p_cb->req_oob_type) {
1043     case SMP_OOB_BOTH:
1044     case SMP_OOB_LOCAL:
1045         SMP_TRACE_DEBUG("%s restore secret key\n", __func__);
1046         // copy private key in smp_process_private_key
1047         smp_process_private_key(p_cb);
1048         break;
1049     default:
1050         SMP_TRACE_DEBUG("%s create secret key anew\n", __func__);
1051         smp_set_state(SMP_STATE_PAIR_REQ_RSP);
1052         smp_decide_association_model(p_cb, NULL);
1053         break;
1054     }
1055 }
1056 
1057 /*******************************************************************************
1058 **
1059 ** Function         smp_continue_private_key_creation
1060 **
1061 ** Description      This function is used to continue private key creation.
1062 **
1063 ** Returns          void
1064 **
1065 *******************************************************************************/
smp_continue_private_key_creation(tSMP_CB * p_cb,tBTM_RAND_ENC * p)1066 void smp_continue_private_key_creation (tSMP_CB *p_cb, tBTM_RAND_ENC *p)
1067 {
1068     UINT8   state = p_cb->rand_enc_proc_state & ~0x80;
1069     SMP_TRACE_DEBUG ("%s state=0x%x\n", __func__, state);
1070 
1071     switch (state) {
1072     case SMP_GENERATE_PRIVATE_KEY_0_7:
1073         memcpy((void *)p_cb->private_key, p->param_buf, p->param_len);
1074         p_cb->rand_enc_proc_state = SMP_GENERATE_PRIVATE_KEY_8_15;
1075         if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
1076             smp_rand_back(NULL);
1077         }
1078         break;
1079 
1080     case SMP_GENERATE_PRIVATE_KEY_8_15:
1081         memcpy((void *)&p_cb->private_key[8], p->param_buf, p->param_len);
1082         p_cb->rand_enc_proc_state = SMP_GENERATE_PRIVATE_KEY_16_23;
1083         if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
1084             smp_rand_back(NULL);
1085         }
1086         break;
1087 
1088     case SMP_GENERATE_PRIVATE_KEY_16_23:
1089         memcpy((void *)&p_cb->private_key[16], p->param_buf, p->param_len);
1090         p_cb->rand_enc_proc_state = SMP_GENERATE_PRIVATE_KEY_24_31;
1091         if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
1092             smp_rand_back(NULL);
1093         }
1094         break;
1095 
1096     case SMP_GENERATE_PRIVATE_KEY_24_31:
1097         memcpy((void *)&p_cb->private_key[24], p->param_buf, p->param_len);
1098         smp_process_private_key (p_cb);
1099         break;
1100 
1101     default:
1102         break;
1103     }
1104 
1105     return;
1106 }
1107 
1108 /*******************************************************************************
1109 **
1110 ** Function         smp_process_private_key
1111 **
1112 ** Description      This function processes private key.
1113 **                  It calculates public key and notifies SM that private key /
1114 **                  public key pair is created.
1115 **
1116 ** Returns          void
1117 **
1118 *******************************************************************************/
smp_process_private_key(tSMP_CB * p_cb)1119 void smp_process_private_key(tSMP_CB *p_cb)
1120 {
1121     Point       public_key;
1122     BT_OCTET32  private_key;
1123     tSMP_LOC_OOB_DATA *p_loc_oob = &p_cb->sc_oob_data.loc_oob_data;
1124 
1125     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1126 
1127     /* if local oob data present, then restore oob private and public key */
1128     if (p_loc_oob->present) {
1129         memcpy(p_cb->private_key, p_loc_oob->private_key_used, BT_OCTET32_LEN);
1130         memcpy(p_cb->loc_publ_key.x, p_loc_oob->publ_key_used.x, BT_OCTET32_LEN);
1131         memcpy(p_cb->loc_publ_key.y, p_loc_oob->publ_key_used.y, BT_OCTET32_LEN);
1132         memcpy(p_cb->local_random, p_loc_oob->randomizer, BT_OCTET16_LEN);
1133     } else {
1134         memcpy(private_key, p_cb->private_key, BT_OCTET32_LEN);
1135         ECC_PointMult(&public_key, &(curve_p256.G), (DWORD *) private_key, KEY_LENGTH_DWORDS_P256);
1136         memcpy(p_cb->loc_publ_key.x, public_key.x, BT_OCTET32_LEN);
1137         memcpy(p_cb->loc_publ_key.y, public_key.y, BT_OCTET32_LEN);
1138     }
1139 
1140     smp_debug_print_nbyte_little_endian (p_cb->private_key, (const UINT8 *)"private",
1141                                          BT_OCTET32_LEN);
1142     smp_debug_print_nbyte_little_endian (p_cb->loc_publ_key.x, (const UINT8 *)"local public(x)",
1143                                          BT_OCTET32_LEN);
1144     smp_debug_print_nbyte_little_endian (p_cb->loc_publ_key.y, (const UINT8 *)"local public(y)",
1145                                          BT_OCTET32_LEN);
1146     p_cb->flags |= SMP_PAIR_FLAG_HAVE_LOCAL_PUBL_KEY;
1147     smp_sm_event(p_cb, SMP_LOC_PUBL_KEY_CRTD_EVT, NULL);
1148 }
1149 
1150 /*******************************************************************************
1151 **
1152 ** Function         smp_compute_dhkey
1153 **
1154 ** Description      The function:
1155 **                  - calculates a new public key using as input local private
1156 **                    key and peer public key;
1157 **                  - saves the new public key x-coordinate as DHKey.
1158 **
1159 ** Returns          void
1160 **
1161 *******************************************************************************/
smp_compute_dhkey(tSMP_CB * p_cb)1162 void smp_compute_dhkey (tSMP_CB *p_cb)
1163 {
1164     Point       peer_publ_key, new_publ_key;
1165     BT_OCTET32  private_key;
1166 
1167     SMP_TRACE_DEBUG ("%s\n", __FUNCTION__);
1168 
1169     memcpy(private_key, p_cb->private_key, BT_OCTET32_LEN);
1170     memcpy(peer_publ_key.x, p_cb->peer_publ_key.x, BT_OCTET32_LEN);
1171     memcpy(peer_publ_key.y, p_cb->peer_publ_key.y, BT_OCTET32_LEN);
1172 
1173     ECC_PointMult(&new_publ_key, &peer_publ_key, (DWORD *) private_key, KEY_LENGTH_DWORDS_P256);
1174 
1175     memcpy(p_cb->dhkey, new_publ_key.x, BT_OCTET32_LEN);
1176 
1177     smp_debug_print_nbyte_little_endian (p_cb->dhkey, (const UINT8 *)"Old DHKey",
1178                                          BT_OCTET32_LEN);
1179 
1180     smp_debug_print_nbyte_little_endian (p_cb->private_key, (const UINT8 *)"private",
1181                                          BT_OCTET32_LEN);
1182     smp_debug_print_nbyte_little_endian (p_cb->peer_publ_key.x, (const UINT8 *)"rem public(x)",
1183                                          BT_OCTET32_LEN);
1184     smp_debug_print_nbyte_little_endian (p_cb->peer_publ_key.y, (const UINT8 *)"rem public(y)",
1185                                          BT_OCTET32_LEN);
1186     smp_debug_print_nbyte_little_endian (p_cb->dhkey, (const UINT8 *)"Reverted DHKey",
1187                                          BT_OCTET32_LEN);
1188 }
1189 
1190 /*******************************************************************************
1191 **
1192 ** Function         smp_calculate_local_commitment
1193 **
1194 ** Description      The function calculates and saves local commmitment in CB.
1195 **
1196 ** Returns          void
1197 **
1198 *******************************************************************************/
smp_calculate_local_commitment(tSMP_CB * p_cb)1199 void smp_calculate_local_commitment(tSMP_CB *p_cb)
1200 {
1201     UINT8 random_input;
1202 
1203     SMP_TRACE_DEBUG("%s\n", __FUNCTION__);
1204 
1205     switch (p_cb->selected_association_model) {
1206     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1207     case SMP_MODEL_SEC_CONN_NUM_COMP:
1208         if (p_cb->role  == HCI_ROLE_MASTER) {
1209             SMP_TRACE_WARNING ("local commitment calc on master is not expected \
1210                                     for Just Works/Numeric Comparison models\n");
1211         }
1212         smp_calculate_f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand, 0,
1213                          p_cb->commitment);
1214         break;
1215     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1216     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1217         random_input = smp_calculate_random_input(p_cb->local_random, p_cb->round);
1218         smp_calculate_f4(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand,
1219                          random_input, p_cb->commitment);
1220         break;
1221     case SMP_MODEL_SEC_CONN_OOB:
1222         SMP_TRACE_WARNING ("local commitment calc is expected for OOB model BEFORE pairing\n");
1223         smp_calculate_f4(p_cb->loc_publ_key.x, p_cb->loc_publ_key.x, p_cb->local_random, 0,
1224                          p_cb->commitment);
1225         break;
1226     default:
1227         SMP_TRACE_ERROR("Association Model = %d is not used in LE SC\n",
1228                         p_cb->selected_association_model);
1229         return;
1230     }
1231 
1232     SMP_TRACE_EVENT ("local commitment calculation is completed");
1233 }
1234 
1235 /*******************************************************************************
1236 **
1237 ** Function         smp_calculate_peer_commitment
1238 **
1239 ** Description      The function calculates and saves peer commmitment at the
1240 **                  provided output buffer.
1241 **
1242 ** Returns          void
1243 **
1244 *******************************************************************************/
smp_calculate_peer_commitment(tSMP_CB * p_cb,BT_OCTET16 output_buf)1245 void smp_calculate_peer_commitment(tSMP_CB *p_cb, BT_OCTET16 output_buf)
1246 {
1247     UINT8 ri;
1248 
1249     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1250 
1251     switch (p_cb->selected_association_model) {
1252     case SMP_MODEL_SEC_CONN_JUSTWORKS:
1253     case SMP_MODEL_SEC_CONN_NUM_COMP:
1254         if (p_cb->role  == HCI_ROLE_SLAVE) {
1255             SMP_TRACE_WARNING ("peer commitment calc on slave is not expected \
1256                 for Just Works/Numeric Comparison models\n");
1257         }
1258         smp_calculate_f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, 0,
1259                          output_buf);
1260         break;
1261     case SMP_MODEL_SEC_CONN_PASSKEY_ENT:
1262     case SMP_MODEL_SEC_CONN_PASSKEY_DISP:
1263         ri = smp_calculate_random_input(p_cb->peer_random, p_cb->round);
1264         smp_calculate_f4(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand, ri,
1265                          output_buf);
1266         break;
1267     case SMP_MODEL_SEC_CONN_OOB:
1268         smp_calculate_f4(p_cb->peer_publ_key.x, p_cb->peer_publ_key.x, p_cb->peer_random, 0,
1269                          output_buf);
1270         break;
1271     default:
1272         SMP_TRACE_ERROR("Association Model = %d is not used in LE SC\n",
1273                         p_cb->selected_association_model);
1274         return;
1275     }
1276 
1277     SMP_TRACE_EVENT ("peer commitment calculation is completed\n");
1278 }
1279 
1280 /*******************************************************************************
1281 **
1282 ** Function         smp_calculate_f4
1283 **
1284 ** Description      The function calculates
1285 **                  C = f4(U, V, X, Z) = AES-CMAC (U||V||Z)
1286 **                                               X
1287 **                  where
1288 **                  input:  U is 256 bit,
1289 **                          V is 256 bit,
1290 **                          X is 128 bit,
1291 **                          Z is 8 bit,
1292 **                  output: C is 128 bit.
1293 **
1294 ** Returns          void
1295 **
1296 ** Note             The LSB is the first octet, the MSB is the last octet of
1297 **                  the AES-CMAC input/output stream.
1298 **
1299 *******************************************************************************/
smp_calculate_f4(UINT8 * u,UINT8 * v,UINT8 * x,UINT8 z,UINT8 * c)1300 void smp_calculate_f4(UINT8 *u, UINT8 *v, UINT8 *x, UINT8 z, UINT8 *c)
1301 {
1302     UINT8   msg_len = BT_OCTET32_LEN /* U size */ + BT_OCTET32_LEN /* V size */ + 1 /* Z size */;
1303     UINT8   msg[BT_OCTET32_LEN + BT_OCTET32_LEN + 1];
1304     UINT8   key[BT_OCTET16_LEN];
1305     UINT8   cmac[BT_OCTET16_LEN];
1306     UINT8   *p = NULL;
1307 #if SMP_DEBUG == TRUE
1308     UINT8   *p_prnt = NULL;
1309 #endif
1310 
1311     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1312 
1313 #if SMP_DEBUG == TRUE
1314     p_prnt = u;
1315     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"U", BT_OCTET32_LEN);
1316     p_prnt = v;
1317     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"V", BT_OCTET32_LEN);
1318     p_prnt = x;
1319     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"X", BT_OCTET16_LEN);
1320     p_prnt = &z;
1321     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"Z", 1);
1322 #endif
1323 
1324     p = msg;
1325     UINT8_TO_STREAM(p, z);
1326     ARRAY_TO_STREAM(p, v, BT_OCTET32_LEN);
1327     ARRAY_TO_STREAM(p, u, BT_OCTET32_LEN);
1328 #if SMP_DEBUG == TRUE
1329     p_prnt = msg;
1330     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"M", msg_len);
1331 #endif
1332 
1333     p = key;
1334     ARRAY_TO_STREAM(p, x, BT_OCTET16_LEN);
1335 #if SMP_DEBUG == TRUE
1336     p_prnt = key;
1337     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"K", BT_OCTET16_LEN);
1338 #endif
1339 
1340     aes_cipher_msg_auth_code(key, msg, msg_len, BT_OCTET16_LEN, cmac);
1341 #if SMP_DEBUG == TRUE
1342     p_prnt = cmac;
1343     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"AES_CMAC", BT_OCTET16_LEN);
1344 #endif
1345 
1346     p = c;
1347     ARRAY_TO_STREAM(p, cmac, BT_OCTET16_LEN);
1348 }
1349 
1350 /*******************************************************************************
1351 **
1352 ** Function         smp_calculate_numeric_comparison_display_number
1353 **
1354 ** Description      The function calculates and saves number to display in numeric
1355 **                  comparison association mode.
1356 **
1357 ** Returns          void
1358 **
1359 *******************************************************************************/
smp_calculate_numeric_comparison_display_number(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1360 void smp_calculate_numeric_comparison_display_number(tSMP_CB *p_cb,
1361         tSMP_INT_DATA *p_data)
1362 {
1363     SMP_TRACE_DEBUG ("%s", __func__);
1364 
1365     if (p_cb->role == HCI_ROLE_MASTER) {
1366         p_cb->number_to_display =
1367             smp_calculate_g2(p_cb->loc_publ_key.x, p_cb->peer_publ_key.x, p_cb->rand,
1368                              p_cb->rrand);
1369     } else {
1370         p_cb->number_to_display =
1371             smp_calculate_g2(p_cb->peer_publ_key.x, p_cb->loc_publ_key.x, p_cb->rrand,
1372                              p_cb->rand);
1373     }
1374 
1375     if (p_cb->number_to_display >= (BTM_MAX_PASSKEY_VAL + 1)) {
1376         UINT8 reason;
1377         reason = p_cb->failure = SMP_PAIR_FAIL_UNKNOWN;
1378         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason);
1379         return;
1380     }
1381 
1382     SMP_TRACE_EVENT("Number to display in numeric comparison = %d", p_cb->number_to_display);
1383     p_cb->cb_evt = SMP_NC_REQ_EVT;
1384     smp_sm_event(p_cb, SMP_SC_DSPL_NC_EVT, &p_cb->number_to_display);
1385     return;
1386 }
1387 
1388 /*******************************************************************************
1389 **
1390 ** Function         smp_calculate_g2
1391 **
1392 ** Description      The function calculates
1393 **                  g2(U, V, X, Y) = AES-CMAC (U||V||Y) mod 2**32 mod 10**6
1394 **                                           X
1395 **                  and
1396 **                  Vres = g2(U, V, X, Y) mod 10**6
1397 **                  where
1398 **                  input:  U     is 256 bit,
1399 **                          V     is 256 bit,
1400 **                          X     is 128 bit,
1401 **                          Y     is 128 bit,
1402 **
1403 ** Returns          Vres.
1404 **                  Expected value has to be in the range [0 - 999999] i.e. [0 - 0xF423F].
1405 **                  Vres = 1000000 means that the calculation fails.
1406 **
1407 ** Note             The LSB is the first octet, the MSB is the last octet of
1408 **                  the AES-CMAC input/output stream.
1409 **
1410 *******************************************************************************/
smp_calculate_g2(UINT8 * u,UINT8 * v,UINT8 * x,UINT8 * y)1411 UINT32 smp_calculate_g2(UINT8 *u, UINT8 *v, UINT8 *x, UINT8 *y)
1412 {
1413     UINT8   msg_len = BT_OCTET32_LEN /* U size */ + BT_OCTET32_LEN /* V size */
1414                       + BT_OCTET16_LEN /* Y size */;
1415     UINT8   msg[BT_OCTET32_LEN + BT_OCTET32_LEN + BT_OCTET16_LEN];
1416     UINT8   key[BT_OCTET16_LEN];
1417     UINT8   cmac[BT_OCTET16_LEN];
1418     UINT8   *p = NULL;
1419     UINT32  vres;
1420 #if SMP_DEBUG == TRUE
1421     UINT8   *p_prnt = NULL;
1422 #endif
1423 
1424     SMP_TRACE_DEBUG ("%s\n", __FUNCTION__);
1425 
1426     p = msg;
1427     ARRAY_TO_STREAM(p, y, BT_OCTET16_LEN);
1428     ARRAY_TO_STREAM(p, v, BT_OCTET32_LEN);
1429     ARRAY_TO_STREAM(p, u, BT_OCTET32_LEN);
1430 #if SMP_DEBUG == TRUE
1431     p_prnt = u;
1432     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"U", BT_OCTET32_LEN);
1433     p_prnt = v;
1434     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"V", BT_OCTET32_LEN);
1435     p_prnt = x;
1436     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"X", BT_OCTET16_LEN);
1437     p_prnt = y;
1438     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"Y", BT_OCTET16_LEN);
1439 #endif
1440 
1441     p = key;
1442     ARRAY_TO_STREAM(p, x, BT_OCTET16_LEN);
1443 #if SMP_DEBUG == TRUE
1444     p_prnt = key;
1445     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"K", BT_OCTET16_LEN);
1446 #endif
1447 
1448     if (!aes_cipher_msg_auth_code(key, msg, msg_len, BT_OCTET16_LEN, cmac)) {
1449         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
1450         return (BTM_MAX_PASSKEY_VAL + 1);
1451     }
1452 
1453 #if SMP_DEBUG == TRUE
1454     p_prnt = cmac;
1455     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"AES-CMAC", BT_OCTET16_LEN);
1456 #endif
1457 
1458     /* vres = cmac mod 2**32 mod 10**6 */
1459     p = &cmac[0];
1460     STREAM_TO_UINT32(vres, p);
1461 #if SMP_DEBUG == TRUE
1462     p_prnt = (UINT8 *) &vres;
1463     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"cmac mod 2**32", 4);
1464 #endif
1465 
1466     while (vres > BTM_MAX_PASSKEY_VAL) {
1467         vres -= (BTM_MAX_PASSKEY_VAL + 1);
1468     }
1469 #if SMP_DEBUG == TRUE
1470     p_prnt = (UINT8 *) &vres;
1471     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"cmac mod 2**32 mod 10**6", 4);
1472 #endif
1473 
1474     SMP_TRACE_ERROR("Value for numeric comparison = %d", vres);
1475     return vres;
1476 }
1477 
1478 /*******************************************************************************
1479 **
1480 ** Function         smp_calculate_f5
1481 **
1482 ** Description      The function provides two AES-CMAC that are supposed to be used as
1483 **                  - MacKey (MacKey is used in pairing DHKey check calculation);
1484 **                  - LTK (LTK is used to ecrypt the link after completion of Phase 2
1485 **                    and on reconnection, to derive BR/EDR LK).
1486 **                  The function inputs are W, N1, N2, A1, A2.
1487 **                  F5 rules:
1488 **                  - the value used as key in MacKey/LTK (T) is calculated
1489 **                    (function smp_calculate_f5_key(...));
1490 **                    The formula is:
1491 **                          T = AES-CMAC    (W)
1492 **                                      salt
1493 **                    where salt is internal parameter of smp_calculate_f5_key(...).
1494 **                  - MacKey and LTK are calculated as AES-MAC values received with the
1495 **                    key T calculated in the previous step and the plaintext message
1496 **                    built from the external parameters N1, N2, A1, A2 and the internal
1497 **                    parameters counter, keyID, length.
1498 **                    The function smp_calculate_f5_mackey_or_long_term_key(...) is used in the
1499 **                    calculations.
1500 **                    The same formula is used in calculation of MacKey and LTK and the
1501 **                    same parameter values except the value of the internal parameter
1502 **                    counter:
1503 **                    - in MacKey calculations the value is 0;
1504 **                    - in LTK calculations the value is 1.
1505 **                      MacKey  = AES-CMAC (Counter=0||keyID||N1||N2||A1||A2||Length=256)
1506 **                                        T
1507 **                      LTK     = AES-CMAC (Counter=1||keyID||N1||N2||A1||A2||Length=256)
1508 **                                        T
1509 **                  The parameters are
1510 **                  input:
1511 **                          W       is 256 bits,
1512 **                          N1      is 128 bits,
1513 **                          N2      is 128 bits,
1514 **                          A1 is 56 bit,
1515 **                          A2 is 56 bit.
1516 **                  internal:
1517 **                          Counter is 8 bits,  its value is 0 for MacKey,
1518 **                                                          1 for LTK;
1519 **                          KeyId   is 32 bits, its value is
1520 **                                              0x62746c65 (MSB~LSB);
1521 **                          Length  is 16 bits, its value is 0x0100
1522 **                                              (MSB~LSB).
1523 **                  output:
1524 **                          MacKey  is 128 bits;
1525 **                          LTK     is 128 bits
1526 **
1527 ** Returns          FALSE if out of resources, TRUE in other cases.
1528 **
1529 ** Note             The LSB is the first octet, the MSB is the last octet of
1530 **                  the AES-CMAC input/output stream.
1531 **
1532 *******************************************************************************/
smp_calculate_f5(UINT8 * w,UINT8 * n1,UINT8 * n2,UINT8 * a1,UINT8 * a2,UINT8 * mac_key,UINT8 * ltk)1533 BOOLEAN smp_calculate_f5(UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *a1, UINT8 *a2,
1534                          UINT8 *mac_key, UINT8 *ltk)
1535 {
1536     BT_OCTET16  t;    /* AES-CMAC output in smp_calculate_f5_key(...), key in */
1537     /* smp_calculate_f5_mackey_or_long_term_key(...) */
1538 #if SMP_DEBUG == TRUE
1539     UINT8   *p_prnt = NULL;
1540 #endif
1541     /* internal parameters: */
1542 
1543     /*
1544         counter is 0 for MacKey,
1545                 is 1 for LTK
1546     */
1547     UINT8   counter_mac_key[1]  = {0};
1548     UINT8   counter_ltk[1]      = {1};
1549     /*
1550         keyID   62746c65
1551     */
1552     UINT8   key_id[4] = {0x65, 0x6c, 0x74, 0x62};
1553     /*
1554         length  0100
1555     */
1556     UINT8   length[2] = {0x00, 0x01};
1557 
1558     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1559 #if SMP_DEBUG == TRUE
1560     p_prnt = w;
1561     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"W", BT_OCTET32_LEN);
1562     p_prnt = n1;
1563     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"N1", BT_OCTET16_LEN);
1564     p_prnt = n2;
1565     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"N2", BT_OCTET16_LEN);
1566     p_prnt = a1;
1567     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"A1", 7);
1568     p_prnt = a2;
1569     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *) "A2", 7);
1570 #endif
1571 
1572     if (!smp_calculate_f5_key(w, t)) {
1573         SMP_TRACE_ERROR("%s failed to calc T", __FUNCTION__);
1574         return FALSE;
1575     }
1576 #if SMP_DEBUG == TRUE
1577     p_prnt = t;
1578     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"T", BT_OCTET16_LEN);
1579 #endif
1580 
1581     if (!smp_calculate_f5_mackey_or_long_term_key(t, counter_mac_key, key_id, n1, n2, a1, a2,
1582             length, mac_key)) {
1583         SMP_TRACE_ERROR("%s failed to calc MacKey", __FUNCTION__);
1584         return FALSE;
1585     }
1586 #if SMP_DEBUG == TRUE
1587     p_prnt = mac_key;
1588     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"MacKey", BT_OCTET16_LEN);
1589 #endif
1590 
1591     if (!smp_calculate_f5_mackey_or_long_term_key(t, counter_ltk, key_id, n1, n2, a1, a2,
1592             length, ltk)) {
1593         SMP_TRACE_ERROR("%s failed to calc LTK", __FUNCTION__);
1594         return FALSE;
1595     }
1596 #if SMP_DEBUG == TRUE
1597     p_prnt = ltk;
1598     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"LTK", BT_OCTET16_LEN);
1599 #endif
1600 
1601     return TRUE;
1602 }
1603 
1604 /*******************************************************************************
1605 **
1606 ** Function         smp_calculate_f5_mackey_or_long_term_key
1607 **
1608 ** Description      The function calculates the value of MacKey or LTK by the rules
1609 **                  defined for f5 function.
1610 **                  At the moment exactly the same formula is used to calculate
1611 **                  LTK and MacKey.
1612 **                  The difference is the value of input parameter Counter:
1613 **                  - in MacKey calculations the value is 0;
1614 **                  - in LTK calculations the value is 1.
1615 **                  The formula:
1616 **                  mac = AES-CMAC (Counter||keyID||N1||N2||A1||A2||Length)
1617 **                                T
1618 **                  where
1619 **                  input:      T       is 256 bits;
1620 **                              Counter is 8 bits, its value is 0 for MacKey,
1621 **                                                              1 for LTK;
1622 **                              keyID   is 32 bits, its value is 0x62746c65;
1623 **                              N1      is 128 bits;
1624 **                              N2      is 128 bits;
1625 **                              A1      is 56 bits;
1626 **                              A2      is 56 bits;
1627 **                              Length  is 16 bits, its value is 0x0100
1628 **                  output:     LTK     is 128 bit.
1629 **
1630 ** Returns          FALSE if out of resources, TRUE in other cases.
1631 **
1632 ** Note             The LSB is the first octet, the MSB is the last octet of
1633 **                  the AES-CMAC input/output stream.
1634 **
1635 *******************************************************************************/
smp_calculate_f5_mackey_or_long_term_key(UINT8 * t,UINT8 * counter,UINT8 * key_id,UINT8 * n1,UINT8 * n2,UINT8 * a1,UINT8 * a2,UINT8 * length,UINT8 * mac)1636 BOOLEAN smp_calculate_f5_mackey_or_long_term_key(UINT8 *t, UINT8 *counter,
1637         UINT8 *key_id, UINT8 *n1, UINT8 *n2, UINT8 *a1, UINT8 *a2,
1638         UINT8 *length, UINT8 *mac)
1639 {
1640     UINT8   *p = NULL;
1641     UINT8   cmac[BT_OCTET16_LEN];
1642     UINT8   key[BT_OCTET16_LEN];
1643     UINT8   msg_len = 1 /* Counter size */ + 4 /* keyID size */ +
1644                       BT_OCTET16_LEN /* N1 size */ + BT_OCTET16_LEN /* N2 size */ +
1645                       7 /* A1 size*/ + 7 /* A2 size*/ + 2 /* Length size */;
1646     UINT8   msg[1 + 4 + BT_OCTET16_LEN + BT_OCTET16_LEN + 7 + 7 + 2];
1647     BOOLEAN ret = TRUE;
1648 #if SMP_DEBUG == TRUE
1649     UINT8   *p_prnt = NULL;
1650 #endif
1651 
1652     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1653 #if SMP_DEBUG == TRUE
1654     p_prnt = t;
1655     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"T", BT_OCTET16_LEN);
1656     p_prnt = counter;
1657     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"Counter", 1);
1658     p_prnt = key_id;
1659     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"KeyID", 4);
1660     p_prnt = n1;
1661     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"N1", BT_OCTET16_LEN);
1662     p_prnt = n2;
1663     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"N2", BT_OCTET16_LEN);
1664     p_prnt = a1;
1665     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"A1", 7);
1666     p_prnt = a2;
1667     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"A2", 7);
1668     p_prnt = length;
1669     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"Length", 2);
1670 #endif
1671 
1672     p = key;
1673     ARRAY_TO_STREAM(p, t, BT_OCTET16_LEN);
1674 #if SMP_DEBUG == TRUE
1675     p_prnt = key;
1676     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"K", BT_OCTET16_LEN);
1677 #endif
1678     p = msg;
1679     ARRAY_TO_STREAM(p, length, 2);
1680     ARRAY_TO_STREAM(p, a2, 7);
1681     ARRAY_TO_STREAM(p, a1, 7);
1682     ARRAY_TO_STREAM(p, n2, BT_OCTET16_LEN);
1683     ARRAY_TO_STREAM(p, n1, BT_OCTET16_LEN);
1684     ARRAY_TO_STREAM(p, key_id, 4);
1685     ARRAY_TO_STREAM(p, counter, 1);
1686 #if SMP_DEBUG == TRUE
1687     p_prnt = msg;
1688     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"M", msg_len);
1689 #endif
1690 
1691     if (!aes_cipher_msg_auth_code(key, msg, msg_len, BT_OCTET16_LEN, cmac)) {
1692         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
1693         ret = FALSE;
1694     }
1695 
1696 #if SMP_DEBUG == TRUE
1697     p_prnt = cmac;
1698     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"AES-CMAC", BT_OCTET16_LEN);
1699 #endif
1700 
1701     p = mac;
1702     ARRAY_TO_STREAM(p, cmac, BT_OCTET16_LEN);
1703     return ret;
1704 }
1705 
1706 /*******************************************************************************
1707 **
1708 ** Function         smp_calculate_f5_key
1709 **
1710 ** Description      The function calculates key T used in calculation of
1711 **                  MacKey and LTK (f5 output is defined as MacKey || LTK).
1712 **                  T = AES-CMAC    (W)
1713 **                              salt
1714 **                  where
1715 **                  Internal:   salt    is 128 bit.
1716 **                  input:      W       is 256 bit.
1717 **                  Output:     T       is 128 bit.
1718 **
1719 ** Returns          FALSE if out of resources, TRUE in other cases.
1720 **
1721 ** Note             The LSB is the first octet, the MSB is the last octet of
1722 **                  the AES-CMAC input/output stream.
1723 **
1724 *******************************************************************************/
smp_calculate_f5_key(UINT8 * w,UINT8 * t)1725 BOOLEAN smp_calculate_f5_key(UINT8 *w, UINT8 *t)
1726 {
1727     UINT8 *p = NULL;
1728     /* Please see 2.2.7 LE Secure Connections Key Generation Function f5 */
1729     /*
1730         salt:   6C88 8391 AAF5 A538 6037 0BDB 5A60 83BE
1731     */
1732     BT_OCTET16  salt = {
1733         0xBE, 0x83, 0x60, 0x5A, 0xDB, 0x0B, 0x37, 0x60,
1734         0x38, 0xA5, 0xF5, 0xAA, 0x91, 0x83, 0x88, 0x6C
1735     };
1736 #if SMP_DEBUG == TRUE
1737     UINT8   *p_prnt = NULL;
1738 #endif
1739 
1740     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1741 #if SMP_DEBUG == TRUE
1742     p_prnt = salt;
1743     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"salt", BT_OCTET16_LEN);
1744     p_prnt = w;
1745     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"W", BT_OCTET32_LEN);
1746 #endif
1747 
1748     BT_OCTET16 key;
1749     BT_OCTET32 msg;
1750 
1751     p = key;
1752     ARRAY_TO_STREAM(p, salt, BT_OCTET16_LEN);
1753     p = msg;
1754     ARRAY_TO_STREAM(p, w, BT_OCTET32_LEN);
1755 #if SMP_DEBUG == TRUE
1756     p_prnt = key;
1757     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"K", BT_OCTET16_LEN);
1758     p_prnt = msg;
1759     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"M", BT_OCTET32_LEN);
1760 #endif
1761 
1762     BT_OCTET16 cmac;
1763     BOOLEAN ret = TRUE;
1764     if (!aes_cipher_msg_auth_code(key, msg, BT_OCTET32_LEN, BT_OCTET16_LEN, cmac)) {
1765         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
1766         ret = FALSE;
1767     }
1768 
1769 #if SMP_DEBUG == TRUE
1770     p_prnt = cmac;
1771     smp_debug_print_nbyte_little_endian (p_prnt, (const UINT8 *)"AES-CMAC", BT_OCTET16_LEN);
1772 #endif
1773 
1774     p = t;
1775     ARRAY_TO_STREAM(p, cmac, BT_OCTET16_LEN);
1776     return ret;
1777 }
1778 
1779 /*******************************************************************************
1780 **
1781 ** Function         smp_calculate_local_dhkey_check
1782 **
1783 ** Description      The function calculates and saves local device DHKey check
1784 **                  value in CB.
1785 **                  Before doing this it calls smp_calculate_f5_mackey_and_long_term_key(...).
1786 **                  to calculate MacKey and LTK.
1787 **                  MacKey is used in dhkey calculation.
1788 **
1789 ** Returns          void
1790 **
1791 *******************************************************************************/
smp_calculate_local_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1792 void smp_calculate_local_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
1793 {
1794     UINT8   iocap[3], a[7], b[7];
1795 
1796     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1797 
1798     smp_calculate_f5_mackey_and_long_term_key(p_cb);
1799 
1800     smp_collect_local_io_capabilities(iocap, p_cb);
1801 
1802     smp_collect_local_ble_address(a, p_cb);
1803     smp_collect_peer_ble_address(b, p_cb);
1804     smp_calculate_f6(p_cb->mac_key, p_cb->rand, p_cb->rrand, p_cb->peer_random, iocap, a, b,
1805                      p_cb->dhkey_check);
1806 
1807     SMP_TRACE_EVENT ("local DHKey check calculation is completed");
1808 }
1809 
1810 /*******************************************************************************
1811 **
1812 ** Function         smp_calculate_peer_dhkey_check
1813 **
1814 ** Description      The function calculates peer device DHKey check value.
1815 **
1816 ** Returns          void
1817 **
1818 *******************************************************************************/
smp_calculate_peer_dhkey_check(tSMP_CB * p_cb,tSMP_INT_DATA * p_data)1819 void smp_calculate_peer_dhkey_check(tSMP_CB *p_cb, tSMP_INT_DATA *p_data)
1820 {
1821     UINT8       iocap[3], a[7], b[7];
1822     BT_OCTET16  param_buf;
1823     BOOLEAN     ret;
1824     tSMP_KEY    key;
1825     tSMP_STATUS status = SMP_PAIR_FAIL_UNKNOWN;
1826 
1827     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1828 
1829     smp_collect_peer_io_capabilities(iocap, p_cb);
1830 
1831     smp_collect_local_ble_address(a, p_cb);
1832     smp_collect_peer_ble_address(b, p_cb);
1833     ret = smp_calculate_f6(p_cb->mac_key, p_cb->rrand, p_cb->rand, p_cb->local_random, iocap,
1834                            b, a, param_buf);
1835 
1836     if (ret) {
1837         SMP_TRACE_EVENT ("peer DHKey check calculation is completed");
1838 #if (SMP_DEBUG == TRUE)
1839         smp_debug_print_nbyte_little_endian (param_buf, (const UINT8 *)"peer DHKey check",
1840                                              BT_OCTET16_LEN);
1841 #endif
1842         key.key_type = SMP_KEY_TYPE_PEER_DHK_CHCK;
1843         key.p_data   = param_buf;
1844         smp_sm_event(p_cb, SMP_SC_KEY_READY_EVT, &key);
1845     } else {
1846         SMP_TRACE_EVENT ("peer DHKey check calculation failed");
1847         smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &status);
1848     }
1849 }
1850 
1851 /*******************************************************************************
1852 **
1853 ** Function         smp_calculate_f6
1854 **
1855 ** Description      The function calculates
1856 **                  C = f6(W, N1, N2, R, IOcap, A1, A2) = AES-CMAC (N1||N2||R||IOcap||A1||A2)
1857 **                                                                W
1858 **                  where
1859 **                  input:  W is 128 bit,
1860 **                          N1 is 128 bit,
1861 **                          N2 is 128 bit,
1862 **                          R is 128 bit,
1863 **                          IOcap is 24 bit,
1864 **                          A1 is 56 bit,
1865 **                          A2 is 56 bit,
1866 **                  output: C is 128 bit.
1867 **
1868 ** Returns          FALSE if out of resources, TRUE in other cases.
1869 **
1870 ** Note             The LSB is the first octet, the MSB is the last octet of
1871 **                  the AES-CMAC input/output stream.
1872 **
1873 *******************************************************************************/
smp_calculate_f6(UINT8 * w,UINT8 * n1,UINT8 * n2,UINT8 * r,UINT8 * iocap,UINT8 * a1,UINT8 * a2,UINT8 * c)1874 BOOLEAN smp_calculate_f6(UINT8 *w, UINT8 *n1, UINT8 *n2, UINT8 *r, UINT8 *iocap, UINT8 *a1,
1875                          UINT8 *a2, UINT8 *c)
1876 {
1877     UINT8   *p = NULL;
1878     UINT8   msg_len = BT_OCTET16_LEN /* N1 size */ + BT_OCTET16_LEN /* N2 size */ +
1879                       BT_OCTET16_LEN /* R size */ + 3 /* IOcap size */ + 7 /* A1 size*/
1880                       + 7 /* A2 size*/;
1881     UINT8   msg[BT_OCTET16_LEN + BT_OCTET16_LEN + BT_OCTET16_LEN + 3 + 7 + 7];
1882 #if SMP_DEBUG == TRUE
1883     UINT8   *p_print = NULL;
1884 #endif
1885 
1886     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
1887 #if SMP_DEBUG == TRUE
1888     p_print = w;
1889     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"W", BT_OCTET16_LEN);
1890     p_print = n1;
1891     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"N1", BT_OCTET16_LEN);
1892     p_print = n2;
1893     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"N2", BT_OCTET16_LEN);
1894     p_print = r;
1895     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"R", BT_OCTET16_LEN);
1896     p_print = iocap;
1897     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"IOcap", 3);
1898     p_print = a1;
1899     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"A1", 7);
1900     p_print = a2;
1901     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"A2", 7);
1902 #endif
1903 
1904     UINT8 cmac[BT_OCTET16_LEN];
1905     UINT8 key[BT_OCTET16_LEN];
1906 
1907     p = key;
1908     ARRAY_TO_STREAM(p, w, BT_OCTET16_LEN);
1909 #if SMP_DEBUG == TRUE
1910     p_print = key;
1911     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"K", BT_OCTET16_LEN);
1912 #endif
1913 
1914     p = msg;
1915     ARRAY_TO_STREAM(p, a2, 7);
1916     ARRAY_TO_STREAM(p, a1, 7);
1917     ARRAY_TO_STREAM(p, iocap, 3);
1918     ARRAY_TO_STREAM(p, r, BT_OCTET16_LEN);
1919     ARRAY_TO_STREAM(p, n2, BT_OCTET16_LEN);
1920     ARRAY_TO_STREAM(p, n1, BT_OCTET16_LEN);
1921 #if SMP_DEBUG == TRUE
1922     p_print = msg;
1923     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"M", msg_len);
1924 #endif
1925 
1926     BOOLEAN ret = TRUE;
1927     if (!aes_cipher_msg_auth_code(key, msg, msg_len, BT_OCTET16_LEN, cmac)) {
1928         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
1929         ret = FALSE;
1930     }
1931 
1932 #if SMP_DEBUG == TRUE
1933     p_print = cmac;
1934     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"AES-CMAC", BT_OCTET16_LEN);
1935 #endif
1936 
1937     p = c;
1938     ARRAY_TO_STREAM(p, cmac, BT_OCTET16_LEN);
1939     return ret;
1940 }
1941 
1942 /*******************************************************************************
1943 **
1944 ** Function         smp_calculate_link_key_from_long_term_key
1945 **
1946 ** Description      The function calculates and saves BR/EDR link key derived from
1947 **                  LE SC LTK.
1948 **
1949 ** Returns          FALSE if out of resources, TRUE in other cases.
1950 **
1951 *******************************************************************************/
smp_calculate_link_key_from_long_term_key(tSMP_CB * p_cb)1952 BOOLEAN smp_calculate_link_key_from_long_term_key(tSMP_CB *p_cb)
1953 {
1954     tBTM_SEC_DEV_REC *p_dev_rec;
1955     BD_ADDR bda_for_lk;
1956     tBLE_ADDR_TYPE conn_addr_type;
1957 
1958     SMP_TRACE_DEBUG ("%s", __func__);
1959 
1960     if (p_cb->id_addr_rcvd && p_cb->id_addr_type == BLE_ADDR_PUBLIC) {
1961         SMP_TRACE_DEBUG ("Use rcvd identity address as BD_ADDR of LK rcvd identity address");
1962         memcpy(bda_for_lk, p_cb->id_addr, BD_ADDR_LEN);
1963     } else if ((BTM_ReadRemoteConnectionAddr(p_cb->pairing_bda, bda_for_lk, &conn_addr_type)) &&
1964                conn_addr_type == BLE_ADDR_PUBLIC) {
1965         SMP_TRACE_DEBUG ("Use rcvd connection address as BD_ADDR of LK");
1966     } else {
1967         SMP_TRACE_WARNING ("Don't have peer public address to associate with LK");
1968         return FALSE;
1969     }
1970 
1971     if ((p_dev_rec = btm_find_dev (p_cb->pairing_bda)) == NULL) {
1972         SMP_TRACE_ERROR("%s failed to find Security Record", __func__);
1973         return FALSE;
1974     }
1975 
1976     BT_OCTET16 intermediate_link_key;
1977     BOOLEAN ret = TRUE;
1978 
1979     ret = smp_calculate_h6(p_cb->ltk, (UINT8 *)"1pmt" /* reversed "tmp1" */, intermediate_link_key);
1980     if (!ret) {
1981         SMP_TRACE_ERROR("%s failed to derive intermediate_link_key", __func__);
1982         return ret;
1983     }
1984 
1985     BT_OCTET16 link_key;
1986     ret = smp_calculate_h6(intermediate_link_key, (UINT8 *) "rbel" /* reversed "lebr" */, link_key);
1987     if (!ret) {
1988         SMP_TRACE_ERROR("%s failed", __func__);
1989     } else {
1990         UINT8 link_key_type;
1991         if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
1992             /* Secure Connections Only Mode */
1993             link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
1994         } else if (controller_get_interface()->supports_secure_connections()) {
1995             /* both transports are SC capable */
1996             if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) {
1997                 link_key_type = BTM_LKEY_TYPE_AUTH_COMB_P_256;
1998             } else {
1999                 link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB_P_256;
2000             }
2001         } else if (btm_cb.security_mode == BTM_SEC_MODE_SP) {
2002             /* BR/EDR transport is SSP capable */
2003             if (p_cb->sec_level == SMP_SEC_AUTHENTICATED) {
2004                 link_key_type = BTM_LKEY_TYPE_AUTH_COMB;
2005             } else {
2006                 link_key_type = BTM_LKEY_TYPE_UNAUTH_COMB;
2007             }
2008         } else {
2009             SMP_TRACE_ERROR ("%s failed to update link_key. Sec Mode = %d, sm4 = 0x%02x",
2010                              __func__, btm_cb.security_mode, p_dev_rec->sm4);
2011             return FALSE;
2012         }
2013 
2014         link_key_type += BTM_LTK_DERIVED_LKEY_OFFSET;
2015 
2016         UINT8 *p;
2017         BT_OCTET16 notif_link_key;
2018         p = notif_link_key;
2019         ARRAY16_TO_STREAM(p, link_key);
2020 
2021         btm_sec_link_key_notification (bda_for_lk, notif_link_key, link_key_type);
2022 
2023         SMP_TRACE_EVENT ("%s is completed", __func__);
2024     }
2025 
2026     return ret;
2027 }
2028 
2029 /*******************************************************************************
2030 **
2031 ** Function         smp_calculate_long_term_key_from_link_key
2032 **
2033 ** Description      The function calculates and saves SC LTK derived from BR/EDR
2034 **                  link key.
2035 **
2036 ** Returns          FALSE if out of resources, TRUE in other cases.
2037 **
2038 *******************************************************************************/
smp_calculate_long_term_key_from_link_key(tSMP_CB * p_cb)2039 BOOLEAN smp_calculate_long_term_key_from_link_key(tSMP_CB *p_cb)
2040 {
2041     BOOLEAN ret = TRUE;
2042     tBTM_SEC_DEV_REC *p_dev_rec;
2043     UINT8 rev_link_key[16];
2044 
2045     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
2046 
2047     if ((p_dev_rec = btm_find_dev (p_cb->pairing_bda)) == NULL) {
2048         SMP_TRACE_ERROR("%s failed to find Security Record", __FUNCTION__);
2049         return FALSE;
2050     }
2051 
2052     UINT8 br_link_key_type;
2053     if ((br_link_key_type = BTM_SecGetDeviceLinkKeyType (p_cb->pairing_bda))
2054             == BTM_LKEY_TYPE_IGNORE) {
2055         SMP_TRACE_ERROR("%s failed to retrieve BR link type", __FUNCTION__);
2056         return FALSE;
2057     }
2058 
2059     if ((br_link_key_type != BTM_LKEY_TYPE_AUTH_COMB_P_256) &&
2060             (br_link_key_type != BTM_LKEY_TYPE_UNAUTH_COMB_P_256)) {
2061         SMP_TRACE_ERROR("%s LE SC LTK can't be derived from LK %d",
2062                         __FUNCTION__, br_link_key_type);
2063         return FALSE;
2064     }
2065 
2066     UINT8 *p1;
2067     UINT8 *p2;
2068     p1 = rev_link_key;
2069     p2 = p_dev_rec->link_key;
2070     REVERSE_ARRAY_TO_STREAM(p1, p2, 16);
2071 
2072     BT_OCTET16 intermediate_long_term_key;
2073     /* "tmp2" obtained from the spec */
2074     ret = smp_calculate_h6(rev_link_key, (UINT8 *) "2pmt" /* reversed "tmp2" */,
2075                            intermediate_long_term_key);
2076 
2077     if (!ret) {
2078         SMP_TRACE_ERROR("%s failed to derive intermediate_long_term_key", __FUNCTION__);
2079         return ret;
2080     }
2081 
2082     /* "brle" obtained from the spec */
2083     ret = smp_calculate_h6(intermediate_long_term_key, (UINT8 *) "elrb" /* reversed "brle" */,
2084                            p_cb->ltk);
2085 
2086     if (!ret) {
2087         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
2088     } else {
2089         p_cb->sec_level = (br_link_key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256)
2090                           ? SMP_SEC_AUTHENTICATED : SMP_SEC_UNAUTHENTICATE;
2091         SMP_TRACE_EVENT ("%s is completed", __FUNCTION__);
2092     }
2093 
2094     return ret;
2095 }
2096 
2097 /*******************************************************************************
2098 **
2099 ** Function         smp_calculate_h6
2100 **
2101 ** Description      The function calculates
2102 **                  C = h6(W, KeyID) = AES-CMAC (KeyID)
2103 **                                             W
2104 **                  where
2105 **                  input:  W is 128 bit,
2106 **                          KeyId is 32 bit,
2107 **                  output: C is 128 bit.
2108 **
2109 ** Returns          FALSE if out of resources, TRUE in other cases.
2110 **
2111 ** Note             The LSB is the first octet, the MSB is the last octet of
2112 **                  the AES-CMAC input/output stream.
2113 **
2114 *******************************************************************************/
smp_calculate_h6(UINT8 * w,UINT8 * keyid,UINT8 * c)2115 BOOLEAN smp_calculate_h6(UINT8 *w, UINT8 *keyid, UINT8 *c)
2116 {
2117 #if SMP_DEBUG == TRUE
2118     UINT8   *p_print = NULL;
2119 #endif
2120 
2121     SMP_TRACE_DEBUG ("%s", __FUNCTION__);
2122 #if SMP_DEBUG == TRUE
2123     p_print = w;
2124     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"W", BT_OCTET16_LEN);
2125     p_print = keyid;
2126     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"keyID", 4);
2127 #endif
2128 
2129     UINT8 *p = NULL;
2130     UINT8 key[BT_OCTET16_LEN];
2131 
2132     p = key;
2133     ARRAY_TO_STREAM(p, w, BT_OCTET16_LEN);
2134 
2135 #if SMP_DEBUG == TRUE
2136     p_print = key;
2137     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"K", BT_OCTET16_LEN);
2138 #endif
2139 
2140     UINT8 msg_len = 4 /* KeyID size */;
2141     UINT8 msg[4];
2142 
2143     p = msg;
2144     ARRAY_TO_STREAM(p, keyid, 4);
2145 
2146 #if SMP_DEBUG == TRUE
2147     p_print = msg;
2148     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *) "M", msg_len);
2149 #endif
2150 
2151     BOOLEAN ret = TRUE;
2152     UINT8 cmac[BT_OCTET16_LEN];
2153     if (!aes_cipher_msg_auth_code(key, msg, msg_len, BT_OCTET16_LEN, cmac)) {
2154         SMP_TRACE_ERROR("%s failed", __FUNCTION__);
2155         ret = FALSE;
2156     }
2157 
2158 #if SMP_DEBUG == TRUE
2159     p_print = cmac;
2160     smp_debug_print_nbyte_little_endian (p_print, (const UINT8 *)"AES-CMAC", BT_OCTET16_LEN);
2161 #endif
2162 
2163     p = c;
2164     ARRAY_TO_STREAM(p, cmac, BT_OCTET16_LEN);
2165     return ret;
2166 }
2167 
2168 /*******************************************************************************
2169 **
2170 ** Function         smp_start_nonce_generation
2171 **
2172 ** Description      This function starts nonce generation.
2173 **
2174 ** Returns          void
2175 **
2176 *******************************************************************************/
smp_start_nonce_generation(tSMP_CB * p_cb)2177 void smp_start_nonce_generation(tSMP_CB *p_cb)
2178 {
2179     SMP_TRACE_DEBUG("%s", __FUNCTION__);
2180     p_cb->rand_enc_proc_state = SMP_GEN_NONCE_0_7;
2181     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
2182         smp_rand_back(NULL);
2183     }
2184 }
2185 
2186 /*******************************************************************************
2187 **
2188 ** Function         smp_finish_nonce_generation
2189 **
2190 ** Description      This function finishes nonce generation.
2191 **
2192 ** Returns          void
2193 **
2194 *******************************************************************************/
smp_finish_nonce_generation(tSMP_CB * p_cb)2195 void smp_finish_nonce_generation(tSMP_CB *p_cb)
2196 {
2197     SMP_TRACE_DEBUG("%s", __FUNCTION__);
2198     p_cb->rand_enc_proc_state = SMP_GEN_NONCE_8_15;
2199     if (!btsnd_hcic_ble_rand((void *)smp_rand_back)) {
2200         smp_rand_back(NULL);
2201     }
2202 }
2203 
2204 /*******************************************************************************
2205 **
2206 ** Function         smp_process_new_nonce
2207 **
2208 ** Description      This function notifies SM that it has new nonce.
2209 **
2210 ** Returns          void
2211 **
2212 *******************************************************************************/
smp_process_new_nonce(tSMP_CB * p_cb)2213 void smp_process_new_nonce(tSMP_CB *p_cb)
2214 {
2215     SMP_TRACE_DEBUG ("%s round %d", __FUNCTION__, p_cb->round);
2216     smp_sm_event(p_cb, SMP_HAVE_LOC_NONCE_EVT, NULL);
2217 }
2218 
2219 /*******************************************************************************
2220 **
2221 ** Function         smp_rand_back
2222 **
2223 ** Description      This function is to process the rand command finished,
2224 **                  process the random/encrypted number for further action.
2225 **
2226 ** Returns          void
2227 **
2228 *******************************************************************************/
smp_rand_back(tBTM_RAND_ENC * p)2229 static void smp_rand_back(tBTM_RAND_ENC *p)
2230 {
2231     tSMP_CB *p_cb = &smp_cb;
2232     UINT8   *pp = p->param_buf;
2233     UINT8   failure = SMP_PAIR_FAIL_UNKNOWN;
2234     UINT8   state = p_cb->rand_enc_proc_state & ~0x80;
2235 
2236     SMP_TRACE_DEBUG ("%s state=0x%x", __FUNCTION__, state);
2237     if (p && p->status == HCI_SUCCESS) {
2238         switch (state) {
2239         case SMP_GEN_SRAND_MRAND:
2240             memcpy((void *)p_cb->rand, p->param_buf, p->param_len);
2241             smp_generate_rand_cont(p_cb, NULL);
2242             break;
2243 
2244         case SMP_GEN_SRAND_MRAND_CONT:
2245             memcpy((void *)&p_cb->rand[8], p->param_buf, p->param_len);
2246             smp_generate_confirm(p_cb, NULL);
2247             break;
2248 
2249         case SMP_GEN_DIV_LTK:
2250             STREAM_TO_UINT16(p_cb->div, pp);
2251             smp_generate_ltk_cont(p_cb, NULL);
2252             break;
2253 
2254         case SMP_GEN_DIV_CSRK:
2255             STREAM_TO_UINT16(p_cb->div, pp);
2256             smp_compute_csrk(p_cb, NULL);
2257             break;
2258 
2259         case SMP_GEN_TK:
2260             smp_proc_passkey(p_cb, p);
2261             break;
2262 
2263         case SMP_GEN_RAND_V:
2264             memcpy(p_cb->enc_rand, p->param_buf, BT_OCTET8_LEN);
2265             smp_generate_y(p_cb, NULL);
2266             break;
2267 
2268         case SMP_GENERATE_PRIVATE_KEY_0_7:
2269         case SMP_GENERATE_PRIVATE_KEY_8_15:
2270         case SMP_GENERATE_PRIVATE_KEY_16_23:
2271         case SMP_GENERATE_PRIVATE_KEY_24_31:
2272             smp_continue_private_key_creation(p_cb, p);
2273             break;
2274 
2275         case SMP_GEN_NONCE_0_7:
2276             memcpy((void *)p_cb->rand, p->param_buf, p->param_len);
2277             smp_finish_nonce_generation(p_cb);
2278             break;
2279 
2280         case SMP_GEN_NONCE_8_15:
2281             memcpy((void *)&p_cb->rand[8], p->param_buf, p->param_len);
2282             smp_process_new_nonce(p_cb);
2283             break;
2284         }
2285 
2286         return;
2287     }
2288 
2289     SMP_TRACE_ERROR("%s key generation failed: (%d)", __FUNCTION__, p_cb->rand_enc_proc_state);
2290     smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &failure);
2291 }
2292 
2293 #endif
2294