xref: /btstack/src/btstack_crypto.c (revision 1b464e99afd70ddaf6b75be1ba7cc563a5f5dfd8)
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 MATTHIAS RINGWALD 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 MATTHIAS
21  * RINGWALD 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 "hci.h"
48 
49 //
50 // AES128 Configuration
51 //
52 
53 // By default, AES128 is computed by Bluetooth Controller using HCI Command/Event asynchronously
54 // as fallback/alternative, a software implementation can be used
55 // configure ECC implementations
56 #if defined(HAVE_AES128) && defined(ENABLE_SOFTWARE_AES128)
57 #error "If you have custom AES128 implementation (HAVE_AES128), please disable software AES128 (ENABLE_SOFTWARE_AES128) in bstack_config.h"
58 #endif
59 
60 #ifdef ENABLE_SOFTWARE_AES128
61 #define HAVE_AES128
62 #include "rijndael.h"
63 #endif
64 
65 #ifdef HAVE_AES128
66 #define USE_BTSTACK_AES128
67 #endif
68 
69 //
70 // ECC Configuration
71 //
72 
73 // backwards-compatitility ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS -> ENABLE_MICRO_ECC_P256
74 #if defined(ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS) && !defined(ENABLE_MICRO_ECC_P256)
75 #define ENABLE_MICRO_ECC_P256
76 #endif
77 
78 // configure ECC implementations
79 #if defined(ENABLE_MICRO_ECC_P256) && defined(HAVE_MBEDTLS_ECC_P256)
80 #error "If you have mbedTLS (HAVE_MBEDTLS_ECC_P256), please disable uECC (ENABLE_MICRO_ECC_P256) in bstack_config.h"
81 #endif
82 
83 // Software ECC-P256 implementation provided by micro-ecc
84 #ifdef ENABLE_MICRO_ECC_P256
85 #define ENABLE_ECC_P256
86 #define USE_MICRO_ECC_P256
87 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
88 #include "uECC.h"
89 #endif
90 
91 // Software ECC-P256 implementation provided by mbedTLS
92 #ifdef HAVE_MBEDTLS_ECC_P256
93 #define ENABLE_ECC_P256
94 #define USE_MBEDTLS_ECC_P256
95 #define USE_SOFTWARE_ECC_P256_IMPLEMENTATION
96 #include "mbedtls/config.h"
97 #include "mbedtls/platform.h"
98 #include "mbedtls/ecp.h"
99 #endif
100 
101 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && !defined(ENABLE_ECC_P256)
102 #define ENABLE_ECC_P256
103 #endif
104 
105 // degbugging
106 // #define DEBUG_CCM
107 
108 typedef enum {
109     CMAC_IDLE,
110     CMAC_CALC_SUBKEYS,
111     CMAC_W4_SUBKEYS,
112     CMAC_CALC_MI,
113     CMAC_W4_MI,
114     CMAC_CALC_MLAST,
115     CMAC_W4_MLAST
116 } btstack_crypto_cmac_state_t;
117 
118 typedef enum {
119     ECC_P256_KEY_GENERATION_IDLE,
120     ECC_P256_KEY_GENERATION_GENERATING_RANDOM,
121     ECC_P256_KEY_GENERATION_ACTIVE,
122     ECC_P256_KEY_GENERATION_W4_KEY,
123     ECC_P256_KEY_GENERATION_DONE,
124 } btstack_crypto_ecc_p256_key_generation_state_t;
125 
126 static void btstack_crypto_run(void);
127 
128 static const uint8_t zero[16] = { 0 };
129 
130 static uint8_t btstack_crypto_initialized;
131 static btstack_linked_list_t btstack_crypto_operations;
132 static btstack_packet_callback_registration_t hci_event_callback_registration;
133 static uint8_t btstack_crypto_wait_for_hci_result;
134 
135 // state for AES-CMAC
136 #ifndef USE_BTSTACK_AES128
137 static btstack_crypto_cmac_state_t btstack_crypto_cmac_state;
138 static sm_key_t btstack_crypto_cmac_k;
139 static sm_key_t btstack_crypto_cmac_x;
140 static sm_key_t btstack_crypto_cmac_subkey;
141 static uint8_t  btstack_crypto_cmac_block_current;
142 static uint8_t  btstack_crypto_cmac_block_count;
143 #endif
144 
145 // state for AES-CCM
146 #ifndef USE_BTSTACK_AES128
147 static uint8_t btstack_crypto_ccm_s[16];
148 #endif
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 == 0) return 0;
291     return (len & 0x0f) == 0;
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*16) + 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[0] & 0x80){
317                 k1[15] ^= 0x87;
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[0] & 0x80){
323                 k2[15] ^= 0x87;
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 - 16 + i) ^ k1[i];
336                 }
337             } else {
338                 int valid_octets_in_last_block = btstack_crypto_cmac->size & 0x0f;
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 & 0xfff0) + i) ^ k2[i];
342                         continue;
343                     }
344                     if (i == valid_octets_in_last_block){
345                         btstack_crypto_cmac_m_last[i] = 0x80 ^ 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 - 1)) ? 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 - 1)) ? 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 + 15) / 16;
400 
401     // step 3: ..
402     if (btstack_crypto_cmac_block_count==0){
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 #ifndef USE_BTSTACK_AES128
416 
417 /*
418   To encrypt the message data we use Counter (CTR) mode.  We first
419   define the key stream blocks by:
420 
421       S_i := E( K, A_i )   for i=0, 1, 2, ...
422 
423   The values A_i are formatted as follows, where the Counter field i is
424   encoded in most-significant-byte first order:
425 
426   Octet Number   Contents
427   ------------   ---------
428   0              Flags
429   1 ... 15-L     Nonce N
430   16-L ... 15    Counter i
431 
432   Bit Number   Contents
433   ----------   ----------------------
434   7            Reserved (always zero)
435   6            Reserved (always zero)
436   5 ... 3      Zero
437   2 ... 0      L'
438 */
439 
440 static void btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm_t * btstack_crypto_ccm, uint16_t counter){
441     btstack_crypto_ccm_s[0] = 1;  // L' = L - 1
442     (void)memcpy(&btstack_crypto_ccm_s[1], btstack_crypto_ccm->nonce, 13);
443     big_endian_store_16(btstack_crypto_ccm_s, 14, counter);
444 #ifdef DEBUG_CCM
445     printf("ststack_crypto_ccm_setup_a_%u\n", counter);
446     printf("%16s: ", "ai");
447     printf_hexdump(btstack_crypto_ccm_s, 16);
448 #endif
449 }
450 
451 /*
452  The first step is to compute the authentication field T.  This is
453    done using CBC-MAC [MAC].  We first define a sequence of blocks B_0,
454    B_1, ..., B_n and then apply CBC-MAC to these blocks.
455 
456    The first block B_0 is formatted as follows, where l(m) is encoded in
457    most-significant-byte first order:
458 
459       Octet Number   Contents
460       ------------   ---------
461       0              Flags
462       1 ... 15-L     Nonce N
463       16-L ... 15    l(m)
464 
465    Within the first block B_0, the Flags field is formatted as follows:
466 
467       Bit Number   Contents
468       ----------   ----------------------
469       7            Reserved (always zero)
470       6            Adata
471       5 ... 3      M'
472       2 ... 0      L'
473  */
474 
475 static void btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm_t * btstack_crypto_ccm, uint8_t * b0){
476     uint8_t m_prime = (btstack_crypto_ccm->auth_len - 2) / 2;
477     uint8_t Adata   = btstack_crypto_ccm->aad_len ? 1 : 0;
478     b0[0] = (Adata << 6) | (m_prime << 3) | 1 ;  // Adata, M', L' = L - 1
479     (void)memcpy(&b0[1], btstack_crypto_ccm->nonce, 13);
480     big_endian_store_16(b0, 14, btstack_crypto_ccm->message_len);
481 #ifdef DEBUG_CCM
482     printf("%16s: ", "B0");
483     printf_hexdump(b0, 16);
484 #endif
485 }
486 #endif
487 
488 #ifdef ENABLE_ECC_P256
489 
490 static void btstack_crypto_log_ec_publickey(const uint8_t * ec_q){
491     log_info("Elliptic curve: X");
492     log_info_hexdump(&ec_q[0],32);
493     log_info("Elliptic curve: Y");
494     log_info_hexdump(&ec_q[32],32);
495 }
496 
497 #if (defined(USE_MICRO_ECC_P256) && !defined(WICED_VERSION)) || defined(USE_MBEDTLS_ECC_P256)
498 // @return OK
499 static int sm_generate_f_rng(unsigned char * buffer, unsigned size){
500     if (btstack_crypto_ecc_p256_key_generation_state != ECC_P256_KEY_GENERATION_ACTIVE) return 0;
501     log_info("sm_generate_f_rng: size %u - offset %u", (int) size, btstack_crypto_ecc_p256_random_offset);
502     while (size) {
503         *buffer++ = btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_offset++];
504         size--;
505     }
506     return 1;
507 }
508 #endif
509 #ifdef USE_MBEDTLS_ECC_P256
510 // @return error - just wrap sm_generate_f_rng
511 static int sm_generate_f_rng_mbedtls(void * context, unsigned char * buffer, size_t size){
512     UNUSED(context);
513     return sm_generate_f_rng(buffer, size) == 0;
514 }
515 #endif /* USE_MBEDTLS_ECC_P256 */
516 
517 static void btstack_crypto_ecc_p256_generate_key_software(void){
518 
519     btstack_crypto_ecc_p256_random_offset = 0;
520 
521     // generate EC key
522 #ifdef USE_MICRO_ECC_P256
523 
524 #ifndef WICED_VERSION
525     log_info("set uECC RNG for initial key generation with 64 random bytes");
526     // micro-ecc from WICED SDK uses its wiced_crypto_get_random by default - no need to set it
527     uECC_set_rng(&sm_generate_f_rng);
528 #endif /* WICED_VERSION */
529 
530 #if uECC_SUPPORTS_secp256r1
531     // standard version
532     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d, uECC_secp256r1());
533 
534     // disable RNG again, as returning no randmon data lets shared key generation fail
535     log_info("disable uECC RNG in standard version after key generation");
536     uECC_set_rng(NULL);
537 #else
538     // static version
539     uECC_make_key(btstack_crypto_ecc_p256_public_key, btstack_crypto_ecc_p256_d);
540 #endif
541 #endif /* USE_MICRO_ECC_P256 */
542 
543 #ifdef USE_MBEDTLS_ECC_P256
544     mbedtls_mpi d;
545     mbedtls_ecp_point P;
546     mbedtls_mpi_init(&d);
547     mbedtls_ecp_point_init(&P);
548     int res = mbedtls_ecp_gen_keypair(&mbedtls_ec_group, &d, &P, &sm_generate_f_rng_mbedtls, NULL);
549     log_info("gen keypair %x", res);
550     mbedtls_mpi_write_binary(&P.X, &btstack_crypto_ecc_p256_public_key[0],  32);
551     mbedtls_mpi_write_binary(&P.Y, &btstack_crypto_ecc_p256_public_key[32], 32);
552     mbedtls_mpi_write_binary(&d, btstack_crypto_ecc_p256_d, 32);
553     mbedtls_ecp_point_free(&P);
554     mbedtls_mpi_free(&d);
555 #endif  /* USE_MBEDTLS_ECC_P256 */
556 }
557 
558 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
559 static void btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192){
560     memset(btstack_crypto_ec_p192->dhkey, 0, 32);
561 
562 #ifdef USE_MICRO_ECC_P256
563 #if uECC_SUPPORTS_secp256r1
564     // standard version
565     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey, uECC_secp256r1());
566 #else
567     // static version
568     uECC_shared_secret(btstack_crypto_ec_p192->public_key, btstack_crypto_ecc_p256_d, btstack_crypto_ec_p192->dhkey);
569 #endif
570 #endif
571 
572 #ifdef USE_MBEDTLS_ECC_P256
573     // da * Pb
574     mbedtls_mpi d;
575     mbedtls_ecp_point Q;
576     mbedtls_ecp_point DH;
577     mbedtls_mpi_init(&d);
578     mbedtls_ecp_point_init(&Q);
579     mbedtls_ecp_point_init(&DH);
580     mbedtls_mpi_read_binary(&d, btstack_crypto_ecc_p256_d, 32);
581     mbedtls_mpi_read_binary(&Q.X, &btstack_crypto_ec_p192->public_key[0] , 32);
582     mbedtls_mpi_read_binary(&Q.Y, &btstack_crypto_ec_p192->public_key[32], 32);
583     mbedtls_mpi_lset(&Q.Z, 1);
584     mbedtls_ecp_mul(&mbedtls_ec_group, &DH, &d, &Q, NULL, NULL);
585     mbedtls_mpi_write_binary(&DH.X, btstack_crypto_ec_p192->dhkey, 32);
586     mbedtls_ecp_point_free(&DH);
587     mbedtls_mpi_free(&d);
588     mbedtls_ecp_point_free(&Q);
589 #endif
590 
591     log_info("dhkey");
592     log_info_hexdump(btstack_crypto_ec_p192->dhkey, 32);
593 }
594 #endif
595 
596 #endif
597 
598 #ifdef USE_BTSTACK_AES128
599 // CCM not implemented using software AES128 yet
600 #else
601 
602 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
603 #ifdef DEBUG_CCM
604     printf("btstack_crypto_ccm_calc_s0\n");
605 #endif
606     btstack_crypto_ccm->state = CCM_W4_S0;
607     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
608     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
609 }
610 
611 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
612 #ifdef DEBUG_CCM
613     printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter);
614 #endif
615     btstack_crypto_ccm->state = CCM_W4_SN;
616     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
617     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
618 }
619 
620 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
621     uint8_t btstack_crypto_ccm_buffer[16];
622     btstack_crypto_ccm->state = CCM_W4_X1;
623     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
624     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
625 }
626 
627 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
628     uint8_t btstack_crypto_ccm_buffer[16];
629     btstack_crypto_ccm->state = CCM_W4_XN;
630 
631 #ifdef DEBUG_CCM
632     printf("%16s: ", "bn");
633     printf_hexdump(plaintext, 16);
634 #endif
635     uint8_t i;
636     uint8_t bytes_to_decrypt = btstack_crypto_ccm->block_len;
637     // use explicit min implementation as c-stat worried about out-of-bounds-reads
638     if (bytes_to_decrypt > 16) {
639         bytes_to_decrypt = 16;
640     }
641     for (i = 0; i < bytes_to_decrypt ; i++){
642         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
643     }
644     (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i],
645                  16 - bytes_to_decrypt);
646 #ifdef DEBUG_CCM
647     printf("%16s: ", "Xn XOR bn");
648     printf_hexdump(btstack_crypto_ccm_buffer, 16);
649 #endif
650 
651     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
652 }
653 
654 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){
655     // store length
656     if (btstack_crypto_ccm->aad_offset == 0){
657         uint8_t len_buffer[2];
658         big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len);
659         btstack_crypto_ccm->x_i[0] ^= len_buffer[0];
660         btstack_crypto_ccm->x_i[1] ^= len_buffer[1];
661         btstack_crypto_ccm->aad_remainder_len += 2;
662         btstack_crypto_ccm->aad_offset        += 2;
663     }
664 
665     // fill from input
666     uint16_t bytes_free = 16 - btstack_crypto_ccm->aad_remainder_len;
667     uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len);
668     while (bytes_to_copy){
669         btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++;
670         btstack_crypto_ccm->aad_offset++;
671         btstack_crypto_ccm->block_len--;
672         bytes_to_copy--;
673         bytes_free--;
674     }
675 
676     // if last block, fill with zeros
677     if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2)){
678         btstack_crypto_ccm->aad_remainder_len = 16;
679     }
680     // if not full, notify done
681     if (btstack_crypto_ccm->aad_remainder_len < 16){
682         btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
683         return;
684     }
685 
686     // encrypt block
687 #ifdef DEBUG_CCM
688     printf("%16s: ", "Xn XOR Bn (aad)");
689     printf_hexdump(btstack_crypto_ccm->x_i, 16);
690 #endif
691 
692     btstack_crypto_ccm->aad_remainder_len = 0;
693     btstack_crypto_ccm->state = CCM_W4_AAD_XN;
694     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i);
695 }
696 
697 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
698     // data is little-endian, flip on the fly
699     int i;
700     for (i=0;i<16;i++){
701         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
702     }
703     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
704 }
705 
706 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
707     // data is little-endian, flip on the fly
708     int i;
709     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
710     for (i=0;i<bytes_to_process;i++){
711         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
712     }
713 }
714 
715 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
716     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
717     // next block
718     btstack_crypto_ccm->counter++;
719     btstack_crypto_ccm->input       += bytes_to_process;
720     btstack_crypto_ccm->output      += bytes_to_process;
721     btstack_crypto_ccm->block_len   -= bytes_to_process;
722     btstack_crypto_ccm->message_len -= bytes_to_process;
723 #ifdef DEBUG_CCM
724     printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len);
725 #endif
726     if (btstack_crypto_ccm->message_len == 0){
727         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
728     } else {
729         btstack_crypto_ccm->state = state_when_done;
730         if (btstack_crypto_ccm->block_len == 0){
731             btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
732         }
733     }
734 }
735 #endif
736 
737 static void btstack_crypto_run(void){
738 
739     btstack_crypto_aes128_t        * btstack_crypto_aes128;
740     btstack_crypto_ccm_t           * btstack_crypto_ccm;
741     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
742 #ifdef ENABLE_ECC_P256
743     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
744 #endif
745 
746     // stack up and running?
747     if (hci_get_state() != HCI_STATE_WORKING) return;
748 
749     // try to do as much as possible
750     while (true){
751 
752         // anything to do?
753         if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
754 
755         // already active?
756         if (btstack_crypto_wait_for_hci_result) return;
757 
758         // can send a command?
759         if (!hci_can_send_command_packet_now()) return;
760 
761         // ok, find next task
762     	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
763     	switch (btstack_crypto->operation){
764     		case BTSTACK_CRYPTO_RANDOM:
765     			btstack_crypto_wait_for_hci_result = 1;
766     		    hci_send_cmd(&hci_le_rand);
767     		    break;
768     		case BTSTACK_CRYPTO_AES128:
769                 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
770 #ifdef USE_BTSTACK_AES128
771                 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
772                 btstack_crypto_done(btstack_crypto);
773 #else
774                 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
775 #endif
776     		    break;
777 
778     		case BTSTACK_CRYPTO_CMAC_MESSAGE:
779     		case BTSTACK_CRYPTO_CMAC_GENERATOR:
780                 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
781 #ifdef USE_BTSTACK_AES128
782                 btstack_crypto_cmac_calc( btstack_crypto_cmac );
783                 btstack_crypto_done(btstack_crypto);
784 #else
785     			btstack_crypto_wait_for_hci_result = 1;
786     			if (btstack_crypto_cmac_state == CMAC_IDLE){
787     				btstack_crypto_cmac_start(btstack_crypto_cmac);
788     			} else {
789     				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
790     			}
791 #endif
792     			break;
793 
794             case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
795             case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
796             case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
797 #ifdef USE_BTSTACK_AES128
798                 UNUSED(btstack_crypto_ccm);
799                 // NOTE: infinite output of this message
800                 log_error("ccm not implemented for software aes128 yet");
801 #else
802                 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
803                 switch (btstack_crypto_ccm->state){
804                     case CCM_CALCULATE_AAD_XN:
805                         btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm);
806                         break;
807                     case CCM_CALCULATE_X1:
808                         btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
809                         break;
810                     case CCM_CALCULATE_S0:
811                         btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
812                         break;
813                     case CCM_CALCULATE_SN:
814                         btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
815                         break;
816                     case CCM_CALCULATE_XN:
817                         btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
818                         break;
819                     default:
820                         break;
821                 }
822 #endif
823                 break;
824 
825 #ifdef ENABLE_ECC_P256
826             case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
827                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
828                 switch (btstack_crypto_ecc_p256_key_generation_state){
829                     case ECC_P256_KEY_GENERATION_DONE:
830                         // done
831                         btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
832                         (void)memcpy(btstack_crypto_ec_p192->public_key,
833                                      btstack_crypto_ecc_p256_public_key, 64);
834                         btstack_linked_list_pop(&btstack_crypto_operations);
835                         (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
836                         break;
837                     case ECC_P256_KEY_GENERATION_IDLE:
838 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
839                         log_info("start ecc random");
840                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
841                         btstack_crypto_ecc_p256_random_offset = 0;
842                         btstack_crypto_wait_for_hci_result = 1;
843                         hci_send_cmd(&hci_le_rand);
844 #else
845                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
846                         btstack_crypto_wait_for_hci_result = 1;
847                         hci_send_cmd(&hci_le_read_local_p256_public_key);
848 #endif
849                         break;
850 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
851                     case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
852                         log_info("more ecc random");
853                         btstack_crypto_wait_for_hci_result = 1;
854                         hci_send_cmd(&hci_le_rand);
855                         break;
856 #endif
857                     default:
858                         break;
859                 }
860                 break;
861             case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
862                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
863 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
864                 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
865                 // done
866                 btstack_linked_list_pop(&btstack_crypto_operations);
867                 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
868 #else
869                 btstack_crypto_wait_for_hci_result = 1;
870                 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
871 #endif
872                 break;
873 
874 #endif /* ENABLE_ECC_P256 */
875 
876             default:
877                 break;
878         }
879     }
880 }
881 
882 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
883     btstack_crypto_random_t * btstack_crypto_random;
884     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
885     uint16_t bytes_to_copy;
886 	if (!btstack_crypto) return;
887     switch (btstack_crypto->operation){
888         case BTSTACK_CRYPTO_RANDOM:
889             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
890             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
891             (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
892             btstack_crypto_random->buffer += bytes_to_copy;
893             btstack_crypto_random->size   -= bytes_to_copy;
894             // data processed, more?
895             if (!btstack_crypto_random->size) {
896                 // done
897                 btstack_linked_list_pop(&btstack_crypto_operations);
898                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
899             }
900             break;
901 #ifdef ENABLE_ECC_P256
902         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
903             (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len],
904 			 data, 8);
905             btstack_crypto_ecc_p256_random_len += 8;
906             if (btstack_crypto_ecc_p256_random_len >= 64) {
907                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
908                 btstack_crypto_ecc_p256_generate_key_software();
909                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
910             }
911             break;
912 #endif
913         default:
914             break;
915     }
916 	// more work?
917 	btstack_crypto_run();
918 }
919 
920 #ifndef USE_BTSTACK_AES128
921 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
922 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
923 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
924     btstack_crypto_ccm_t         * btstack_crypto_ccm;
925 	uint8_t result[16];
926 
927     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
928 	if (!btstack_crypto) return;
929 	switch (btstack_crypto->operation){
930 		case BTSTACK_CRYPTO_AES128:
931 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
932 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
933             btstack_crypto_done(btstack_crypto);
934 			break;
935 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
936 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
937 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
938 		    reverse_128(data, result);
939 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
940 			break;
941         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
942             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
943             switch (btstack_crypto_ccm->state){
944                 case CCM_W4_X1:
945                     reverse_128(data, btstack_crypto_ccm->x_i);
946 #ifdef DEBUG_CCM
947     printf("%16s: ", "X1");
948     printf_hexdump(btstack_crypto_ccm->x_i, 16);
949 #endif
950                     btstack_crypto_ccm->aad_remainder_len = 0;
951                     btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
952                     break;
953                 case CCM_W4_AAD_XN:
954                     reverse_128(data, btstack_crypto_ccm->x_i);
955 #ifdef DEBUG_CCM
956     printf("%16s: ", "Xn+1 AAD");
957     printf_hexdump(btstack_crypto_ccm->x_i, 16);
958 #endif
959                     // more aad?
960                     if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2)){
961                         btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
962                     } else {
963                         // done
964                         btstack_crypto_done(btstack_crypto);
965                     }
966                     break;
967                 default:
968                     break;
969             }
970             break;
971         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
972             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
973             switch (btstack_crypto_ccm->state){
974                 case CCM_W4_X1:
975                     reverse_128(data, btstack_crypto_ccm->x_i);
976 #ifdef DEBUG_CCM
977     printf("%16s: ", "X1");
978     printf_hexdump(btstack_crypto_ccm->x_i, 16);
979 #endif
980                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
981                     break;
982                 case CCM_W4_XN:
983                     reverse_128(data, btstack_crypto_ccm->x_i);
984 #ifdef DEBUG_CCM
985     printf("%16s: ", "Xn+1");
986     printf_hexdump(btstack_crypto_ccm->x_i, 16);
987 #endif
988                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
989                     break;
990                 case CCM_W4_S0:
991 #ifdef DEBUG_CCM
992     reverse_128(data, result);
993     printf("%16s: ", "X0");
994     printf_hexdump(btstack_crypto_ccm->x_i, 16);
995 #endif
996                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
997                     break;
998                 case CCM_W4_SN:
999 #ifdef DEBUG_CCM
1000     reverse_128(data, result);
1001     printf("%16s: ", "Sn");
1002     printf_hexdump(btstack_crypto_ccm->x_i, 16);
1003 #endif
1004                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
1005                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
1006                     break;
1007                 default:
1008                     break;
1009             }
1010             break;
1011         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
1012             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1013             switch (btstack_crypto_ccm->state){
1014                 case CCM_W4_X1:
1015                     reverse_128(data, btstack_crypto_ccm->x_i);
1016 #ifdef DEBUG_CCM
1017     printf("%16s: ", "X1");
1018     printf_hexdump(btstack_crypto_ccm->x_i, 16);
1019 #endif
1020                     btstack_crypto_ccm->state = CCM_CALCULATE_SN;
1021                     break;
1022                 case CCM_W4_XN:
1023                     reverse_128(data, btstack_crypto_ccm->x_i);
1024 #ifdef DEBUG_CCM
1025     printf("%16s: ", "Xn+1");
1026     printf_hexdump(btstack_crypto_ccm->x_i, 16);
1027 #endif
1028                     btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
1029                     break;
1030                 case CCM_W4_S0:
1031                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
1032                     break;
1033                 case CCM_W4_SN:
1034                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
1035                     btstack_crypto_ccm->state = CCM_CALCULATE_XN;
1036                     break;
1037                 default:
1038                     break;
1039             }
1040             break;
1041 		default:
1042 			break;
1043 	}
1044 }
1045 #endif
1046 
1047 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1048     UNUSED(cid);         // ok: there is no channel
1049     UNUSED(size);        // ok: fixed format events read from HCI buffer
1050 
1051 #ifdef ENABLE_ECC_P256
1052 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1053     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
1054 #endif
1055 #endif
1056 
1057     if (packet_type != HCI_EVENT_PACKET)  return;
1058 
1059     switch (hci_event_packet_get_type(packet)){
1060         case BTSTACK_EVENT_STATE:
1061             log_info("BTSTACK_EVENT_STATE");
1062             if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break;
1063             if (!btstack_crypto_wait_for_hci_result) break;
1064             // request stack to defer shutdown a bit
1065             hci_halting_defer();
1066             break;
1067 
1068         case HCI_EVENT_COMMAND_COMPLETE:
1069 #ifndef USE_BTSTACK_AES128
1070     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
1071                 if (!btstack_crypto_wait_for_hci_result) return;
1072                 btstack_crypto_wait_for_hci_result = 0;
1073     	        btstack_crypto_handle_encryption_result(&packet[6]);
1074     	    }
1075 #endif
1076     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
1077                 if (!btstack_crypto_wait_for_hci_result) return;
1078                 btstack_crypto_wait_for_hci_result = 0;
1079     	        btstack_crypto_handle_random_data(&packet[6], 8);
1080     	    }
1081             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1082                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
1083                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
1084 #ifdef ENABLE_ECC_P256
1085 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1086                 if (!ecdh_operations_supported){
1087                     // mbedTLS can also be used if already available (and malloc is supported)
1088                     log_error("ECC-P256 support enabled, but HCI Controller doesn't support it. Please add ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS to btstack_config.h");
1089                 }
1090 #endif
1091 #endif
1092             }
1093             break;
1094 
1095 #ifdef ENABLE_ECC_P256
1096 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1097         case HCI_EVENT_LE_META:
1098             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1099             if (!btstack_crypto_ec_p192) break;
1100             switch (hci_event_le_meta_get_subevent_code(packet)){
1101                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
1102                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
1103                     if (!btstack_crypto_wait_for_hci_result) return;
1104                     btstack_crypto_wait_for_hci_result = 0;
1105                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
1106                         log_error("Read Local P256 Public Key failed");
1107                     }
1108                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
1109                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
1110                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1111                     break;
1112                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
1113                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
1114                     if (!btstack_crypto_wait_for_hci_result) return;
1115                     btstack_crypto_wait_for_hci_result = 0;
1116                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
1117                         log_error("Generate DHKEY failed -> abort");
1118                     }
1119                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
1120                     // done
1121                     btstack_linked_list_pop(&btstack_crypto_operations);
1122                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
1123                     break;
1124                 default:
1125                     break;
1126             }
1127             break;
1128 #endif
1129 #endif
1130         default:
1131             break;
1132     }
1133 
1134     // try processing
1135 	btstack_crypto_run();
1136 }
1137 
1138 void btstack_crypto_init(void){
1139 	if (btstack_crypto_initialized) return;
1140 	btstack_crypto_initialized = 1;
1141 
1142 	// register with HCI
1143     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
1144     hci_add_event_handler(&hci_event_callback_registration);
1145 
1146 #ifdef USE_MBEDTLS_ECC_P256
1147 	mbedtls_ecp_group_init(&mbedtls_ec_group);
1148 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
1149 #endif
1150 }
1151 
1152 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
1153 	request->btstack_crypto.context_callback.callback  = callback;
1154 	request->btstack_crypto.context_callback.context   = callback_arg;
1155 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
1156 	request->buffer = buffer;
1157 	request->size   = size;
1158 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1159 	btstack_crypto_run();
1160 }
1161 
1162 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){
1163 	request->btstack_crypto.context_callback.callback  = callback;
1164 	request->btstack_crypto.context_callback.context   = callback_arg;
1165 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
1166 	request->key 									   = key;
1167 	request->plaintext      					       = plaintext;
1168 	request->ciphertext 							   = ciphertext;
1169 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1170 	btstack_crypto_run();
1171 }
1172 
1173 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){
1174 	request->btstack_crypto.context_callback.callback  = callback;
1175 	request->btstack_crypto.context_callback.context   = callback_arg;
1176 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
1177 	request->key 									   = key;
1178 	request->size 									   = size;
1179 	request->data.get_byte_callback					   = get_byte_callback;
1180 	request->hash 									   = hash;
1181 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1182 	btstack_crypto_run();
1183 }
1184 
1185 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){
1186 	request->btstack_crypto.context_callback.callback  = callback;
1187 	request->btstack_crypto.context_callback.context   = callback_arg;
1188 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
1189 	request->key 									   = key;
1190 	request->size 									   = size;
1191 	request->data.message      						   = message;
1192 	request->hash 									   = hash;
1193 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1194 	btstack_crypto_run();
1195 }
1196 
1197 void btstack_crypto_aes128_cmac_zero(btstack_crypto_aes128_cmac_t * request, uint16_t len, const uint8_t * message,  uint8_t * hash, void (* callback)(void * arg), void * callback_arg){
1198     request->btstack_crypto.context_callback.callback  = callback;
1199     request->btstack_crypto.context_callback.context   = callback_arg;
1200     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
1201     request->key                                       = zero;
1202     request->size                                      = len;
1203     request->data.message                              = message;
1204     request->hash                                      = hash;
1205     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1206     btstack_crypto_run();
1207 }
1208 
1209 #ifdef ENABLE_ECC_P256
1210 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
1211     // reset key generation
1212     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
1213         btstack_crypto_ecc_p256_random_len = 0;
1214         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1215     }
1216     request->btstack_crypto.context_callback.callback  = callback;
1217     request->btstack_crypto.context_callback.context   = callback_arg;
1218     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
1219     request->public_key                                = public_key;
1220     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1221     btstack_crypto_run();
1222 }
1223 
1224 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){
1225     request->btstack_crypto.context_callback.callback  = callback;
1226     request->btstack_crypto.context_callback.context   = callback_arg;
1227     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
1228     request->public_key                                = (uint8_t *) public_key;
1229     request->dhkey                                     = dhkey;
1230     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1231     btstack_crypto_run();
1232 }
1233 
1234 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
1235 
1236     // validate public key using micro-ecc
1237     int err = 0;
1238 
1239 #ifdef USE_MICRO_ECC_P256
1240 #if uECC_SUPPORTS_secp256r1
1241     // standard version
1242     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
1243 #else
1244     // static version
1245     err = uECC_valid_public_key(public_key) == 0;
1246 #endif
1247 #endif
1248 
1249 #ifdef USE_MBEDTLS_ECC_P256
1250     mbedtls_ecp_point Q;
1251     mbedtls_ecp_point_init( &Q );
1252     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
1253     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
1254     mbedtls_mpi_lset(&Q.Z, 1);
1255     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
1256     mbedtls_ecp_point_free( & Q);
1257 #endif
1258 
1259     if (err){
1260         log_error("public key invalid %x", err);
1261     }
1262     return  err;
1263 }
1264 #endif
1265 
1266 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){
1267     request->key         = key;
1268     request->nonce       = nonce;
1269     request->message_len = message_len;
1270     request->aad_len     = additional_authenticated_data_len;
1271     request->aad_offset  = 0;
1272     request->auth_len    = auth_len;
1273     request->counter     = 1;
1274     request->state       = CCM_CALCULATE_X1;
1275 }
1276 
1277 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){
1278     // not implemented yet
1279     request->btstack_crypto.context_callback.callback  = callback;
1280     request->btstack_crypto.context_callback.context   = callback_arg;
1281     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK;
1282     request->block_len                                 = additional_authenticated_data_len;
1283     request->input                                     = additional_authenticated_data;
1284     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1285     btstack_crypto_run();
1286 }
1287 
1288 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1289     (void)memcpy(authentication_value, request->x_i, request->auth_len);
1290 }
1291 
1292 void btstack_crypto_ccm_encrypt_block(btstack_crypto_ccm_t * request, uint16_t block_len, const uint8_t * plaintext, uint8_t * ciphertext, void (* callback)(void * arg), void * callback_arg){
1293 #ifdef DEBUG_CCM
1294     printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", block_len);
1295 #endif
1296     request->btstack_crypto.context_callback.callback  = callback;
1297     request->btstack_crypto.context_callback.context   = callback_arg;
1298     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1299     request->block_len                                 = block_len;
1300     request->input                                     = plaintext;
1301     request->output                                    = ciphertext;
1302     if (request->state != CCM_CALCULATE_X1){
1303         request->state  = CCM_CALCULATE_XN;
1304     }
1305     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1306     btstack_crypto_run();
1307 }
1308 
1309 void btstack_crypto_ccm_decrypt_block(btstack_crypto_ccm_t * request, uint16_t block_len, const uint8_t * ciphertext, uint8_t * plaintext, void (* callback)(void * arg), void * callback_arg){
1310     request->btstack_crypto.context_callback.callback  = callback;
1311     request->btstack_crypto.context_callback.context   = callback_arg;
1312     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1313     request->block_len                                 = block_len;
1314     request->input                                     = ciphertext;
1315     request->output                                    = plaintext;
1316     if (request->state != CCM_CALCULATE_X1){
1317         request->state  = CCM_CALCULATE_SN;
1318     }
1319     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1320     btstack_crypto_run();
1321 }
1322 
1323 // PTS only
1324 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){
1325 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1326     (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32);
1327     (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64);
1328     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1329 #else
1330     UNUSED(public_key);
1331     UNUSED(private_key);
1332 #endif
1333 }
1334 // Unit testing
1335 int btstack_crypto_idle(void){
1336     return btstack_linked_list_empty(&btstack_crypto_operations);
1337 }
1338 void btstack_crypto_reset(void){
1339     btstack_crypto_operations = NULL;
1340     btstack_crypto_wait_for_hci_result = 0;
1341 }
1342