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