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