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