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