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