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