1 /**
2  * \brief GCM block cipher, ESP DMA hardware accelerated version
3  * Based on mbedTLS FIPS-197 compliant version.
4  *
5  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
6  *  Additions Copyright (C) 2016-2020, Espressif Systems (Shanghai) PTE Ltd
7  *  SPDX-License-Identifier: Apache-2.0
8  *
9  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
10  *  not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *  http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  *
21  */
22 /*
23  *  The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
24  *
25  *  http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
26  *  http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
27  */
28 
29 #include "soc/soc_caps.h"
30 
31 #if SOC_AES_SUPPORT_GCM
32 
33 #include "aes/esp_aes.h"
34 #include "aes/esp_aes_gcm.h"
35 #include "aes/esp_aes_internal.h"
36 #include "hal/aes_hal.h"
37 
38 #include "esp_log.h"
39 #include "mbedtls/aes.h"
40 #include "esp_heap_caps.h"
41 #include "soc/soc_memory_layout.h"
42 
43 #include <string.h>
44 
45 #define ESP_PUT_BE64(a, val)                                    \
46     do {                                                        \
47         *(uint64_t*)(a) = __builtin_bswap64( (uint64_t)(val) ); \
48     } while (0)
49 
50 /* For simplicity limit the maxium amount of aad bytes to a single DMA descriptor
51    This should cover all normal, e.g. mbedtls, use cases */
52 #define ESP_AES_GCM_AAD_MAX_BYTES 4080
53 
54 static const char *TAG = "esp-aes-gcm";
55 
56 static void esp_gcm_ghash(esp_gcm_context *ctx, const unsigned char *x, size_t x_len, uint8_t *z);
57 
58 /*
59  * Calculates the Initial Counter Block, J0
60  * and copies to to the esp_gcm_context
61  */
esp_gcm_derive_J0(esp_gcm_context * ctx)62 static void esp_gcm_derive_J0(esp_gcm_context *ctx)
63 {
64     uint8_t len_buf[16];
65 
66     memset(ctx->J0, 0, AES_BLOCK_BYTES);
67     memset(len_buf, 0, AES_BLOCK_BYTES);
68 
69     /* If IV is 96 bits J0 = ( IV || 0^31 || 1 ) */
70     if (ctx->iv_len == 12) {
71         memcpy(ctx->J0, ctx->iv, ctx->iv_len);
72         ctx->J0[AES_BLOCK_BYTES - 1] |= 1;
73     } else {
74         /* For IV != 96 bit, J0 = GHASH(IV || 0[s+64] || [len(IV)]64) */
75         /* First calculate GHASH on IV */
76         esp_gcm_ghash(ctx, ctx->iv, ctx->iv_len, ctx->J0);
77         /* Next create 128 bit block which is equal to
78         64 bit 0 + iv length truncated to 64 bits */
79         ESP_PUT_BE64(len_buf + 8, ctx->iv_len * 8);
80         /*   Calculate GHASH on last block */
81         esp_gcm_ghash(ctx, len_buf, 16, ctx->J0);
82 
83 
84     }
85 }
86 
87 
88 /*
89  * Increment J0 as per GCM spec, by applying the Standard Incrementing
90    Function INC_32 to it.
91  * j is the counter which needs to be incremented which is
92  * copied to ctx->J0 after incrementing
93  */
increment32_j0(esp_gcm_context * ctx,uint8_t * j)94 static void increment32_j0(esp_gcm_context *ctx, uint8_t *j)
95 {
96     uint8_t j_len = AES_BLOCK_BYTES;
97     memcpy(j, ctx->J0, AES_BLOCK_BYTES);
98     if (j) {
99         for (uint32_t i = j_len; i > (j_len - 4); i--) {
100             if (++j[i - 1] != 0) {
101                 break;
102             }
103         }
104         memcpy(ctx->J0, j, AES_BLOCK_BYTES);
105     }
106 }
107 
108 /* Function to xor two data blocks */
xor_data(uint8_t * d,const uint8_t * s)109 static void xor_data(uint8_t *d, const uint8_t *s)
110 {
111     uint32_t *dst = (uint32_t *) d;
112     uint32_t *src = (uint32_t *) s;
113     *dst++ ^= *src++;
114     *dst++ ^= *src++;
115     *dst++ ^= *src++;
116     *dst++ ^= *src++;
117 }
118 
119 
120 /*
121  * 32-bit integer manipulation macros (big endian)
122  */
123 #ifndef GET_UINT32_BE
124 #define GET_UINT32_BE(n,b,i)                            \
125 {                                                       \
126     (n) = ( (uint32_t) (b)[(i)    ] << 24 )             \
127         | ( (uint32_t) (b)[(i) + 1] << 16 )             \
128         | ( (uint32_t) (b)[(i) + 2] <<  8 )             \
129         | ( (uint32_t) (b)[(i) + 3]       );            \
130 }
131 #endif
132 
133 #ifndef PUT_UINT32_BE
134 #define PUT_UINT32_BE(n,b,i)                            \
135 {                                                       \
136     (b)[(i)    ] = (unsigned char) ( (n) >> 24 );       \
137     (b)[(i) + 1] = (unsigned char) ( (n) >> 16 );       \
138     (b)[(i) + 2] = (unsigned char) ( (n) >>  8 );       \
139     (b)[(i) + 3] = (unsigned char) ( (n)       );       \
140 }
141 #endif
142 
143 /* Based on MbedTLS's implemenation
144  *
145  * Precompute small multiples of H, that is set
146  *      HH[i] || HL[i] = H times i,
147  * where i is seen as a field element as in [MGV], ie high-order bits
148  * correspond to low powers of P. The result is stored in the same way, that
149  * is the high-order bit of HH corresponds to P^0 and the low-order bit of HL
150  * corresponds to P^127.
151  */
gcm_gen_table(esp_gcm_context * ctx)152 static int gcm_gen_table( esp_gcm_context *ctx )
153 {
154     int i, j;
155     uint64_t hi, lo;
156     uint64_t vl, vh;
157     unsigned char *h;
158 
159     h = ctx->H;
160 
161     /* pack h as two 64-bits ints, big-endian */
162     GET_UINT32_BE( hi, h,  0  );
163     GET_UINT32_BE( lo, h,  4  );
164     vh = (uint64_t) hi << 32 | lo;
165 
166     GET_UINT32_BE( hi, h,  8  );
167     GET_UINT32_BE( lo, h,  12 );
168     vl = (uint64_t) hi << 32 | lo;
169 
170     /* 8 = 1000 corresponds to 1 in GF(2^128) */
171     ctx->HL[8] = vl;
172     ctx->HH[8] = vh;
173 
174     /* 0 corresponds to 0 in GF(2^128) */
175     ctx->HH[0] = 0;
176     ctx->HL[0] = 0;
177 
178     for ( i = 4; i > 0; i >>= 1 ) {
179         uint32_t T = ( vl & 1 ) * 0xe1000000U;
180         vl  = ( vh << 63 ) | ( vl >> 1 );
181         vh  = ( vh >> 1 ) ^ ( (uint64_t) T << 32);
182 
183         ctx->HL[i] = vl;
184         ctx->HH[i] = vh;
185     }
186 
187     for ( i = 2; i <= 8; i *= 2 ) {
188         uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
189         vh = *HiH;
190         vl = *HiL;
191         for ( j = 1; j < i; j++ ) {
192             HiH[j] = vh ^ ctx->HH[j];
193             HiL[j] = vl ^ ctx->HL[j];
194         }
195     }
196 
197     return ( 0 );
198 }
199 /*
200  * Shoup's method for multiplication use this table with
201  *      last4[x] = x times P^128
202  * where x and last4[x] are seen as elements of GF(2^128) as in [MGV]
203  */
204 static const uint64_t last4[16] = {
205     0x0000, 0x1c20, 0x3840, 0x2460,
206     0x7080, 0x6ca0, 0x48c0, 0x54e0,
207     0xe100, 0xfd20, 0xd940, 0xc560,
208     0x9180, 0x8da0, 0xa9c0, 0xb5e0
209 };
210 /* Based on MbedTLS's implemenation
211  *
212  * Sets output to x times H using the precomputed tables.
213  * x and output are seen as elements of GF(2^128) as in [MGV].
214  */
gcm_mult(esp_gcm_context * ctx,const unsigned char x[16],unsigned char output[16])215 static void gcm_mult( esp_gcm_context *ctx, const unsigned char x[16],
216                       unsigned char output[16] )
217 {
218     int i = 0;
219     unsigned char lo, hi, rem;
220     uint64_t zh, zl;
221 
222     lo = x[15] & 0xf;
223 
224     zh = ctx->HH[lo];
225     zl = ctx->HL[lo];
226 
227     for ( i = 15; i >= 0; i-- ) {
228         lo = x[i] & 0xf;
229         hi = x[i] >> 4;
230 
231         if ( i != 15 ) {
232             rem = (unsigned char) zl & 0xf;
233             zl = ( zh << 60 ) | ( zl >> 4 );
234             zh = ( zh >> 4 );
235             zh ^= (uint64_t) last4[rem] << 48;
236             zh ^= ctx->HH[lo];
237             zl ^= ctx->HL[lo];
238 
239         }
240 
241         rem = (unsigned char) zl & 0xf;
242         zl = ( zh << 60 ) | ( zl >> 4 );
243         zh = ( zh >> 4 );
244         zh ^= (uint64_t) last4[rem] << 48;
245         zh ^= ctx->HH[hi];
246         zl ^= ctx->HL[hi];
247     }
248 
249     PUT_UINT32_BE( zh >> 32, output, 0 );
250     PUT_UINT32_BE( zh, output, 4 );
251     PUT_UINT32_BE( zl >> 32, output, 8 );
252     PUT_UINT32_BE( zl, output, 12 );
253 }
254 
255 
256 
257 /* Update the key value in gcm context */
esp_aes_gcm_setkey(esp_gcm_context * ctx,mbedtls_cipher_id_t cipher,const unsigned char * key,unsigned int keybits)258 int esp_aes_gcm_setkey( esp_gcm_context *ctx,
259                         mbedtls_cipher_id_t cipher,
260                         const unsigned char *key,
261                         unsigned int keybits )
262 {
263     if (keybits != 128 && keybits != 192 && keybits != 256) {
264         return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH;
265     }
266 
267 
268     ctx->aes_ctx.key_bytes = keybits / 8;
269 
270     memcpy(ctx->aes_ctx.key, key, ctx->aes_ctx.key_bytes);
271 
272     return ( 0 );
273 }
274 
275 
276 /* AES-GCM GHASH calculation z = GHASH(x) using h0 hash key
277 */
esp_gcm_ghash(esp_gcm_context * ctx,const unsigned char * x,size_t x_len,uint8_t * z)278 static void esp_gcm_ghash(esp_gcm_context *ctx, const unsigned char *x, size_t x_len, uint8_t *z)
279 {
280 
281     uint8_t tmp[AES_BLOCK_BYTES];
282 
283     memset(tmp, 0, AES_BLOCK_BYTES);
284     /* GHASH(X) is calculated on input string which is multiple of 128 bits
285      * If input string bit length is not multiple of 128 bits it needs to
286      * be padded by 0
287      *
288      * Steps:
289      * 1. Let X1, X2, ... , Xm-1, Xm denote the unique sequence of blocks such
290      * that X = X1 || X2 || ... || Xm-1 || Xm.
291      * 2. Let Y0 be the “zero block,” 0128.
292      * 3. Fori=1,...,m,letYi =(Yi-1 ^ Xi)•H.
293      * 4. Return Ym
294      */
295 
296     /* If input bit string is >= 128 bits, process full 128 bit blocks */
297     while (x_len >= AES_BLOCK_BYTES) {
298 
299         xor_data(z, x);
300         gcm_mult(ctx, z, z);
301 
302         x += AES_BLOCK_BYTES;
303         x_len -= AES_BLOCK_BYTES;
304     }
305 
306     /* If input bit string is not multiple of 128 create last 128 bit
307      * block by padding necessary 0s
308      */
309     if (x_len) {
310         memcpy(tmp, x, x_len);
311         xor_data(z, tmp);
312         gcm_mult(ctx, z, z);
313     }
314 }
315 
316 
317 /* Function to init AES GCM context to zero */
esp_aes_gcm_init(esp_gcm_context * ctx)318 void esp_aes_gcm_init( esp_gcm_context *ctx)
319 {
320     if (ctx == NULL) {
321         return;
322     }
323 
324     bzero(ctx, sizeof(esp_gcm_context));
325 
326     ctx->gcm_state = ESP_AES_GCM_STATE_INIT;
327 }
328 
329 /* Function to clear AES-GCM context */
esp_aes_gcm_free(esp_gcm_context * ctx)330 void esp_aes_gcm_free( esp_gcm_context *ctx)
331 {
332     if (ctx == NULL) {
333         return;
334     }
335     bzero(ctx, sizeof(esp_gcm_context));
336 }
337 
338 /* Setup AES-GCM */
esp_aes_gcm_starts(esp_gcm_context * ctx,int mode,const unsigned char * iv,size_t iv_len,const unsigned char * aad,size_t aad_len)339 int esp_aes_gcm_starts( esp_gcm_context *ctx,
340                         int mode,
341                         const unsigned char *iv,
342                         size_t iv_len,
343                         const unsigned char *aad,
344                         size_t aad_len )
345 {
346     /* IV and AD are limited to 2^32 bits, so 2^29 bytes */
347     /* IV is not allowed to be zero length */
348     if ( iv_len == 0 ||
349             ( (uint32_t) iv_len  ) >> 29 != 0 ||
350             ( (uint32_t) aad_len ) >> 29 != 0 ) {
351         return ( MBEDTLS_ERR_GCM_BAD_INPUT );
352     }
353 
354     if (!ctx) {
355         ESP_LOGE(TAG, "No AES context supplied");
356         return -1;
357     }
358 
359     if (!iv) {
360         ESP_LOGE(TAG, "No IV supplied");
361         return -1;
362     }
363 
364     if ( (aad_len > 0) && !aad) {
365         ESP_LOGE(TAG, "No aad supplied");
366         return -1;
367     }
368 
369     /* Initialize AES-GCM context */
370     memset(ctx->ghash, 0, sizeof(ctx->ghash));
371     ctx->data_len = 0;
372 
373     ctx->iv = iv;
374     ctx->iv_len = iv_len;
375     ctx->aad = aad;
376     ctx->aad_len = aad_len;
377     ctx->mode = mode;
378 
379     /* H and the lookup table are only generated once per ctx */
380     if (ctx->gcm_state == ESP_AES_GCM_STATE_INIT) {
381         /* Lock the AES engine to calculate ghash key H in hardware */
382         esp_aes_acquire_hardware();
383         ctx->aes_ctx.key_in_hardware = aes_hal_setkey(ctx->aes_ctx.key, ctx->aes_ctx.key_bytes, mode);
384         aes_hal_mode_init(ESP_AES_BLOCK_MODE_GCM);
385 
386         aes_hal_gcm_calc_hash(ctx->H);
387 
388         esp_aes_release_hardware();
389 
390         gcm_gen_table(ctx);
391     }
392 
393     ctx->gcm_state = ESP_AES_GCM_STATE_START;
394 
395     /* Once H is obtained we need to derive J0 (Initial Counter Block) */
396     esp_gcm_derive_J0(ctx);
397 
398     /* The initial counter block keeps updating during the esp_gcm_update call
399      * however to calculate final authentication tag T we need original J0
400      * so we make a copy here
401      */
402     memcpy(ctx->ori_j0, ctx->J0, 16);
403 
404     esp_gcm_ghash(ctx, ctx->aad, ctx->aad_len, ctx->ghash);
405 
406     return ( 0 );
407 }
408 
409 /* Perform AES-GCM operation */
esp_aes_gcm_update(esp_gcm_context * ctx,size_t length,const unsigned char * input,unsigned char * output)410 int esp_aes_gcm_update( esp_gcm_context *ctx,
411                         size_t length,
412                         const unsigned char *input,
413                         unsigned char *output )
414 {
415     size_t nc_off = 0;
416     uint8_t nonce_counter[AES_BLOCK_BYTES] = {0};
417     uint8_t stream[AES_BLOCK_BYTES] = {0};
418 
419     if (!ctx) {
420         ESP_LOGE(TAG, "No GCM context supplied");
421         return -1;
422     }
423     if (!input) {
424         ESP_LOGE(TAG, "No input supplied");
425         return -1;
426     }
427     if (!output) {
428         ESP_LOGE(TAG, "No output supplied");
429         return -1;
430     }
431 
432     if ( output > input && (size_t) ( output - input ) < length ) {
433         return ( MBEDTLS_ERR_GCM_BAD_INPUT );
434     }
435     /* If this is the first time esp_gcm_update is getting called
436      * calculate GHASH on aad and preincrement the ICB
437      */
438     if (ctx->gcm_state == ESP_AES_GCM_STATE_START) {
439         /* Jo needs to be incremented first time, later the CTR
440          * operation will auto update it
441          */
442         increment32_j0(ctx, nonce_counter);
443         ctx->gcm_state = ESP_AES_GCM_STATE_UPDATE;
444     } else if (ctx->gcm_state == ESP_AES_GCM_STATE_UPDATE) {
445         memcpy(nonce_counter, ctx->J0, AES_BLOCK_BYTES);
446     }
447 
448     /* Perform intermediate GHASH on "encrypted" data during decryption */
449     if (ctx->mode == ESP_AES_DECRYPT) {
450         esp_gcm_ghash(ctx, input, length, ctx->ghash);
451     }
452 
453     /* Output = GCTR(J0, Input): Encrypt/Decrypt the input */
454     esp_aes_crypt_ctr(&ctx->aes_ctx, length, &nc_off, nonce_counter, stream, input, output);
455 
456     /* ICB gets auto incremented after GCTR operation here so update the context */
457     memcpy(ctx->J0, nonce_counter, AES_BLOCK_BYTES);
458 
459     /* Keep updating the length counter for final tag calculation */
460     ctx->data_len += length;
461 
462     /* Perform intermediate GHASH on "encrypted" data during encryption*/
463     if (ctx->mode == ESP_AES_ENCRYPT) {
464         esp_gcm_ghash(ctx, output, length, ctx->ghash);
465     }
466 
467     return 0;
468 }
469 
470 /* Function to read the tag value */
esp_aes_gcm_finish(esp_gcm_context * ctx,unsigned char * tag,size_t tag_len)471 int esp_aes_gcm_finish( esp_gcm_context *ctx,
472                         unsigned char *tag,
473                         size_t tag_len )
474 {
475     size_t nc_off = 0;
476     uint8_t len_block[AES_BLOCK_BYTES] = {0};
477 
478     if ( tag_len > 16 || tag_len < 4 ) {
479         return ( MBEDTLS_ERR_GCM_BAD_INPUT );
480     }
481 
482     /* Calculate final GHASH on aad_len, data length */
483     ESP_PUT_BE64(len_block, ctx->aad_len * 8);
484     ESP_PUT_BE64(len_block + 8, ctx->data_len * 8);
485     esp_gcm_ghash(ctx, len_block, AES_BLOCK_BYTES, ctx->ghash);
486 
487     /* Tag T = GCTR(J0, ) where T is truncated to tag_len */
488     esp_aes_crypt_ctr(&ctx->aes_ctx, tag_len, &nc_off, ctx->ori_j0, 0, ctx->ghash, tag);
489 
490     return 0;
491 }
492 
493 /* Due to restrictions in the hardware (e.g. need to do the whole conversion in one go),
494    some combinations of inputs are not supported */
esp_aes_gcm_input_support_hw_accel(size_t length,const unsigned char * aad,size_t aad_len,const unsigned char * input,unsigned char * output)495 static bool esp_aes_gcm_input_support_hw_accel(size_t length, const unsigned char *aad, size_t aad_len,
496                                                const unsigned char *input, unsigned char *output)
497 {
498     bool support_hw_accel = true;
499 
500     if (aad_len > ESP_AES_GCM_AAD_MAX_BYTES) {
501         support_hw_accel = false;
502     } else if (!esp_ptr_dma_capable(aad) && aad_len > 0) {
503         /* aad in non internal DMA memory */
504         support_hw_accel = false;
505     } else if (!esp_ptr_dma_capable(input) && length > 0) {
506         /* input in non internal DMA memory */
507         support_hw_accel = false;
508     } else if (!esp_ptr_dma_capable(output) && length > 0) {
509         /* output in non internal DMA memory */
510         support_hw_accel = false;
511     } else if (length == 0) {
512         support_hw_accel = false;
513     }
514 
515     return support_hw_accel;
516 }
517 
esp_aes_gcm_crypt_and_tag_partial_hw(esp_gcm_context * ctx,int mode,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * aad,size_t aad_len,const unsigned char * input,unsigned char * output,size_t tag_len,unsigned char * tag)518 static int esp_aes_gcm_crypt_and_tag_partial_hw( esp_gcm_context *ctx,
519         int mode,
520         size_t length,
521         const unsigned char *iv,
522         size_t iv_len,
523         const unsigned char *aad,
524         size_t aad_len,
525         const unsigned char *input,
526         unsigned char *output,
527         size_t tag_len,
528         unsigned char *tag )
529 {
530     int ret = 0;
531 
532     if ( ( ret = esp_aes_gcm_starts( ctx, mode, iv, iv_len, aad, aad_len ) ) != 0 ) {
533         return ( ret );
534     }
535 
536     if ( ( ret = esp_aes_gcm_update( ctx, length, input, output ) ) != 0 ) {
537         return ( ret );
538     }
539 
540     if ( ( ret = esp_aes_gcm_finish( ctx, tag, tag_len ) ) != 0 ) {
541         return ( ret );
542     }
543 
544     return ret;
545 }
546 
esp_aes_gcm_crypt_and_tag(esp_gcm_context * ctx,int mode,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * aad,size_t aad_len,const unsigned char * input,unsigned char * output,size_t tag_len,unsigned char * tag)547 int esp_aes_gcm_crypt_and_tag( esp_gcm_context *ctx,
548                                int mode,
549                                size_t length,
550                                const unsigned char *iv,
551                                size_t iv_len,
552                                const unsigned char *aad,
553                                size_t aad_len,
554                                const unsigned char *input,
555                                unsigned char *output,
556                                size_t tag_len,
557                                unsigned char *tag )
558 {
559     int ret;
560     lldesc_t aad_desc[2] = {};
561     lldesc_t *aad_head_desc = NULL;
562     size_t remainder_bit;
563     uint8_t stream_in[AES_BLOCK_BYTES] = {};
564     unsigned stream_bytes = aad_len % AES_BLOCK_BYTES; // bytes which aren't in a full block
565     unsigned block_bytes = aad_len - stream_bytes;     // bytes which are in a full block
566 
567     /* Due to hardware limition only certain cases are fully supported in HW */
568     if (!esp_aes_gcm_input_support_hw_accel(length, aad, aad_len, input, output)) {
569         return esp_aes_gcm_crypt_and_tag_partial_hw(ctx, mode, length, iv, iv_len, aad, aad_len, input, output, tag_len, tag);
570     }
571 
572     /* Limit aad len to a single DMA descriptor to simplify DMA handling
573        In practice, e.g. with mbedtls the length of aad will always be short
574     */
575     if (aad_len > LLDESC_MAX_NUM_PER_DESC) {
576         return -1;
577     }
578     /* IV and AD are limited to 2^32 bits, so 2^29 bytes */
579     /* IV is not allowed to be zero length */
580     if ( iv_len == 0 ||
581             ( (uint32_t) iv_len  ) >> 29 != 0 ||
582             ( (uint32_t) aad_len ) >> 29 != 0 ) {
583         return ( MBEDTLS_ERR_GCM_BAD_INPUT );
584     }
585 
586     if (!ctx) {
587         ESP_LOGE(TAG, "No AES context supplied");
588         return -1;
589     }
590 
591     if (!iv) {
592         ESP_LOGE(TAG, "No IV supplied");
593         return -1;
594     }
595 
596     if ( (aad_len > 0) && !aad) {
597         ESP_LOGE(TAG, "No aad supplied");
598         return -1;
599     }
600 
601     /* Initialize AES-GCM context */
602     memset(ctx->ghash, 0, sizeof(ctx->ghash));
603     ctx->data_len = 0;
604 
605     ctx->iv = iv;
606     ctx->iv_len = iv_len;
607     ctx->aad = aad;
608     ctx->aad_len = aad_len;
609     ctx->mode = mode;
610 
611     esp_aes_acquire_hardware();
612     ctx->aes_ctx.key_in_hardware = 0;
613     ctx->aes_ctx.key_in_hardware = aes_hal_setkey(ctx->aes_ctx.key, ctx->aes_ctx.key_bytes, mode);
614 
615     if (block_bytes > 0) {
616         aad_desc[0].length = block_bytes;
617         aad_desc[0].size = block_bytes;
618         aad_desc[0].owner = 1;
619         aad_desc[0].buf = aad;
620     }
621 
622     if (stream_bytes > 0) {
623         memcpy(stream_in, aad + block_bytes, stream_bytes);
624 
625         aad_desc[0].empty = (uint32_t)&aad_desc[1];
626         aad_desc[1].length = AES_BLOCK_BYTES;
627         aad_desc[1].size = AES_BLOCK_BYTES;
628         aad_desc[1].owner = 1;
629         aad_desc[1].buf = stream_in;
630     }
631 
632     if (block_bytes > 0) {
633         aad_head_desc = &aad_desc[0];
634     } else if (stream_bytes > 0) {
635         aad_head_desc = &aad_desc[1];
636     }
637 
638     aes_hal_mode_init(ESP_AES_BLOCK_MODE_GCM);
639 
640     /* See TRM GCM chapter for description of this calculation */
641     remainder_bit = (8 * length) % 128;
642     aes_hal_gcm_init( (aad_len + AES_BLOCK_BYTES - 1) / AES_BLOCK_BYTES, remainder_bit);
643     aes_hal_gcm_calc_hash(ctx->H);
644 
645     gcm_gen_table(ctx);
646     esp_gcm_derive_J0(ctx);
647 
648     aes_hal_gcm_set_j0(ctx->J0);
649 
650     ret = esp_aes_process_dma_gcm(&ctx->aes_ctx, input, output, length, aad_head_desc, aad_len);
651 
652     aes_hal_gcm_read_tag(tag, tag_len);
653 
654     esp_aes_release_hardware();
655 
656     return ( ret );
657 }
658 
659 
esp_aes_gcm_auth_decrypt(esp_gcm_context * ctx,size_t length,const unsigned char * iv,size_t iv_len,const unsigned char * aad,size_t aad_len,const unsigned char * tag,size_t tag_len,const unsigned char * input,unsigned char * output)660 int esp_aes_gcm_auth_decrypt( esp_gcm_context *ctx,
661                               size_t length,
662                               const unsigned char *iv,
663                               size_t iv_len,
664                               const unsigned char *aad,
665                               size_t aad_len,
666                               const unsigned char *tag,
667                               size_t tag_len,
668                               const unsigned char *input,
669                               unsigned char *output )
670 {
671     int ret;
672     unsigned char check_tag[16];
673     size_t i;
674     int diff;
675 
676     if ( ( ret = esp_aes_gcm_crypt_and_tag( ctx, ESP_AES_DECRYPT, length,
677                                             iv, iv_len, aad, aad_len,
678                                             input, output, tag_len, check_tag ) ) != 0 ) {
679         return ( ret );
680     }
681 
682     /* Check tag in "constant-time" */
683     for ( diff = 0, i = 0; i < tag_len; i++ ) {
684         diff |= tag[i] ^ check_tag[i];
685     }
686 
687     if ( diff != 0 ) {
688         bzero( output, length );
689         return ( MBEDTLS_ERR_GCM_AUTH_FAILED );
690     }
691 
692     return ( 0 );
693 }
694 
695 #endif //SOC_AES_SUPPORT_GCM
696