xref: /btstack/src/btstack_crypto.c (revision 547f262d7391d95ade515b57859c37435258defc)
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 static void btstack_crypto_ccm_next_block(btstack_crypto_ccm_t * btstack_crypto_ccm, btstack_crypto_ccm_state_t state_when_done){
594     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
595     // next block
596     btstack_crypto_ccm->counter++;
597     btstack_crypto_ccm->input       += bytes_to_process;
598     btstack_crypto_ccm->output      += bytes_to_process;
599     btstack_crypto_ccm->block_len   -= bytes_to_process;
600     btstack_crypto_ccm->message_len -= bytes_to_process;
601 #ifdef DEBUG_CCM
602     printf("btstack_crypto_ccm_next_block (message len %u, block_len %u)\n", btstack_crypto_ccm->message_len, btstack_crypto_ccm->block_len);
603 #endif
604     if (btstack_crypto_ccm->message_len == 0){
605         btstack_crypto_ccm->state = CCM_CALCULATE_S0;
606     } else {
607         btstack_crypto_ccm->state = state_when_done;
608         if (btstack_crypto_ccm->block_len == 0){
609             btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
610         }
611     }
612 }
613 
614 // If Controller is used for AES128, data is little endian
615 static void btstack_crypto_ccm_handle_s0(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
616     int i;
617     for (i=0;i<16;i++){
618 #ifdef USE_BTSTACK_AES128
619         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[i];
620 #else
621         btstack_crypto_ccm->x_i[i] = btstack_crypto_ccm->x_i[i] ^ data[15-i];
622 #endif
623     }
624     btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
625 }
626 
627 // If Controller is used for AES128, data is little endian
628 static void btstack_crypto_ccm_handle_sn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * data){
629     int i;
630     uint16_t bytes_to_process = btstack_min(btstack_crypto_ccm->block_len, 16);
631     for (i=0;i<bytes_to_process;i++){
632 #ifdef USE_BTSTACK_AES128
633         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[i];
634 #else
635         btstack_crypto_ccm->output[i] = btstack_crypto_ccm->input[i] ^ data[15-i];
636 #endif
637     }
638     switch (btstack_crypto_ccm->btstack_crypto.operation){
639         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
640             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
641             break;
642         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
643             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
644             break;
645         default:
646             btstack_assert(false);
647             break;
648     }
649 }
650 
651 static void btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
652 #ifdef DEBUG_CCM
653     printf("%16s: ", "Xn+1 AAD");
654     printf_hexdump(btstack_crypto_ccm->x_i, 16);
655 #endif
656     // more aad?
657     if (btstack_crypto_ccm->aad_offset < (btstack_crypto_ccm->aad_len + 2)){
658         btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
659     } else {
660         // done
661         btstack_crypto_done((btstack_crypto_t *) btstack_crypto_ccm);
662     }
663 }
664 
665 static void btstack_crypto_ccm_handle_x1(btstack_crypto_ccm_t * btstack_crypto_ccm) {
666 #ifdef DEBUG_CCM
667     printf("%16s: ", "Xi");
668     printf_hexdump(btstack_crypto_ccm->x_i, 16);
669 #endif
670     switch (btstack_crypto_ccm->btstack_crypto.operation){
671         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
672             btstack_crypto_ccm->aad_remainder_len = 0;
673             btstack_crypto_ccm->state = CCM_CALCULATE_AAD_XN;
674             break;
675         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
676             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
677             break;
678         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
679             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
680             break;
681         default:
682         btstack_assert(false);
683             break;
684     }
685 }
686 
687 
688 static void btstack_crypto_ccm_calc_s0(btstack_crypto_ccm_t * btstack_crypto_ccm){
689 #ifdef DEBUG_CCM
690     printf("btstack_crypto_ccm_calc_s0\n");
691 #endif
692     btstack_crypto_ccm->state = CCM_W4_S0;
693     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, 0);
694 #ifdef USE_BTSTACK_AES128
695     uint8_t data[16];
696     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
697 #ifdef DEBUG_CCM
698     printf("%16s: ", "S0");
699     printf_hexdump(data, 16);
700 #endif
701     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
702 #else
703     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
704 #endif
705 }
706 
707 static void btstack_crypto_ccm_calc_sn(btstack_crypto_ccm_t * btstack_crypto_ccm){
708 #ifdef DEBUG_CCM
709     printf("btstack_crypto_ccm_calc_s%u\n", btstack_crypto_ccm->counter);
710 #endif
711     btstack_crypto_ccm->state = CCM_W4_SN;
712     btstack_crypto_ccm_setup_a_i(btstack_crypto_ccm, btstack_crypto_ccm->counter);
713 #ifdef USE_BTSTACK_AES128
714     uint8_t data[16];
715     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_s, data);
716 #ifdef DEBUG_CCM
717     printf("%16s: ", "Sn");
718     printf_hexdump(data, 16);
719 #endif
720     switch (btstack_crypto_ccm->btstack_crypto.operation){
721         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
722             btstack_crypto_ccm->state = CCM_CALCULATE_XN;
723             break;
724         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
725             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_XN);
726             break;
727         default:
728             btstack_assert(false);
729             break;
730     }
731 #else
732     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_s);
733 #endif
734 }
735 
736 static void btstack_crypto_ccm_calc_x1(btstack_crypto_ccm_t * btstack_crypto_ccm){
737     uint8_t btstack_crypto_ccm_buffer[16];
738     btstack_crypto_ccm->state = CCM_W4_X1;
739     btstack_crypto_ccm_setup_b_0(btstack_crypto_ccm, btstack_crypto_ccm_buffer);
740 #ifdef USE_BTSTACK_AES128
741     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
742     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
743 #else
744     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
745 #endif
746 }
747 
748 static void btstack_crypto_ccm_handle_xn(btstack_crypto_ccm_t * btstack_crypto_ccm) {
749 #ifdef DEBUG_CCM
750     printf("%16s: ", "Xn+1");
751     printf_hexdump(btstack_crypto_ccm->x_i, 16);
752 #endif
753     switch (btstack_crypto_ccm->btstack_crypto.operation){
754         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
755             btstack_crypto_ccm_next_block(btstack_crypto_ccm, CCM_CALCULATE_SN);
756             break;
757         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
758             btstack_crypto_ccm->state = CCM_CALCULATE_SN;
759             break;
760         default:
761             btstack_assert(false);
762             break;
763     }
764 }
765 
766 static void btstack_crypto_ccm_calc_xn(btstack_crypto_ccm_t * btstack_crypto_ccm, const uint8_t * plaintext){
767     uint8_t btstack_crypto_ccm_buffer[16];
768     btstack_crypto_ccm->state = CCM_W4_XN;
769 
770 #ifdef DEBUG_CCM
771     printf("%16s: ", "bn");
772     printf_hexdump(plaintext, 16);
773 #endif
774     uint8_t i;
775     uint8_t bytes_to_decrypt = btstack_crypto_ccm->block_len;
776     // use explicit min implementation as c-stat worried about out-of-bounds-reads
777     if (bytes_to_decrypt > 16) {
778         bytes_to_decrypt = 16;
779     }
780     for (i = 0; i < bytes_to_decrypt ; i++){
781         btstack_crypto_ccm_buffer[i] =  btstack_crypto_ccm->x_i[i] ^ plaintext[i];
782     }
783     (void)memcpy(&btstack_crypto_ccm_buffer[i], &btstack_crypto_ccm->x_i[i],
784                  16 - bytes_to_decrypt);
785 #ifdef DEBUG_CCM
786     printf("%16s: ", "Xn XOR bn");
787     printf_hexdump(btstack_crypto_ccm_buffer, 16);
788 #endif
789 
790 #ifdef USE_BTSTACK_AES128
791     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer, btstack_crypto_ccm->x_i);
792     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
793 #else
794     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm_buffer);
795 #endif
796 }
797 
798 static void btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm_t * btstack_crypto_ccm){
799     // store length
800     if (btstack_crypto_ccm->aad_offset == 0){
801         uint8_t len_buffer[2];
802         big_endian_store_16(len_buffer, 0, btstack_crypto_ccm->aad_len);
803         btstack_crypto_ccm->x_i[0] ^= len_buffer[0];
804         btstack_crypto_ccm->x_i[1] ^= len_buffer[1];
805         btstack_crypto_ccm->aad_remainder_len += 2;
806         btstack_crypto_ccm->aad_offset        += 2;
807     }
808 
809     // fill from input
810     uint16_t bytes_free = 16 - btstack_crypto_ccm->aad_remainder_len;
811     uint16_t bytes_to_copy = btstack_min(bytes_free, btstack_crypto_ccm->block_len);
812     while (bytes_to_copy){
813         btstack_crypto_ccm->x_i[btstack_crypto_ccm->aad_remainder_len++] ^= *btstack_crypto_ccm->input++;
814         btstack_crypto_ccm->aad_offset++;
815         btstack_crypto_ccm->block_len--;
816         bytes_to_copy--;
817         bytes_free--;
818     }
819 
820     // if last block, fill with zeros
821     if (btstack_crypto_ccm->aad_offset == (btstack_crypto_ccm->aad_len + 2)){
822         btstack_crypto_ccm->aad_remainder_len = 16;
823     }
824     // if not full, notify done
825     if (btstack_crypto_ccm->aad_remainder_len < 16){
826         btstack_crypto_done(&btstack_crypto_ccm->btstack_crypto);
827         return;
828     }
829 
830     // encrypt block
831 #ifdef DEBUG_CCM
832     printf("%16s: ", "Xn XOR Bn (aad)");
833     printf_hexdump(btstack_crypto_ccm->x_i, 16);
834 #endif
835 
836     btstack_crypto_ccm->aad_remainder_len = 0;
837     btstack_crypto_ccm->state = CCM_W4_AAD_XN;
838 #ifdef USE_BTSTACK_AES128
839     btstack_aes128_calc(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i, btstack_crypto_ccm->x_i);
840     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
841 #else
842     btstack_crypto_aes128_start(btstack_crypto_ccm->key, btstack_crypto_ccm->x_i);
843 #endif
844 }
845 
846 static void btstack_crypto_run(void){
847 
848     btstack_crypto_aes128_t        * btstack_crypto_aes128;
849     btstack_crypto_ccm_t           * btstack_crypto_ccm;
850     btstack_crypto_aes128_cmac_t   * btstack_crypto_cmac;
851 #ifdef ENABLE_ECC_P256
852     btstack_crypto_ecc_p256_t      * btstack_crypto_ec_p192;
853 #endif
854 
855     // stack up and running?
856     if (hci_get_state() != HCI_STATE_WORKING) return;
857 
858     // try to do as much as possible
859     while (true){
860 
861         // anything to do?
862         if (btstack_linked_list_empty(&btstack_crypto_operations)) return;
863 
864         // already active?
865         if (btstack_crypto_wait_for_hci_result) return;
866 
867         // can send a command?
868         if (!hci_can_send_command_packet_now()) return;
869 
870         // ok, find next task
871     	btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
872     	switch (btstack_crypto->operation){
873     		case BTSTACK_CRYPTO_RANDOM:
874     			btstack_crypto_wait_for_hci_result = 1;
875     		    hci_send_cmd(&hci_le_rand);
876     		    break;
877     		case BTSTACK_CRYPTO_AES128:
878                 btstack_crypto_aes128 = (btstack_crypto_aes128_t *) btstack_crypto;
879 #ifdef USE_BTSTACK_AES128
880                 btstack_aes128_calc(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext, btstack_crypto_aes128->ciphertext);
881                 btstack_crypto_done(btstack_crypto);
882 #else
883                 btstack_crypto_aes128_start(btstack_crypto_aes128->key, btstack_crypto_aes128->plaintext);
884 #endif
885     		    break;
886 
887     		case BTSTACK_CRYPTO_CMAC_MESSAGE:
888     		case BTSTACK_CRYPTO_CMAC_GENERATOR:
889                 btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t *) btstack_crypto;
890 #ifdef USE_BTSTACK_AES128
891                 btstack_crypto_cmac_calc( btstack_crypto_cmac );
892                 btstack_crypto_done(btstack_crypto);
893 #else
894     			btstack_crypto_wait_for_hci_result = 1;
895     			if (btstack_crypto_cmac_state == CMAC_IDLE){
896     				btstack_crypto_cmac_start(btstack_crypto_cmac);
897     			} else {
898     				btstack_crypto_cmac_handle_aes_engine_ready(btstack_crypto_cmac);
899     			}
900 #endif
901     			break;
902 
903             case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
904             case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
905             case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
906                 btstack_crypto_ccm = (btstack_crypto_ccm_t *) btstack_crypto;
907                 switch (btstack_crypto_ccm->state){
908                     case CCM_CALCULATE_AAD_XN:
909 #ifdef DEBUG_CCM
910                         printf("CCM_CALCULATE_AAD_XN\n");
911 #endif
912                         btstack_crypto_ccm_calc_aad_xn(btstack_crypto_ccm);
913                         break;
914                     case CCM_CALCULATE_X1:
915 #ifdef DEBUG_CCM
916                         printf("CCM_CALCULATE_X1\n");
917 #endif
918                         btstack_crypto_ccm_calc_x1(btstack_crypto_ccm);
919                         break;
920                     case CCM_CALCULATE_S0:
921 #ifdef DEBUG_CCM
922                         printf("CCM_CALCULATE_S0\n");
923 #endif
924                         btstack_crypto_ccm_calc_s0(btstack_crypto_ccm);
925                         break;
926                     case CCM_CALCULATE_SN:
927 #ifdef DEBUG_CCM
928                         printf("CCM_CALCULATE_SN\n");
929 #endif
930                         btstack_crypto_ccm_calc_sn(btstack_crypto_ccm);
931                         break;
932                     case CCM_CALCULATE_XN:
933 #ifdef DEBUG_CCM
934                         printf("CCM_CALCULATE_XN\n");
935 #endif
936                         btstack_crypto_ccm_calc_xn(btstack_crypto_ccm, (btstack_crypto->operation == BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK) ? btstack_crypto_ccm->input : btstack_crypto_ccm->output);
937                         break;
938                     default:
939                         break;
940                 }
941                 break;
942 
943 #ifdef ENABLE_ECC_P256
944             case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
945                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
946                 switch (btstack_crypto_ecc_p256_key_generation_state){
947                     case ECC_P256_KEY_GENERATION_DONE:
948                         // done
949                         btstack_crypto_log_ec_publickey(btstack_crypto_ecc_p256_public_key);
950                         (void)memcpy(btstack_crypto_ec_p192->public_key,
951                                      btstack_crypto_ecc_p256_public_key, 64);
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                         break;
955                     case ECC_P256_KEY_GENERATION_IDLE:
956 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
957                         log_info("start ecc random");
958                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_GENERATING_RANDOM;
959                         btstack_crypto_ecc_p256_random_offset = 0;
960                         btstack_crypto_wait_for_hci_result = 1;
961                         hci_send_cmd(&hci_le_rand);
962 #else
963                         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_W4_KEY;
964                         btstack_crypto_wait_for_hci_result = 1;
965                         hci_send_cmd(&hci_le_read_local_p256_public_key);
966 #endif
967                         break;
968 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
969                     case ECC_P256_KEY_GENERATION_GENERATING_RANDOM:
970                         log_info("more ecc random");
971                         btstack_crypto_wait_for_hci_result = 1;
972                         hci_send_cmd(&hci_le_rand);
973                         break;
974 #endif
975                     default:
976                         break;
977                 }
978                 break;
979             case BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY:
980                 btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t *) btstack_crypto;
981 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
982                 btstack_crypto_ecc_p256_calculate_dhkey_software(btstack_crypto_ec_p192);
983                 // done
984                 btstack_linked_list_pop(&btstack_crypto_operations);
985                 (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
986 #else
987                 btstack_crypto_wait_for_hci_result = 1;
988                 hci_send_cmd(&hci_le_generate_dhkey, &btstack_crypto_ec_p192->public_key[0], &btstack_crypto_ec_p192->public_key[32]);
989 #endif
990                 break;
991 
992 #endif /* ENABLE_ECC_P256 */
993 
994             default:
995                 break;
996         }
997     }
998 }
999 
1000 static void btstack_crypto_handle_random_data(const uint8_t * data, uint16_t len){
1001     btstack_crypto_random_t * btstack_crypto_random;
1002     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1003     uint16_t bytes_to_copy;
1004 	if (!btstack_crypto) return;
1005     switch (btstack_crypto->operation){
1006         case BTSTACK_CRYPTO_RANDOM:
1007             btstack_crypto_random = (btstack_crypto_random_t*) btstack_crypto;
1008             bytes_to_copy = btstack_min(btstack_crypto_random->size, len);
1009             (void)memcpy(btstack_crypto_random->buffer, data, bytes_to_copy);
1010             btstack_crypto_random->buffer += bytes_to_copy;
1011             btstack_crypto_random->size   -= bytes_to_copy;
1012             // data processed, more?
1013             if (!btstack_crypto_random->size) {
1014                 // done
1015                 btstack_linked_list_pop(&btstack_crypto_operations);
1016                 (*btstack_crypto_random->btstack_crypto.context_callback.callback)(btstack_crypto_random->btstack_crypto.context_callback.context);
1017             }
1018             break;
1019 #ifdef ENABLE_ECC_P256
1020         case BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY:
1021             (void)memcpy(&btstack_crypto_ecc_p256_random[btstack_crypto_ecc_p256_random_len],
1022 			 data, 8);
1023             btstack_crypto_ecc_p256_random_len += 8;
1024             if (btstack_crypto_ecc_p256_random_len >= 64) {
1025                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_ACTIVE;
1026                 btstack_crypto_ecc_p256_generate_key_software();
1027                 btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1028             }
1029             break;
1030 #endif
1031         default:
1032             break;
1033     }
1034 	// more work?
1035 	btstack_crypto_run();
1036 }
1037 
1038 #ifndef USE_BTSTACK_AES128
1039 static void btstack_crypto_handle_encryption_result(const uint8_t * data){
1040 	btstack_crypto_aes128_t      * btstack_crypto_aes128;
1041 	btstack_crypto_aes128_cmac_t * btstack_crypto_cmac;
1042     btstack_crypto_ccm_t         * btstack_crypto_ccm;
1043 	uint8_t result[16];
1044 
1045     btstack_crypto_t * btstack_crypto = (btstack_crypto_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1046 	if (!btstack_crypto) return;
1047 	switch (btstack_crypto->operation){
1048 		case BTSTACK_CRYPTO_AES128:
1049 			btstack_crypto_aes128 = (btstack_crypto_aes128_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1050 		    reverse_128(data, btstack_crypto_aes128->ciphertext);
1051             btstack_crypto_done(btstack_crypto);
1052 			break;
1053 		case BTSTACK_CRYPTO_CMAC_GENERATOR:
1054 		case BTSTACK_CRYPTO_CMAC_MESSAGE:
1055 			btstack_crypto_cmac = (btstack_crypto_aes128_cmac_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1056 		    reverse_128(data, result);
1057 		    btstack_crypto_cmac_handle_encryption_result(btstack_crypto_cmac, result);
1058 			break;
1059         case BTSTACK_CRYPTO_CCM_DIGEST_BLOCK:
1060         case BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK:
1061         case BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK:
1062             btstack_crypto_ccm = (btstack_crypto_ccm_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1063             switch (btstack_crypto_ccm->state){
1064                 case CCM_W4_X1:
1065                     reverse_128(data, btstack_crypto_ccm->x_i);
1066                     btstack_crypto_ccm_handle_x1(btstack_crypto_ccm);
1067                     break;
1068                 case CCM_W4_XN:
1069                     reverse_128(data, btstack_crypto_ccm->x_i);
1070                     btstack_crypto_ccm_handle_xn(btstack_crypto_ccm);
1071                     break;
1072                 case CCM_W4_AAD_XN:
1073                     reverse_128(data, btstack_crypto_ccm->x_i);
1074                     btstack_crypto_ccm_handle_aad_xn(btstack_crypto_ccm);
1075                     break;
1076                 case CCM_W4_S0:
1077                     btstack_crypto_ccm_handle_s0(btstack_crypto_ccm, data);
1078                     break;
1079                 case CCM_W4_SN:
1080                     btstack_crypto_ccm_handle_sn(btstack_crypto_ccm, data);
1081                     break;
1082                 default:
1083                     break;
1084             }
1085             break;
1086 		default:
1087 			break;
1088 	}
1089 }
1090 #endif
1091 
1092 static void btstack_crypto_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1093     UNUSED(cid);         // ok: there is no channel
1094     UNUSED(size);        // ok: fixed format events read from HCI buffer
1095 
1096 #ifdef ENABLE_ECC_P256
1097 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1098     btstack_crypto_ecc_p256_t * btstack_crypto_ec_p192;
1099 #endif
1100 #endif
1101 
1102     if (packet_type != HCI_EVENT_PACKET)  return;
1103 
1104     switch (hci_event_packet_get_type(packet)){
1105         case BTSTACK_EVENT_STATE:
1106             log_info("BTSTACK_EVENT_STATE");
1107             if (btstack_event_state_get_state(packet) != HCI_STATE_HALTING) break;
1108             if (!btstack_crypto_wait_for_hci_result) break;
1109             // request stack to defer shutdown a bit
1110             hci_halting_defer();
1111             break;
1112 
1113         case HCI_EVENT_COMMAND_COMPLETE:
1114 #ifndef USE_BTSTACK_AES128
1115     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_encrypt)){
1116                 if (!btstack_crypto_wait_for_hci_result) return;
1117                 btstack_crypto_wait_for_hci_result = 0;
1118     	        btstack_crypto_handle_encryption_result(&packet[6]);
1119     	    }
1120 #endif
1121     	    if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_rand)){
1122                 if (!btstack_crypto_wait_for_hci_result) return;
1123                 btstack_crypto_wait_for_hci_result = 0;
1124     	        btstack_crypto_handle_random_data(&packet[6], 8);
1125     	    }
1126             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1127                 int ecdh_operations_supported = (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x06) == 0x06;
1128                 UNUSED(ecdh_operations_supported);
1129                 log_info("controller supports ECDH operation: %u", ecdh_operations_supported);
1130 #ifdef ENABLE_ECC_P256
1131 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1132                 if (!ecdh_operations_supported){
1133                     // mbedTLS can also be used if already available (and malloc is supported)
1134                     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");
1135                 }
1136 #endif
1137 #endif
1138             }
1139             break;
1140 
1141 #ifdef ENABLE_ECC_P256
1142 #ifndef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1143         case HCI_EVENT_LE_META:
1144             btstack_crypto_ec_p192 = (btstack_crypto_ecc_p256_t*) btstack_linked_list_get_first_item(&btstack_crypto_operations);
1145             if (!btstack_crypto_ec_p192) break;
1146             switch (hci_event_le_meta_get_subevent_code(packet)){
1147                 case HCI_SUBEVENT_LE_READ_LOCAL_P256_PUBLIC_KEY_COMPLETE:
1148                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY) break;
1149                     if (!btstack_crypto_wait_for_hci_result) return;
1150                     btstack_crypto_wait_for_hci_result = 0;
1151                     if (hci_subevent_le_read_local_p256_public_key_complete_get_status(packet)){
1152                         log_error("Read Local P256 Public Key failed");
1153                     }
1154                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_x(packet, &btstack_crypto_ecc_p256_public_key[0]);
1155                     hci_subevent_le_read_local_p256_public_key_complete_get_dhkey_y(packet, &btstack_crypto_ecc_p256_public_key[32]);
1156                     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1157                     break;
1158                 case HCI_SUBEVENT_LE_GENERATE_DHKEY_COMPLETE:
1159                     if (btstack_crypto_ec_p192->btstack_crypto.operation != BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY) break;
1160                     if (!btstack_crypto_wait_for_hci_result) return;
1161                     btstack_crypto_wait_for_hci_result = 0;
1162                     if (hci_subevent_le_generate_dhkey_complete_get_status(packet)){
1163                         log_error("Generate DHKEY failed -> abort");
1164                     }
1165                     hci_subevent_le_generate_dhkey_complete_get_dhkey(packet, btstack_crypto_ec_p192->dhkey);
1166                     // done
1167                     btstack_linked_list_pop(&btstack_crypto_operations);
1168                     (*btstack_crypto_ec_p192->btstack_crypto.context_callback.callback)(btstack_crypto_ec_p192->btstack_crypto.context_callback.context);
1169                     break;
1170                 default:
1171                     break;
1172             }
1173             break;
1174 #endif
1175 #endif
1176         default:
1177             break;
1178     }
1179 
1180     // try processing
1181 	btstack_crypto_run();
1182 }
1183 
1184 void btstack_crypto_init(void){
1185 	if (btstack_crypto_initialized) return;
1186 	btstack_crypto_initialized = 1;
1187 
1188 	// register with HCI
1189     hci_event_callback_registration.callback = &btstack_crypto_event_handler;
1190     hci_add_event_handler(&hci_event_callback_registration);
1191 
1192 #ifdef USE_MBEDTLS_ECC_P256
1193 	mbedtls_ecp_group_init(&mbedtls_ec_group);
1194 	mbedtls_ecp_group_load(&mbedtls_ec_group, MBEDTLS_ECP_DP_SECP256R1);
1195 #endif
1196 }
1197 
1198 void btstack_crypto_random_generate(btstack_crypto_random_t * request, uint8_t * buffer, uint16_t size, void (* callback)(void * arg), void * callback_arg){
1199 	request->btstack_crypto.context_callback.callback  = callback;
1200 	request->btstack_crypto.context_callback.context   = callback_arg;
1201 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_RANDOM;
1202 	request->buffer = buffer;
1203 	request->size   = size;
1204 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1205 	btstack_crypto_run();
1206 }
1207 
1208 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){
1209 	request->btstack_crypto.context_callback.callback  = callback;
1210 	request->btstack_crypto.context_callback.context   = callback_arg;
1211 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_AES128;
1212 	request->key 									   = key;
1213 	request->plaintext      					       = plaintext;
1214 	request->ciphertext 							   = ciphertext;
1215 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1216 	btstack_crypto_run();
1217 }
1218 
1219 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){
1220 	request->btstack_crypto.context_callback.callback  = callback;
1221 	request->btstack_crypto.context_callback.context   = callback_arg;
1222 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_GENERATOR;
1223 	request->key 									   = key;
1224 	request->size 									   = size;
1225 	request->data.get_byte_callback					   = get_byte_callback;
1226 	request->hash 									   = hash;
1227 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1228 	btstack_crypto_run();
1229 }
1230 
1231 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){
1232 	request->btstack_crypto.context_callback.callback  = callback;
1233 	request->btstack_crypto.context_callback.context   = callback_arg;
1234 	request->btstack_crypto.operation         		   = BTSTACK_CRYPTO_CMAC_MESSAGE;
1235 	request->key 									   = key;
1236 	request->size 									   = size;
1237 	request->data.message      						   = message;
1238 	request->hash 									   = hash;
1239 	btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1240 	btstack_crypto_run();
1241 }
1242 
1243 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){
1244     request->btstack_crypto.context_callback.callback  = callback;
1245     request->btstack_crypto.context_callback.context   = callback_arg;
1246     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CMAC_MESSAGE;
1247     request->key                                       = zero;
1248     request->size                                      = len;
1249     request->data.message                              = message;
1250     request->hash                                      = hash;
1251     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1252     btstack_crypto_run();
1253 }
1254 
1255 #ifdef ENABLE_ECC_P256
1256 void btstack_crypto_ecc_p256_generate_key(btstack_crypto_ecc_p256_t * request, uint8_t * public_key, void (* callback)(void * arg), void * callback_arg){
1257     // reset key generation
1258     if (btstack_crypto_ecc_p256_key_generation_state == ECC_P256_KEY_GENERATION_DONE){
1259         btstack_crypto_ecc_p256_random_len = 0;
1260         btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_IDLE;
1261     }
1262     request->btstack_crypto.context_callback.callback  = callback;
1263     request->btstack_crypto.context_callback.context   = callback_arg;
1264     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_GENERATE_KEY;
1265     request->public_key                                = public_key;
1266     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1267     btstack_crypto_run();
1268 }
1269 
1270 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){
1271     request->btstack_crypto.context_callback.callback  = callback;
1272     request->btstack_crypto.context_callback.context   = callback_arg;
1273     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_ECC_P256_CALCULATE_DHKEY;
1274     request->public_key                                = (uint8_t *) public_key;
1275     request->dhkey                                     = dhkey;
1276     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1277     btstack_crypto_run();
1278 }
1279 
1280 int btstack_crypto_ecc_p256_validate_public_key(const uint8_t * public_key){
1281 
1282     // validate public key using micro-ecc
1283     int err = 0;
1284 
1285 #ifdef USE_MICRO_ECC_P256
1286 #if uECC_SUPPORTS_secp256r1
1287     // standard version
1288     err = uECC_valid_public_key(public_key, uECC_secp256r1()) == 0;
1289 #else
1290     // static version
1291     err = uECC_valid_public_key(public_key) == 0;
1292 #endif
1293 #endif
1294 
1295 #ifdef USE_MBEDTLS_ECC_P256
1296     mbedtls_ecp_point Q;
1297     mbedtls_ecp_point_init( &Q );
1298     mbedtls_mpi_read_binary(&Q.X, &public_key[0], 32);
1299     mbedtls_mpi_read_binary(&Q.Y, &public_key[32], 32);
1300     mbedtls_mpi_lset(&Q.Z, 1);
1301     err = mbedtls_ecp_check_pubkey(&mbedtls_ec_group, &Q);
1302     mbedtls_ecp_point_free( & Q);
1303 #endif
1304 
1305     if (err){
1306         log_error("public key invalid %x", err);
1307     }
1308     return  err;
1309 }
1310 #endif
1311 
1312 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){
1313     request->key         = key;
1314     request->nonce       = nonce;
1315     request->message_len = message_len;
1316     request->aad_len     = additional_authenticated_data_len;
1317     request->aad_offset  = 0;
1318     request->auth_len    = auth_len;
1319     request->counter     = 1;
1320     request->state       = CCM_CALCULATE_X1;
1321 }
1322 
1323 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){
1324     // not implemented yet
1325     request->btstack_crypto.context_callback.callback  = callback;
1326     request->btstack_crypto.context_callback.context   = callback_arg;
1327     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DIGEST_BLOCK;
1328     request->block_len                                 = additional_authenticated_data_len;
1329     request->input                                     = additional_authenticated_data;
1330     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1331     btstack_crypto_run();
1332 }
1333 
1334 void btstack_crypto_ccm_get_authentication_value(btstack_crypto_ccm_t * request, uint8_t * authentication_value){
1335     (void)memcpy(authentication_value, request->x_i, request->auth_len);
1336 }
1337 
1338 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){
1339 #ifdef DEBUG_CCM
1340     printf("\nbtstack_crypto_ccm_encrypt_block, len %u\n", block_len);
1341 #endif
1342     request->btstack_crypto.context_callback.callback  = callback;
1343     request->btstack_crypto.context_callback.context   = callback_arg;
1344     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_ENCRYPT_BLOCK;
1345     request->block_len                                 = block_len;
1346     request->input                                     = plaintext;
1347     request->output                                    = ciphertext;
1348     if (request->state != CCM_CALCULATE_X1){
1349         request->state  = CCM_CALCULATE_XN;
1350     }
1351     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1352     btstack_crypto_run();
1353 }
1354 
1355 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){
1356     request->btstack_crypto.context_callback.callback  = callback;
1357     request->btstack_crypto.context_callback.context   = callback_arg;
1358     request->btstack_crypto.operation                  = BTSTACK_CRYPTO_CCM_DECRYPT_BLOCK;
1359     request->block_len                                 = block_len;
1360     request->input                                     = ciphertext;
1361     request->output                                    = plaintext;
1362     if (request->state != CCM_CALCULATE_X1){
1363         request->state  = CCM_CALCULATE_SN;
1364     }
1365     btstack_linked_list_add_tail(&btstack_crypto_operations, (btstack_linked_item_t*) request);
1366     btstack_crypto_run();
1367 }
1368 
1369 // PTS only
1370 void btstack_crypto_ecc_p256_set_key(const uint8_t * public_key, const uint8_t * private_key){
1371 #ifdef USE_SOFTWARE_ECC_P256_IMPLEMENTATION
1372     (void)memcpy(btstack_crypto_ecc_p256_d, private_key, 32);
1373     (void)memcpy(btstack_crypto_ecc_p256_public_key, public_key, 64);
1374     btstack_crypto_ecc_p256_key_generation_state = ECC_P256_KEY_GENERATION_DONE;
1375 #else
1376     UNUSED(public_key);
1377     UNUSED(private_key);
1378 #endif
1379 }
1380 // Unit testing
1381 int btstack_crypto_idle(void){
1382     return btstack_linked_list_empty(&btstack_crypto_operations);
1383 }
1384 void btstack_crypto_reset(void){
1385     btstack_crypto_operations = NULL;
1386     btstack_crypto_wait_for_hci_result = 0;
1387 }
1388