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