1 /* 2 * Copyright (C) 2017 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 20 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN 21 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 23 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 24 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 27 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 28 * SUCH DAMAGE. 29 * 30 */ 31 32 #define BTSTACK_FILE__ "btstack_crypto.c" 33 34 /* 35 * btstack_crypto.h 36 * 37 * Central place for all crypto-related functions with completion callbacks to allow 38 * using of MCU crypto peripherals or the Bluetooth controller 39 */ 40 41 #include "btstack_crypto.h" 42 43 #include "btstack_debug.h" 44 #include "btstack_event.h" 45 #include "btstack_linked_list.h" 46 #include "btstack_util.h" 47 #include "btstack_bool.h" 48 #include "hci.h" 49 50 // 51 // AES128 Configuration 52 // 53 54 // By default, AES128 is computed by Bluetooth Controller using HCI Command/Event asynchronously 55 // as fallback/alternative, a software implementation can be used 56 // configure ECC implementations 57 #if defined(HAVE_AES128) && defined(ENABLE_SOFTWARE_AES128) 58 #error "If you have custom AES128 implementation (HAVE_AES128), please disable software AES128 (ENABLE_SOFTWARE_AES128) in bstack_config.h" 59 #endif 60 61 #ifdef ENABLE_SOFTWARE_AES128 62 #define HAVE_AES128 63 #include "rijndael.h" 64 #endif 65 66 #ifdef HAVE_AES128 67 #define USE_BTSTACK_AES128 68 #endif 69 70 // 71 // ECC Configuration 72 // 73 74 // backwards-compatitility ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS -> ENABLE_MICRO_ECC_P256 75 #if defined(ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS) && !defined(ENABLE_MICRO_ECC_P256) 76 #define ENABLE_MICRO_ECC_P256 77 #endif 78 79 // configure ECC implementations 80 #if defined(ENABLE_MICRO_ECC_P256) && defined(HAVE_MBEDTLS_ECC_P256) 81 #error "If you have mbedTLS (HAVE_MBEDTLS_ECC_P256), please disable uECC (ENABLE_MICRO_ECC_P256) in bstack_config.h" 82 #endif 83 84 // Software ECC-P256 implementation provided by micro-ecc 85 #ifdef ENABLE_MICRO_ECC_P256 86 #define ENABLE_ECC_P256 87 #define USE_MICRO_ECC_P256 88 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION 89 #include "uECC.h" 90 #endif 91 92 // Software ECC-P256 implementation provided by mbedTLS, allow config via MBEDTLS_CONFIG_FILE 93 #ifdef HAVE_MBEDTLS_ECC_P256 94 #define ENABLE_ECC_P256 95 #define USE_MBEDTLS_ECC_P256 96 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION 97 #ifdef MBEDTLS_CONFIG_FILE 98 #include MBEDTLS_CONFIG_FILE 99 #else 100 #include "mbedtls/mbedtls_config.h" 101 #endif 102 #include "mbedtls/platform.h" 103 #include "mbedtls/ecp.h" 104 #endif 105 106 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && !defined(ENABLE_ECC_P256) 107 #define ENABLE_ECC_P256 108 #endif 109 110 // debugging 111 // #define DEBUG_CCM 112 113 typedef enum { 114 CMAC_IDLE, 115 CMAC_CALC_SUBKEYS, 116 CMAC_W4_SUBKEYS, 117 CMAC_CALC_MI, 118 CMAC_W4_MI, 119 CMAC_CALC_MLAST, 120 CMAC_W4_MLAST 121 } btstack_crypto_cmac_state_t; 122 123 typedef enum { 124 ECC_P256_KEY_GENERATION_IDLE, 125 ECC_P256_KEY_GENERATION_GENERATING_RANDOM, 126 ECC_P256_KEY_GENERATION_ACTIVE, 127 ECC_P256_KEY_GENERATION_W4_KEY, 128 ECC_P256_KEY_GENERATION_DONE, 129 } btstack_crypto_ecc_p256_key_generation_state_t; 130 131 static void btstack_crypto_run(void); 132 static void btstack_crypto_state_reset(void); 133 134 static const uint8_t zero[16] = { 0 }; 135 136 static bool btstack_crypto_initialized; 137 static bool btstack_crypto_wait_for_hci_result; 138 static btstack_linked_list_t btstack_crypto_operations; 139 static btstack_packet_callback_registration_t hci_event_callback_registration; 140 141 // state for AES-CMAC 142 #ifndef USE_BTSTACK_AES128 143 static btstack_crypto_cmac_state_t btstack_crypto_cmac_state; 144 static sm_key_t btstack_crypto_cmac_k; 145 static sm_key_t btstack_crypto_cmac_x; 146 static sm_key_t btstack_crypto_cmac_subkey; 147 static uint8_t btstack_crypto_cmac_block_current; 148 static uint8_t btstack_crypto_cmac_block_count; 149 #endif 150 151 // state for AES-CCM 152 static uint8_t btstack_crypto_ccm_s[16]; 153 154 #ifdef ENABLE_ECC_P256 155 156 static uint8_t btstack_crypto_ecc_p256_public_key[64]; 157 static uint8_t btstack_crypto_ecc_p256_random[64]; 158 static uint8_t btstack_crypto_ecc_p256_random_len; 159 static uint8_t btstack_crypto_ecc_p256_random_offset; 160 static btstack_crypto_ecc_p256_key_generation_state_t btstack_crypto_ecc_p256_key_generation_state; 161 162 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 163 static uint8_t btstack_crypto_ecc_p256_d[32]; 164 #endif 165 166 // Software ECDH implementation provided by mbedtls 167 #ifdef USE_MBEDTLS_ECC_P256 168 static mbedtls_ecp_group mbedtls_ec_group; 169 #endif 170 171 #endif /* ENABLE_ECC_P256 */ 172 173 #ifdef ENABLE_SOFTWARE_AES128 174 // AES128 using public domain rijndael implementation 175 void btstack_aes128_calc(const uint8_t * key, const uint8_t * plaintext, uint8_t * ciphertext){ 176 uint32_t rk[RKLENGTH(KEYBITS)]; 177 int nrounds = rijndaelSetupEncrypt(rk, &key[0], KEYBITS); 178 rijndaelEncrypt(rk, nrounds, plaintext, ciphertext); 179 } 180 #endif 181 182 static void btstack_crypto_done(btstack_crypto_t * btstack_crypto){ 183 btstack_linked_list_pop(&btstack_crypto_operations); 184 (*btstack_crypto->context_callback.callback)(btstack_crypto->context_callback.context); 185 } 186 187 static void btstack_crypto_cmac_shift_left_by_one_bit_inplace(int len, uint8_t * data){ 188 int i; 189 int carry = 0; 190 for (i=len-1; i >= 0 ; i--){ 191 int new_carry = data[i] >> 7; 192 data[i] = (data[i] << 1) | carry; 193 carry = new_carry; 194 } 195 } 196 197 static uint8_t btstack_crypto_cmac_get_byte(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, uint16_t pos){ 198 if (btstack_crypto_cmac->btstack_crypto.operation == BTSTACK_CRYPTO_CMAC_GENERATOR){ 199 return (*btstack_crypto_cmac->data.get_byte_callback)(pos); 200 } else { 201 return btstack_crypto_cmac->data.message[pos]; 202 } 203 } 204 205 #ifdef USE_BTSTACK_AES128 206 207 static void btstack_crypto_cmac_calc_subkeys(sm_key_t k0, sm_key_t k1, sm_key_t k2){ 208 memcpy(k1, k0, 16); 209 btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1); 210 if (k0[0] & 0x80){ 211 k1[15] ^= 0x87; 212 } 213 memcpy(k2, k1, 16); 214 btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2); 215 if (k1[0] & 0x80){ 216 k2[15] ^= 0x87; 217 } 218 } 219 220 static void btstack_crypto_cmac_calc(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac) { 221 sm_key_t k0, k1, k2; 222 uint16_t i; 223 224 btstack_aes128_calc(btstack_crypto_cmac->key, zero, k0); 225 btstack_crypto_cmac_calc_subkeys(k0, k1, k2); 226 227 uint16_t cmac_block_count = (btstack_crypto_cmac->size + 15) / 16; 228 229 // step 3: .. 230 if (cmac_block_count==0){ 231 cmac_block_count = 1; 232 } 233 234 // Step 5 235 sm_key_t cmac_x; 236 memset(cmac_x, 0, 16); 237 238 // Step 6 239 sm_key_t cmac_y; 240 int block; 241 for (block = 0 ; block < cmac_block_count-1 ; block++){ 242 for (i=0;i<16;i++){ 243 cmac_y[i] = cmac_x[i] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (block*16) + i); 244 } 245 btstack_aes128_calc(btstack_crypto_cmac->key, cmac_y, cmac_x); 246 } 247 248 // step 4: set m_last 249 sm_key_t cmac_m_last; 250 bool last_block_complete = btstack_crypto_cmac->size != 0 && (btstack_crypto_cmac->size & 0x0f) == 0; 251 if (last_block_complete){ 252 for (i=0;i<16;i++){ 253 cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16 + i) ^ k1[i]; 254 } 255 } else { 256 uint16_t valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0f; 257 for (i=0;i<16;i++){ 258 if (i < valid_octets_in_last_block){ 259 cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0) + i) ^ k2[i]; 260 continue; 261 } 262 if (i == valid_octets_in_last_block){ 263 cmac_m_last[i] = 0x80 ^ k2[i]; 264 continue; 265 } 266 cmac_m_last[i] = k2[i]; 267 } 268 } 269 270 for (i=0;i<16;i++){ 271 cmac_y[i] = cmac_x[i] ^ cmac_m_last[i]; 272 } 273 274 // Step 7 275 btstack_aes128_calc(btstack_crypto_cmac->key, cmac_y, btstack_crypto_cmac->hash); 276 } 277 #else 278 279 static void btstack_crypto_aes128_start(const sm_key_t key, const sm_key_t plaintext){ 280 uint8_t key_flipped[16]; 281 uint8_t plaintext_flipped[16]; 282 reverse_128(key, key_flipped); 283 reverse_128(plaintext, plaintext_flipped); 284 btstack_crypto_wait_for_hci_result = 1; 285 hci_send_cmd(&hci_le_encrypt, key_flipped, plaintext_flipped); 286 } 287 288 static inline void btstack_crypto_cmac_next_state(void){ 289 btstack_crypto_cmac_state = (btstack_crypto_cmac_state_t) (((int)btstack_crypto_cmac_state) + 1); 290 } 291 292 static int btstack_crypto_cmac_last_block_complete(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){ 293 uint16_t len = btstack_crypto_cmac->size; 294 if (len == 0u) return 0u; 295 return (len & 0x0fu) == 0u; 296 } 297 298 static void btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){ 299 switch (btstack_crypto_cmac_state){ 300 case CMAC_CALC_SUBKEYS: { 301 btstack_crypto_cmac_next_state(); 302 btstack_crypto_aes128_start(btstack_crypto_cmac_k, zero); 303 break; 304 } 305 case CMAC_CALC_MI: { 306 int j; 307 sm_key_t y; 308 for (j=0;j<16;j++){ 309 y[j] = btstack_crypto_cmac_x[j] ^ btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac_block_current*16u) + j); 310 } 311 btstack_crypto_cmac_block_current++; 312 btstack_crypto_cmac_next_state(); 313 btstack_crypto_aes128_start(btstack_crypto_cmac_k, y); 314 break; 315 } 316 case CMAC_CALC_MLAST: { 317 sm_key_t k1; 318 (void)memcpy(k1, btstack_crypto_cmac_subkey, 16); 319 btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k1); 320 if (btstack_crypto_cmac_subkey[0u] & 0x80u){ 321 k1[15u] ^= 0x87u; 322 } 323 sm_key_t k2; 324 (void)memcpy(k2, k1, 16); 325 btstack_crypto_cmac_shift_left_by_one_bit_inplace(16, k2); 326 if (k1[0u] & 0x80u){ 327 k2[15u] ^= 0x87u; 328 } 329 330 log_info_key("k", btstack_crypto_cmac_k); 331 log_info_key("k1", k1); 332 log_info_key("k2", k2); 333 334 // step 4: set m_last 335 int i; 336 sm_key_t btstack_crypto_cmac_m_last; 337 if (btstack_crypto_cmac_last_block_complete(btstack_crypto_cmac)){ 338 for (i=0;i<16;i++){ 339 btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, btstack_crypto_cmac->size - 16u + i) ^ k1[i]; 340 } 341 } else { 342 int valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0fu; 343 for (i=0;i<16;i++){ 344 if (i < valid_octets_in_last_block){ 345 btstack_crypto_cmac_m_last[i] = btstack_crypto_cmac_get_byte(btstack_crypto_cmac, (btstack_crypto_cmac->size & 0xfff0u) + i) ^ k2[i]; 346 continue; 347 } 348 if (i == valid_octets_in_last_block){ 349 btstack_crypto_cmac_m_last[i] = 0x80u ^ k2[i]; 350 continue; 351 } 352 btstack_crypto_cmac_m_last[i] = k2[i]; 353 } 354 } 355 sm_key_t y; 356 for (i=0;i<16;i++){ 357 y[i] = btstack_crypto_cmac_x[i] ^ btstack_crypto_cmac_m_last[i]; 358 } 359 btstack_crypto_cmac_block_current++; 360 btstack_crypto_cmac_next_state(); 361 btstack_crypto_aes128_start(btstack_crypto_cmac_k, y); 362 break; 363 } 364 default: 365 log_info("btstack_crypto_cmac_handle_aes_engine_ready called in state %u", btstack_crypto_cmac_state); 366 break; 367 } 368 } 369 370 static void btstack_crypto_cmac_handle_encryption_result(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac, sm_key_t data){ 371 switch (btstack_crypto_cmac_state){ 372 case CMAC_W4_SUBKEYS: 373 (void)memcpy(btstack_crypto_cmac_subkey, data, 16); 374 // next 375 btstack_crypto_cmac_state = (btstack_crypto_cmac_block_current < (btstack_crypto_cmac_block_count - 1u)) ? CMAC_CALC_MI : CMAC_CALC_MLAST; 376 break; 377 case CMAC_W4_MI: 378 (void)memcpy(btstack_crypto_cmac_x, data, 16); 379 btstack_crypto_cmac_state = (btstack_crypto_cmac_block_current < (btstack_crypto_cmac_block_count - 1u)) ? CMAC_CALC_MI : CMAC_CALC_MLAST; 380 break; 381 case CMAC_W4_MLAST: 382 // done 383 log_info("Setting CMAC Engine to IDLE"); 384 btstack_crypto_cmac_state = CMAC_IDLE; 385 log_info_key("CMAC", data); 386 (void)memcpy(btstack_crypto_cmac->hash, data, 16); 387 btstack_linked_list_pop(&btstack_crypto_operations); 388 (*btstack_crypto_cmac->btstack_crypto.context_callback.callback)(btstack_crypto_cmac->btstack_crypto.context_callback.context); 389 break; 390 default: 391 log_info("btstack_crypto_cmac_handle_encryption_result called in state %u", btstack_crypto_cmac_state); 392 break; 393 } 394 } 395 396 static void btstack_crypto_cmac_start(btstack_crypto_aes128_cmac_t * btstack_crypto_cmac){ 397 398 (void)memcpy(btstack_crypto_cmac_k, btstack_crypto_cmac->key, 16); 399 memset(btstack_crypto_cmac_x, 0, 16); 400 btstack_crypto_cmac_block_current = 0; 401 402 // step 2: n := ceil(len/const_Bsize); 403 btstack_crypto_cmac_block_count = (btstack_crypto_cmac->size + 15u) / 16u; 404 405 // step 3: .. 406 if (btstack_crypto_cmac_block_count==0u){ 407 btstack_crypto_cmac_block_count = 1; 408 } 409 log_info("btstack_crypto_cmac_start: len %u, block count %u", btstack_crypto_cmac->size, btstack_crypto_cmac_block_count); 410 411 // first, we need to compute l for k1, k2, and m_last 412 btstack_crypto_cmac_state = CMAC_CALC_SUBKEYS; 413 414 // let's go 415 btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac); 416 } 417 #endif 418 419 /* 420 To encrypt the message data we use Counter (CTR) mode. We first 421 define the key stream blocks by: 422 423 S_i := E( K, A_i ) for i=0, 1, 2, ... 424 425 The values A_i are formatted as follows, where the Counter field i is 426 encoded in most-significant-byte first order: 427 428 Octet Number Contents 429 ------------ --------- 430 0 Flags 431 1 ... 15-L Nonce N 432 16-L ... 15 Counter i 433 434 Bit Number Contents 435 ---------- ---------------------- 436 7 Reserved (always zero) 437 6 Reserved (always zero) 438 5 ... 3 Zero 439 2 ... 0 L' 440 */ 441 442 static void btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm_t * btstack_crypto_ccm, uint16_t counter){ 443 btstack_crypto_ccm_s[0] = 1; // L' = L - 1 444 (void)memcpy(&btstack_crypto_ccm_s[1], btstack_crypto_ccm->nonce, 13); 445 big_endian_store_16(btstack_crypto_ccm_s, 14, counter); 446 #ifdef DEBUG_CCM 447 printf("btstack_crypto_ccm_setup_a_%u\n", counter); 448 printf("%16s: ", "ai"); 449 printf_hexdump(btstack_crypto_ccm_s, 16); 450 #endif 451 } 452 453 /* 454 The first step is to compute the authentication field T. This is 455 done using CBC-MAC [MAC]. We first define a sequence of blocks B_0, 456 B_1, ..., B_n and then apply CBC-MAC to these blocks. 457 458 The first block B_0 is formatted as follows, where l(m) is encoded in 459 most-significant-byte first order: 460 461 Octet Number Contents 462 ------------ --------- 463 0 Flags 464 1 ... 15-L Nonce N 465 16-L ... 15 l(m) 466 467 Within the first block B_0, the Flags field is formatted as follows: 468 469 Bit Number Contents 470 ---------- ---------------------- 471 7 Reserved (always zero) 472 6 Adata 473 5 ... 3 M' 474 2 ... 0 L' 475 */ 476 477 static void btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm_t * btstack_crypto_ccm, uint8_t * b0){ 478 uint8_t m_prime = (btstack_crypto_ccm->auth_len - 2u) / 2u; 479 uint8_t Adata = btstack_crypto_ccm->aad_len ? 1 : 0; 480 b0[0u] = (Adata << 6u) | (m_prime << 3u) | 1u ; // Adata, M', L' = L - 1 481 (void)memcpy(&b0[1], btstack_crypto_ccm->nonce, 13); 482 big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len); 483 #ifdef DEBUG_CCM 484 printf("%16s: ", "B0"); 485 printf_hexdump(b0, 16); 486 #endif 487 } 488 489 #ifdef ENABLE_ECC_P256 490 491 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){ 492 log_info("Elliptic curve: X"); 493 log_info_hexdump(&ec_q[0],32); 494 log_info("Elliptic curve: Y"); 495 log_info_hexdump(&ec_q[32],32); 496 } 497 498 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256) 499 // @return OK 500 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){ 501 if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0; 502 log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset); 503 btstack_assert((btstack_crypto_ecc_p256_random_offset + size) <= btstack_crypto_ecc_p256_random_len); 504 uint16_t remaining_size = size; 505 uint8_t * buffer_ptr = buffer; 506 while (remaining_size) { 507 *buffer_ptr++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++]; 508 remaining_size--; 509 } 510 return 1; 511 } 512 #endif 513 #ifdef USE_MBEDTLS_ECC_P256 514 // @return error - just wrap sm_generate_f_rng 515 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){ 516 UNUSED(context); 517 return sm_generate_f_rng(buffer, size) == 0; 518 } 519 #endif /* USE_MBEDTLS_ECC_P256 */ 520 521 static void btstack_crypto_ecc_p256_generate_key_software(void){ 522 523 btstack_crypto_ecc_p256_random_offset = 0; 524 525 // generate EC key 526 #ifdef USE_MICRO_ECC_P256 527 528 #ifndef WICED_VERSION 529 log_info("set uECC RNG for initial key generation with 64 random bytes"); 530 // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it 531 uECC_set_rng(&sm_generate_f_rng); 532 #endif /* WICED_VERSION */ 533 534 #if uECC_SUPPORTS_secp256r1 535 // standard version 536 uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1()); 537 538 // disable RNG again, as returning no randmon data lets shared key generation fail 539 log_info("disable uECC RNG in standard version after key generation"); 540 uECC_set_rng(NULL); 541 #else 542 // static version 543 uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d); 544 #endif 545 #endif /* USE_MICRO_ECC_P256 */ 546 547 #ifdef USE_MBEDTLS_ECC_P256 548 mbedtls_mpi d; 549 mbedtls_ecp_point P; 550 mbedtls_mpi_init(&d); 551 mbedtls_ecp_point_init(&P); 552 int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL); 553 log_info("gen keypair %x", res); 554 mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0], 32); 555 mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32); 556 mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32); 557 mbedtls_ecp_point_free(&P); 558 mbedtls_mpi_free(&d); 559 #endif /* USE_MBEDTLS_ECC_P256 */ 560 } 561 562 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 563 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){ 564 memset(btstack_crypto_ec_p192->dhkey, 0, 32); 565 566 #ifdef USE_MICRO_ECC_P256 567 #if uECC_SUPPORTS_secp256r1 568 // standard version 569 uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1()); 570 #else 571 // static version 572 uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey); 573 #endif 574 #endif 575 576 #ifdef USE_MBEDTLS_ECC_P256 577 // da * Pb 578 mbedtls_mpi d; 579 mbedtls_ecp_point Q; 580 mbedtls_ecp_point DH; 581 mbedtls_mpi_init(&d); 582 mbedtls_ecp_point_init(&Q); 583 mbedtls_ecp_point_init(&DH); 584 mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32); 585 mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32); 586 mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32); 587 mbedtls_mpi_lset(&Q.Z, 1); 588 mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL); 589 mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32); 590 mbedtls_ecp_point_free(&DH); 591 mbedtls_mpi_free(&d); 592 mbedtls_ecp_point_free(&Q); 593 #endif 594 595 log_info("dhkey"); 596 log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32); 597 } 598 #endif 599 600 #endif 601 602 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){ 603 uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16); 604 // next block 605 btstack_crypto_ccm->counter++; 606 btstack_crypto_ccm->input += bytes_to_process; 607 btstack_crypto_ccm->output += bytes_to_process; 608 btstack_crypto_ccm->block_len -= bytes_to_process; 609 btstack_crypto_ccm->message_len -= bytes_to_process; 610 #ifdef DEBUG_CCM 611 printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len); 612 #endif 613 if (btstack_crypto_ccm->message_len == 0u){ 614 btstack_crypto_ccm->state = CCM_CALCULATE_S0; 615 } else { 616 btstack_crypto_ccm->state = state_when_done; 617 if (btstack_crypto_ccm->block_len == 0u){ 618 btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto); 619 } 620 } 621 } 622 623 // If Controller is used for AES128, data is little endian 624 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){ 625 int i; 626 for (i=0;i<16;i++){ 627 #ifdef USE_BTSTACK_AES128 628 btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[i]; 629 #else 630 btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i]; 631 #endif 632 } 633 btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto); 634 } 635 636 // If Controller is used for AES128, data is little endian 637 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){ 638 int i; 639 uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16); 640 for (i=0;i<bytes_to_process;i++){ 641 #ifdef USE_BTSTACK_AES128 642 btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[i]; 643 #else 644 btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i]; 645 #endif 646 } 647 switch (btstack_crypto_ccm->btstack_crypto.operation){ 648 case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK: 649 btstack_crypto_ccm->state = CCM_CALCULATE_XN; 650 break; 651 case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK: 652 btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN); 653 break; 654 default: 655 btstack_assert(false); 656 break; 657 } 658 } 659 660 static void btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) { 661 #ifdef DEBUG_CCM 662 printf("%16s: ", "Xn+1 AAD"); 663 printf_hexdump(btstack_crypto_ccm->x_i, 16); 664 #endif 665 // more aad? 666 if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2u)){ 667 btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN; 668 } else { 669 // done 670 btstack_crypto_done((btstack_crypto_t *) btstack_crypto_ccm); 671 } 672 } 673 674 static void btstack_crypto_ccm_handle_x1(btstack_crypto_ccm_t * btstack_crypto_ccm) { 675 #ifdef DEBUG_CCM 676 printf("%16s: ", "Xi"); 677 printf_hexdump(btstack_crypto_ccm->x_i, 16); 678 #endif 679 switch (btstack_crypto_ccm->btstack_crypto.operation){ 680 case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK: 681 btstack_crypto_ccm->aad_remainder_len = 0; 682 btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN; 683 break; 684 case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK: 685 btstack_crypto_ccm->state = CCM_CALCULATE_SN; 686 break; 687 case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK: 688 btstack_crypto_ccm->state = CCM_CALCULATE_XN; 689 break; 690 default: 691 btstack_assert(false); 692 break; 693 } 694 } 695 696 static void btstack_crypto_ccm_handle_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) { 697 #ifdef DEBUG_CCM 698 printf("%16s: ", "Xn+1"); 699 printf_hexdump(btstack_crypto_ccm->x_i, 16); 700 #endif 701 switch (btstack_crypto_ccm->btstack_crypto.operation){ 702 case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK: 703 btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN); 704 break; 705 case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK: 706 btstack_crypto_ccm->state = CCM_CALCULATE_SN; 707 break; 708 default: 709 btstack_assert(false); 710 break; 711 } 712 } 713 714 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){ 715 #ifdef DEBUG_CCM 716 printf("btstack_crypto_ccm_calc_s0\n"); 717 #endif 718 btstack_crypto_ccm->state = CCM_W4_S0; 719 btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0); 720 #ifdef USE_BTSTACK_AES128 721 uint8_t data[16]; 722 btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data); 723 btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data); 724 #else 725 btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s); 726 #endif 727 } 728 729 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){ 730 #ifdef DEBUG_CCM 731 printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter); 732 #endif 733 btstack_crypto_ccm->state = CCM_W4_SN; 734 btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter); 735 #ifdef USE_BTSTACK_AES128 736 uint8_t data[16]; 737 btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data); 738 btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data); 739 #else 740 btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s); 741 #endif 742 } 743 744 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){ 745 uint8_t btstack_crypto_ccm_buffer[16]; 746 btstack_crypto_ccm->state = CCM_W4_X1; 747 btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer); 748 #ifdef USE_BTSTACK_AES128 749 btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i); 750 btstack_crypto_ccm_handle_x1(btstack_crypto_ccm); 751 #else 752 btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer); 753 #endif 754 } 755 756 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){ 757 uint8_t btstack_crypto_ccm_buffer[16]; 758 btstack_crypto_ccm->state = CCM_W4_XN; 759 760 #ifdef DEBUG_CCM 761 printf("%16s: ", "bn"); 762 printf_hexdump(plaintext, 16); 763 #endif 764 uint8_t i; 765 uint16_t bytes_to_decrypt = btstack_crypto_ccm->block_len; 766 // use explicit min implementation as c-stat worried about out-of-bounds-reads 767 if (bytes_to_decrypt > 16u) { 768 bytes_to_decrypt = 16; 769 } 770 for (i = 0; i < bytes_to_decrypt ; i++){ 771 btstack_crypto_ccm_buffer[i] = btstack_crypto_ccm->x_i[i] ^ plaintext[i]; 772 } 773 (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i], 774 16u - bytes_to_decrypt); 775 #ifdef DEBUG_CCM 776 printf("%16s: ", "Xn XOR bn"); 777 printf_hexdump(btstack_crypto_ccm_buffer, 16); 778 #endif 779 780 #ifdef USE_BTSTACK_AES128 781 btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i); 782 btstack_crypto_ccm_handle_xn(btstack_crypto_ccm); 783 #else 784 btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer); 785 #endif 786 } 787 788 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){ 789 // store length 790 if (btstack_crypto_ccm->aad_offset == 0u){ 791 uint8_t len_buffer[2]; 792 big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len); 793 btstack_crypto_ccm->x_i[0] ^= len_buffer[0]; 794 btstack_crypto_ccm->x_i[1] ^= len_buffer[1]; 795 btstack_crypto_ccm->aad_remainder_len += 2u; 796 btstack_crypto_ccm->aad_offset += 2u; 797 } 798 799 // fill from input 800 uint16_t bytes_free = 16u - btstack_crypto_ccm->aad_remainder_len; 801 uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len); 802 while (bytes_to_copy){ 803 btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++; 804 btstack_crypto_ccm->aad_offset++; 805 btstack_crypto_ccm->block_len--; 806 bytes_to_copy--; 807 bytes_free--; 808 } 809 810 // if last block, fill with zeros 811 if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2u)){ 812 btstack_crypto_ccm->aad_remainder_len = 16; 813 } 814 // if not full, notify done 815 if (btstack_crypto_ccm->aad_remainder_len < 16u){ 816 btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto); 817 return; 818 } 819 820 // encrypt block 821 #ifdef DEBUG_CCM 822 printf("%16s: ", "Xn XOR Bn (aad)"); 823 printf_hexdump(btstack_crypto_ccm->x_i, 16); 824 #endif 825 826 btstack_crypto_ccm->aad_remainder_len = 0; 827 btstack_crypto_ccm->state = CCM_W4_AAD_XN; 828 #ifdef USE_BTSTACK_AES128 829 btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i, btstack_crypto_ccm->x_i); 830 btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm); 831 #else 832 btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i); 833 #endif 834 } 835 836 static void btstack_crypto_run(void){ 837 838 btstack_crypto_aes128_t * btstack_crypto_aes128; 839 btstack_crypto_ccm_t * btstack_crypto_ccm; 840 btstack_crypto_aes128_cmac_t * btstack_crypto_cmac; 841 #ifdef ENABLE_ECC_P256 842 btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192; 843 #endif 844 845 // stack up and running? 846 if (hci_get_state() != HCI_STATE_WORKING) return; 847 848 // try to do as much as possible 849 while (true){ 850 851 // anything to do? 852 if (btstack_linked_list_empty(&btstack_crypto_operations)) return; 853 854 // already active? 855 if (btstack_crypto_wait_for_hci_result) return; 856 857 // can send a command? 858 if (!hci_can_send_command_packet_now()) return; 859 860 // ok, find next task 861 btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 862 switch (btstack_crypto->operation){ 863 case BTSTACK_CRYPTO_RANDOM: 864 btstack_crypto_wait_for_hci_result = true; 865 hci_send_cmd(&hci_le_rand); 866 break; 867 case BTSTACK_CRYPTO_AES128: 868 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto; 869 #ifdef USE_BTSTACK_AES128 870 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext); 871 btstack_crypto_done(btstack_crypto); 872 #else 873 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext); 874 #endif 875 break; 876 877 case BTSTACK_CRYPTO_CMAC_MESSAGE: 878 case BTSTACK_CRYPTO_CMAC_GENERATOR: 879 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto; 880 #ifdef USE_BTSTACK_AES128 881 btstack_crypto_cmac_calc( btstack_crypto_cmac ); 882 btstack_crypto_done(btstack_crypto); 883 #else 884 btstack_crypto_wait_for_hci_result = 1; 885 if (btstack_crypto_cmac_state == CMAC_IDLE){ 886 btstack_crypto_cmac_start(btstack_crypto_cmac); 887 } else { 888 btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac); 889 } 890 #endif 891 break; 892 893 case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK: 894 case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK: 895 case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK: 896 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto; 897 switch (btstack_crypto_ccm->state){ 898 case CCM_CALCULATE_AAD_XN: 899 #ifdef DEBUG_CCM 900 printf("CCM_CALCULATE_AAD_XN\n"); 901 #endif 902 btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm); 903 break; 904 case CCM_CALCULATE_X1: 905 #ifdef DEBUG_CCM 906 printf("CCM_CALCULATE_X1\n"); 907 #endif 908 btstack_crypto_ccm_calc_x1(btstack_crypto_ccm); 909 break; 910 case CCM_CALCULATE_S0: 911 #ifdef DEBUG_CCM 912 printf("CCM_CALCULATE_S0\n"); 913 #endif 914 btstack_crypto_ccm_calc_s0(btstack_crypto_ccm); 915 break; 916 case CCM_CALCULATE_SN: 917 #ifdef DEBUG_CCM 918 printf("CCM_CALCULATE_SN\n"); 919 #endif 920 btstack_crypto_ccm_calc_sn(btstack_crypto_ccm); 921 break; 922 case CCM_CALCULATE_XN: 923 #ifdef DEBUG_CCM 924 printf("CCM_CALCULATE_XN\n"); 925 #endif 926 btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output); 927 break; 928 default: 929 break; 930 } 931 break; 932 933 #ifdef ENABLE_ECC_P256 934 case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY: 935 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto; 936 switch (btstack_crypto_ecc_p256_key_generation_state){ 937 case ECC_P256_KEY_GENERATION_DONE: 938 // done 939 btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key); 940 (void)memcpy(btstack_crypto_ec_p192->public_key, 941 btstack_crypto_ecc_p256_public_key, 64); 942 btstack_linked_list_pop(&btstack_crypto_operations); 943 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context); 944 break; 945 case ECC_P256_KEY_GENERATION_IDLE: 946 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 947 log_info("start ecc random"); 948 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM; 949 btstack_crypto_ecc_p256_random_len = 0; 950 btstack_crypto_wait_for_hci_result = true; 951 hci_send_cmd(&hci_le_rand); 952 #else 953 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY; 954 btstack_crypto_wait_for_hci_result = 1; 955 hci_send_cmd(&hci_le_read_local_p256_public_key); 956 #endif 957 break; 958 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 959 case ECC_P256_KEY_GENERATION_GENERATING_RANDOM: 960 log_info("more ecc random"); 961 btstack_crypto_wait_for_hci_result = true; 962 hci_send_cmd(&hci_le_rand); 963 break; 964 #endif 965 default: 966 break; 967 } 968 break; 969 case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY: 970 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto; 971 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 972 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192); 973 // done 974 btstack_linked_list_pop(&btstack_crypto_operations); 975 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context); 976 #else 977 btstack_crypto_wait_for_hci_result = 1; 978 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]); 979 #endif 980 break; 981 982 #endif /* ENABLE_ECC_P256 */ 983 984 default: 985 break; 986 } 987 } 988 } 989 990 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){ 991 btstack_crypto_random_t * btstack_crypto_random; 992 btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 993 uint16_t bytes_to_copy; 994 if (!btstack_crypto) return; 995 switch (btstack_crypto->operation){ 996 case BTSTACK_CRYPTO_RANDOM: 997 btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto; 998 bytes_to_copy = btstack_min(btstack_crypto_random->size, len); 999 (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy); 1000 btstack_crypto_random->buffer += bytes_to_copy; 1001 btstack_crypto_random->size -= bytes_to_copy; 1002 // data processed, more? 1003 if (!btstack_crypto_random->size) { 1004 // done 1005 btstack_linked_list_pop(&btstack_crypto_operations); 1006 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context); 1007 } 1008 break; 1009 #ifdef ENABLE_ECC_P256 1010 case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY: 1011 btstack_assert((btstack_crypto_ecc_p256_random_len + 8) <= 64); 1012 (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len], data, 8); 1013 btstack_crypto_ecc_p256_random_len += 8u; 1014 if (btstack_crypto_ecc_p256_random_len >= 64u) { 1015 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE; 1016 btstack_crypto_ecc_p256_generate_key_software(); 1017 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE; 1018 } 1019 break; 1020 #endif 1021 default: 1022 break; 1023 } 1024 // more work? 1025 btstack_crypto_run(); 1026 } 1027 1028 #ifndef USE_BTSTACK_AES128 1029 static void btstack_crypto_handle_encryption_result(const uint8_t * data){ 1030 btstack_crypto_aes128_t * btstack_crypto_aes128; 1031 btstack_crypto_aes128_cmac_t * btstack_crypto_cmac; 1032 btstack_crypto_ccm_t * btstack_crypto_ccm; 1033 uint8_t result[16]; 1034 1035 btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 1036 if (!btstack_crypto) return; 1037 switch (btstack_crypto->operation){ 1038 case BTSTACK_CRYPTO_AES128: 1039 btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 1040 reverse_128(data, btstack_crypto_aes128->ciphertext); 1041 btstack_crypto_done(btstack_crypto); 1042 break; 1043 case BTSTACK_CRYPTO_CMAC_GENERATOR: 1044 case BTSTACK_CRYPTO_CMAC_MESSAGE: 1045 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 1046 reverse_128(data, result); 1047 btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result); 1048 break; 1049 case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK: 1050 case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK: 1051 case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK: 1052 btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 1053 switch (btstack_crypto_ccm->state){ 1054 case CCM_W4_X1: 1055 reverse_128(data, btstack_crypto_ccm->x_i); 1056 btstack_crypto_ccm_handle_x1(btstack_crypto_ccm); 1057 break; 1058 case CCM_W4_XN: 1059 reverse_128(data, btstack_crypto_ccm->x_i); 1060 btstack_crypto_ccm_handle_xn(btstack_crypto_ccm); 1061 break; 1062 case CCM_W4_AAD_XN: 1063 reverse_128(data, btstack_crypto_ccm->x_i); 1064 btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm); 1065 break; 1066 case CCM_W4_S0: 1067 btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data); 1068 break; 1069 case CCM_W4_SN: 1070 btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data); 1071 break; 1072 default: 1073 break; 1074 } 1075 break; 1076 default: 1077 break; 1078 } 1079 } 1080 #endif 1081 1082 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){ 1083 UNUSED(cid); // ok: there is no channel 1084 UNUSED(size); // ok: fixed format events read from HCI buffer 1085 1086 #ifdef ENABLE_ECC_P256 1087 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 1088 btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192; 1089 #endif 1090 #endif 1091 bool ecdh_operations_supported; 1092 1093 if (packet_type != HCI_EVENT_PACKET) return; 1094 1095 switch (hci_event_packet_get_type(packet)){ 1096 case BTSTACK_EVENT_STATE: 1097 switch(btstack_event_state_get_state(packet)){ 1098 case HCI_STATE_HALTING: 1099 // as stack is shutting down, reset state 1100 btstack_crypto_state_reset(); 1101 break; 1102 default: 1103 break; 1104 } 1105 if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break; 1106 break; 1107 1108 case HCI_EVENT_COMMAND_COMPLETE: 1109 switch (hci_event_command_complete_get_command_opcode(packet)){ 1110 #ifndef USE_BTSTACK_AES128 1111 case HCI_OPCODE_HCI_LE_ENCRYPT: 1112 if (!btstack_crypto_wait_for_hci_result) return; 1113 btstack_crypto_wait_for_hci_result = 0; 1114 btstack_crypto_handle_encryption_result(&packet[6]); 1115 break; 1116 #endif 1117 case HCI_OPCODE_HCI_LE_RAND: 1118 if (!btstack_crypto_wait_for_hci_result) return; 1119 btstack_crypto_wait_for_hci_result = false; 1120 btstack_crypto_handle_random_data(&packet[6], 8); 1121 break; 1122 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS: 1123 ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1u+34u] & 0x06u) == 0x06u; 1124 UNUSED(ecdh_operations_supported); 1125 log_info("controller supports ECDH operation: %u", ecdh_operations_supported); 1126 #ifdef ENABLE_ECC_P256 1127 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 1128 // Assert controller supports ECDH operation if we don't implement them ourselves 1129 // Please add ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS to btstack_config.h and add 3rd-party/micro-ecc to your port 1130 btstack_assert(ecdh_operations_supported != 0); 1131 #endif 1132 #endif 1133 break; 1134 default: 1135 break; 1136 } 1137 break; 1138 1139 #ifdef ENABLE_ECC_P256 1140 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 1141 case HCI_EVENT_LE_META: 1142 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations); 1143 if (!btstack_crypto_ec_p192) break; 1144 switch (hci_event_le_meta_get_subevent_code(packet)){ 1145 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE: 1146 if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break; 1147 if (!btstack_crypto_wait_for_hci_result) return; 1148 btstack_crypto_wait_for_hci_result = 0; 1149 if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){ 1150 log_error("Read Local P256 Public Key failed"); 1151 } 1152 hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]); 1153 hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]); 1154 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE; 1155 break; 1156 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE: 1157 if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break; 1158 if (!btstack_crypto_wait_for_hci_result) return; 1159 btstack_crypto_wait_for_hci_result = 0; 1160 if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){ 1161 log_error("Generate DHKEY failed -> abort"); 1162 } 1163 hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey); 1164 // done 1165 btstack_linked_list_pop(&btstack_crypto_operations); 1166 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context); 1167 break; 1168 default: 1169 break; 1170 } 1171 break; 1172 #endif 1173 #endif 1174 default: 1175 break; 1176 } 1177 1178 // try processing 1179 btstack_crypto_run(); 1180 } 1181 1182 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){ 1183 request->btstack_crypto.context_callback.callback = callback; 1184 request->btstack_crypto.context_callback.context = callback_arg; 1185 request->btstack_crypto.operation = BTSTACK_CRYPTO_RANDOM; 1186 request->buffer = buffer; 1187 request->size = size; 1188 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1189 btstack_crypto_run(); 1190 } 1191 1192 void btstack_crypto_aes128_encrypt(btstack_crypto_aes128_t * request, const uint8_t * key, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){ 1193 request->btstack_crypto.context_callback.callback = callback; 1194 request->btstack_crypto.context_callback.context = callback_arg; 1195 request->btstack_crypto.operation = BTSTACK_CRYPTO_AES128; 1196 request->key = key; 1197 request->plaintext = plaintext; 1198 request->ciphertext = ciphertext; 1199 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1200 btstack_crypto_run(); 1201 } 1202 1203 void btstack_crypto_aes128_cmac_generator(btstack_crypto_aes128_cmac_t * request, const uint8_t * key, uint16_t size, uint8_t (*get_byte_callback)(uint16_t pos), uint8_t * hash, void (* callback)(void * arg), void * callback_arg){ 1204 request->btstack_crypto.context_callback.callback = callback; 1205 request->btstack_crypto.context_callback.context = callback_arg; 1206 request->btstack_crypto.operation = BTSTACK_CRYPTO_CMAC_GENERATOR; 1207 request->key = key; 1208 request->size = size; 1209 request->data.get_byte_callback = get_byte_callback; 1210 request->hash = hash; 1211 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1212 btstack_crypto_run(); 1213 } 1214 1215 void btstack_crypto_aes128_cmac_message(btstack_crypto_aes128_cmac_t * request, const uint8_t * key, uint16_t size, const uint8_t * message, uint8_t * hash, void (* callback)(void * arg), void * callback_arg){ 1216 request->btstack_crypto.context_callback.callback = callback; 1217 request->btstack_crypto.context_callback.context = callback_arg; 1218 request->btstack_crypto.operation = BTSTACK_CRYPTO_CMAC_MESSAGE; 1219 request->key = key; 1220 request->size = size; 1221 request->data.message = message; 1222 request->hash = hash; 1223 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1224 btstack_crypto_run(); 1225 } 1226 1227 void btstack_crypto_aes128_cmac_zero(btstack_crypto_aes128_cmac_t * request, uint16_t size, const uint8_t * message, uint8_t * hash, void (* callback)(void * arg), void * callback_arg){ 1228 request->btstack_crypto.context_callback.callback = callback; 1229 request->btstack_crypto.context_callback.context = callback_arg; 1230 request->btstack_crypto.operation = BTSTACK_CRYPTO_CMAC_MESSAGE; 1231 request->key = zero; 1232 request->size = size; 1233 request->data.message = message; 1234 request->hash = hash; 1235 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1236 btstack_crypto_run(); 1237 } 1238 1239 #ifdef ENABLE_ECC_P256 1240 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){ 1241 // reset key generation 1242 if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){ 1243 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE; 1244 } 1245 request->btstack_crypto.context_callback.callback = callback; 1246 request->btstack_crypto.context_callback.context = callback_arg; 1247 request->btstack_crypto.operation = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY; 1248 request->public_key = public_key; 1249 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1250 btstack_crypto_run(); 1251 } 1252 1253 void btstack_crypto_ecc_p256_calculate_dhkey(btstack_crypto_ecc_p256_t * request, const uint8_t * public_key, uint8_t * dhkey, void (* callback)(void * arg), void * callback_arg){ 1254 request->btstack_crypto.context_callback.callback = callback; 1255 request->btstack_crypto.context_callback.context = callback_arg; 1256 request->btstack_crypto.operation = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY; 1257 request->public_key = (uint8_t *) public_key; 1258 request->dhkey = dhkey; 1259 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1260 btstack_crypto_run(); 1261 } 1262 1263 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){ 1264 1265 // validate public key using micro-ecc 1266 int err = 0; 1267 1268 #if defined (USE_MICRO_ECC_P256) 1269 1270 #if uECC_SUPPORTS_secp256r1 1271 // standard version 1272 err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0; 1273 #else 1274 // static version 1275 err = uECC_valid_public_key(public_key) == 0; 1276 #endif 1277 1278 #elif defined(USE_MBEDTLS_ECC_P256) 1279 mbedtls_ecp_point Q; 1280 mbedtls_ecp_point_init( &Q ); 1281 mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32); 1282 mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32); 1283 mbedtls_mpi_lset(&Q.Z, 1); 1284 err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q); 1285 mbedtls_ecp_point_free( & Q); 1286 #else 1287 1288 UNUSED(public_key); 1289 err = 1; 1290 log_error("No elliptic curve library available"); 1291 1292 #endif 1293 1294 if (err != 0){ 1295 log_error("public key invalid %x", err); 1296 } 1297 return err; 1298 } 1299 #endif 1300 1301 void btstack_crypto_ccm_init(btstack_crypto_ccm_t * request, const uint8_t * key, const uint8_t * nonce, uint16_t message_len, uint16_t additional_authenticated_data_len, uint8_t auth_len){ 1302 request->key = key; 1303 request->nonce = nonce; 1304 request->message_len = message_len; 1305 request->aad_len = additional_authenticated_data_len; 1306 request->aad_offset = 0; 1307 request->auth_len = auth_len; 1308 request->counter = 1; 1309 request->state = CCM_CALCULATE_X1; 1310 } 1311 1312 void btstack_crypto_ccm_digest(btstack_crypto_ccm_t * request, uint8_t * additional_authenticated_data, uint16_t additional_authenticated_data_len, void (* callback)(void * arg), void * callback_arg){ 1313 // not implemented yet 1314 request->btstack_crypto.context_callback.callback = callback; 1315 request->btstack_crypto.context_callback.context = callback_arg; 1316 request->btstack_crypto.operation = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK; 1317 request->block_len = additional_authenticated_data_len; 1318 request->input = additional_authenticated_data; 1319 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1320 btstack_crypto_run(); 1321 } 1322 1323 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){ 1324 (void)memcpy(authentication_value, request->x_i, request->auth_len); 1325 } 1326 1327 void btstack_crypto_ccm_encrypt_block(btstack_crypto_ccm_t * request, uint16_t len, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){ 1328 #ifdef DEBUG_CCM 1329 printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", len); 1330 #endif 1331 request->btstack_crypto.context_callback.callback = callback; 1332 request->btstack_crypto.context_callback.context = callback_arg; 1333 request->btstack_crypto.operation = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK; 1334 request->block_len = len; 1335 request->input = plaintext; 1336 request->output = ciphertext; 1337 if (request->state != CCM_CALCULATE_X1){ 1338 request->state = CCM_CALCULATE_XN; 1339 } 1340 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1341 btstack_crypto_run(); 1342 } 1343 1344 void btstack_crypto_ccm_decrypt_block(btstack_crypto_ccm_t * request, uint16_t len, const uint8_t * ciphertext, uint8_t * plaintext, void (* callback)(void * arg), void * callback_arg){ 1345 request->btstack_crypto.context_callback.callback = callback; 1346 request->btstack_crypto.context_callback.context = callback_arg; 1347 request->btstack_crypto.operation = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK; 1348 request->block_len = len; 1349 request->input = ciphertext; 1350 request->output = plaintext; 1351 if (request->state != CCM_CALCULATE_X1){ 1352 request->state = CCM_CALCULATE_SN; 1353 } 1354 btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request); 1355 btstack_crypto_run(); 1356 } 1357 1358 1359 static void btstack_crypto_state_reset(void) { 1360 #ifndef USE_BTSTACK_AES128 1361 btstack_crypto_cmac_state = CMAC_IDLE; 1362 #endif 1363 #ifdef ENABLE_ECC_P256 1364 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE; 1365 #endif 1366 btstack_crypto_wait_for_hci_result = false; 1367 btstack_crypto_operations = NULL; 1368 } 1369 1370 void btstack_crypto_init(void){ 1371 if (btstack_crypto_initialized) return; 1372 btstack_crypto_initialized = true; 1373 1374 // register with HCI 1375 hci_event_callback_registration.callback = &btstack_crypto_event_handler; 1376 hci_add_event_handler(&hci_event_callback_registration); 1377 1378 #ifdef USE_MBEDTLS_ECC_P256 1379 mbedtls_ecp_group_init(&mbedtls_ec_group); 1380 mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1); 1381 #endif 1382 1383 // reset state 1384 btstack_crypto_state_reset(); 1385 } 1386 1387 // De-Init 1388 void btstack_crypto_deinit(void) { 1389 btstack_crypto_initialized = false; 1390 } 1391 1392 // PTS only 1393 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){ 1394 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION 1395 (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32); 1396 (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64); 1397 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE; 1398 #else 1399 UNUSED(public_key); 1400 UNUSED(private_key); 1401 #endif 1402 } 1403 1404 // Unit testing 1405 int btstack_crypto_idle(void){ 1406 return btstack_linked_list_empty(&btstack_crypto_operations); 1407 } 1408 void btstack_crypto_reset(void){ 1409 btstack_crypto_deinit(); 1410 btstack_crypto_init(); 1411 } 1412