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