1 /*
2 *  FIPS-197 compliant AES implementation
3 *
4 *  Copyright The Mbed TLS Contributors
5 *  Copyright (C) 2021, STMicroelectronics, All Rights Reserved
6 *  SPDX-License-Identifier: Apache-2.0
7 *
8 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
9 *  not use this file except in compliance with the License.
10 *  You may obtain a copy of the License at
11 *
12 *  http://www.apache.org/licenses/LICENSE-2.0
13 *
14 *  Unless required by applicable law or agreed to in writing, software
15 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 *  See the License for the specific language governing permissions and
18 *  limitations under the License.
19 *
20 *  This file implements ST AES HW services based on API from mbed TLS
21 *
22 *  The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
23 *
24 *  http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
25 *  http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
26 */
27 
28 
29 /* Includes ------------------------------------------------------------------*/
30 #include "mbedtls/aes.h"
31 
32 #if defined(MBEDTLS_AES_C)
33 #if defined(MBEDTLS_AES_ALT)
34 #include <string.h>
35 #include "mbedtls/platform.h"
36 #include "mbedtls/platform_util.h"
37 #include "mbedtls/error.h"
38 
39 /* Parameter validation macros based on platform_util.h */
40 #define AES_VALIDATE_RET( cond )    \
41     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_AES_BAD_INPUT_DATA )
42 #define AES_VALIDATE( cond )        \
43     MBEDTLS_INTERNAL_VALIDATE( cond )
44 
45 /* Private typedef -----------------------------------------------------------*/
46 /* Private define ------------------------------------------------------------*/
47 #define ST_AES_TIMEOUT     0xFFU   /* 255 ms timeout for the crypto processor */
48 #define ST_AES_NO_ALGO     0xFFFFU /* any algo is programmed */
49 
50 /* Private macro -------------------------------------------------------------*/
51 #define SWAP_B8_TO_B32(b32,b8,i)                         \
52 {                                                        \
53   (b32) = ( (uint32_t) (b8)[(i) + 3]       )             \
54         | ( (uint32_t) (b8)[(i) + 2] <<  8 )             \
55         | ( (uint32_t) (b8)[(i) + 1] << 16 )             \
56         | ( (uint32_t) (b8)[(i)    ] << 24 );            \
57 }
58 
59 #define SWAP_B32_TO_B8(b32,b8,i)                                 \
60 {                                                                \
61   (b8)[(i) + 3] = (unsigned char) ( ( (b32)       ) & 0xFF );    \
62   (b8)[(i) + 2] = (unsigned char) ( ( (b32) >>  8 ) & 0xFF );    \
63   (b8)[(i) + 1] = (unsigned char) ( ( (b32) >> 16 ) & 0xFF );    \
64   (b8)[(i)    ] = (unsigned char) ( ( (b32) >> 24 ) & 0xFF );    \
65 }
66 
67 /* Private variables ---------------------------------------------------------*/
68 /* Private function prototypes -----------------------------------------------*/
69 /* Private functions ---------------------------------------------------------*/
70 
aes_set_key(mbedtls_aes_context * ctx,const unsigned char * key,unsigned int keybits)71 static int aes_set_key(mbedtls_aes_context *ctx,
72                        const unsigned char *key,
73                        unsigned int keybits)
74 {
75     AES_VALIDATE_RET( ctx != NULL );
76 
77     switch (keybits) {
78 #if defined(GENERATOR_HW_CRYPTO_DPA_SUPPORTED) && defined(HW_CRYPTO_DPA_AES)
79         case 0:
80             /* implicit request for using HUK */
81             break;
82 #endif
83         case 128:
84             ctx->hcryp_aes.Init.KeySize = CRYP_KEYSIZE_128B;;
85 
86             SWAP_B8_TO_B32(ctx->aes_key[0],key,0);
87             SWAP_B8_TO_B32(ctx->aes_key[1],key,4);
88             SWAP_B8_TO_B32(ctx->aes_key[2],key,8);
89             SWAP_B8_TO_B32(ctx->aes_key[3],key,12);
90             break;
91 
92         case 192:
93             return (MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED);
94 
95         case 256:
96             ctx->hcryp_aes.Init.KeySize = CRYP_KEYSIZE_256B;
97 
98             SWAP_B8_TO_B32(ctx->aes_key[0],key,0);
99             SWAP_B8_TO_B32(ctx->aes_key[1],key,4);
100             SWAP_B8_TO_B32(ctx->aes_key[2],key,8);
101             SWAP_B8_TO_B32(ctx->aes_key[3],key,12);
102             SWAP_B8_TO_B32(ctx->aes_key[4],key,16);
103             SWAP_B8_TO_B32(ctx->aes_key[5],key,20);
104             SWAP_B8_TO_B32(ctx->aes_key[6],key,24);
105             SWAP_B8_TO_B32(ctx->aes_key[7],key,28);
106             break;
107 
108         default :
109             return (MBEDTLS_ERR_AES_INVALID_KEY_LENGTH);
110     }
111 #if defined(GENERATOR_HW_CRYPTO_DPA_SUPPORTED) && defined(HW_CRYPTO_DPA_AES)
112     ctx->hcryp_aes.Instance = SAES;
113 #else
114     ctx->hcryp_aes.Instance = AES;
115 #endif
116 #if defined(STM32L5)
117     ctx->hcryp_aes.Init.DataType = CRYP_DATATYPE_8B;
118 #else
119     ctx->hcryp_aes.Init.DataType = CRYP_BYTE_SWAP;
120 #endif
121     ctx->hcryp_aes.Init.DataWidthUnit = CRYP_DATAWIDTHUNIT_BYTE;
122     ctx->hcryp_aes.Init.pKey = ctx->aes_key;
123 
124 #if defined(GENERATOR_HW_CRYPTO_DPA_SUPPORTED) && defined(HW_CRYPTO_DPA_AES)
125     if ( 0 == keybits )
126     {
127         ctx->hcryp_aes.Init.KeyMode = CRYP_KEYMODE_NORMAL;
128         ctx->hcryp_aes.Init.KeyProtection = CRYP_KEYSEL_HW;
129     }
130     else
131     {
132         ctx->hcryp_aes.Init.KeyMode = CRYP_KEYMODE_NORMAL;
133         ctx->hcryp_aes.Init.KeyProtection = CRYP_KEYSEL_NORMAL;
134     }
135 #endif
136 
137     /* Initializes the CRYP peripheral */
138     if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) {
139         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
140     }
141 
142 #if defined(GENERATOR_HW_CRYPTO_DPA_SUPPORTED) && defined(HW_CRYPTO_DPA_AES)
143     /* Enable SAES clock */
144     __HAL_RCC_SAES_CLK_ENABLE();
145 #else
146     /* Enable AES clock */
147     __HAL_RCC_AES_CLK_ENABLE();
148 #endif
149 
150     if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) {
151         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
152     }
153 
154     /* allow multi-instance of CRYP use: save context for CRYP HW module CR */
155     ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR;
156 
157     return (0);
158 }
159 
160 /* Implementation that should never be optimized out by the compiler */
mbedtls_zeroize(void * v,size_t n)161 static void mbedtls_zeroize(void *v, size_t n)
162 {
163     volatile unsigned char *p = (unsigned char *)v;
164     while (n--) {
165         *p++ = 0;
166     }
167 }
168 
mbedtls_aes_init(mbedtls_aes_context * ctx)169 void mbedtls_aes_init(mbedtls_aes_context *ctx)
170 {
171     AES_VALIDATE( ctx != NULL );
172 
173     memset(ctx, 0, sizeof(mbedtls_aes_context));
174 
175 #if defined(STM32L5)
176 #else
177     ctx->hcryp_aes.Init.Algorithm  = ST_AES_NO_ALGO;
178 #endif
179 }
180 
181 
mbedtls_aes_free(mbedtls_aes_context * ctx)182 void mbedtls_aes_free(mbedtls_aes_context *ctx)
183 {
184     if (ctx == NULL) {
185         return;
186     }
187 
188     mbedtls_zeroize(ctx, sizeof(mbedtls_aes_context));
189 }
190 
191 #if defined(MBEDTLS_CIPHER_MODE_XTS)
mbedtls_aes_xts_init(mbedtls_aes_xts_context * ctx)192 void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx )
193 {
194     AES_VALIDATE( ctx != NULL );
195 
196     mbedtls_aes_init( &ctx->crypt );
197     mbedtls_aes_init( &ctx->tweak );
198 }
199 
mbedtls_aes_xts_free(mbedtls_aes_xts_context * ctx)200 void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx )
201 {
202     if( ctx == NULL )
203         return;
204 
205     mbedtls_aes_free( &ctx->crypt );
206     mbedtls_aes_free( &ctx->tweak );
207 }
208 #endif /* MBEDTLS_CIPHER_MODE_XTS */
209 
210 /*
211  * AES key schedule (encryption)
212  */
mbedtls_aes_setkey_enc(mbedtls_aes_context * ctx,const unsigned char * key,unsigned int keybits)213 int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key,
214                            unsigned int keybits)
215 {
216     return (aes_set_key(ctx, key, keybits));
217 }
218 
219 /*
220  * AES key schedule (decryption)
221  */
mbedtls_aes_setkey_dec(mbedtls_aes_context * ctx,const unsigned char * key,unsigned int keybits)222 int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key,
223                            unsigned int keybits)
224 {
225     return (aes_set_key(ctx, key, keybits));
226 }
227 
228 #if defined(MBEDTLS_CIPHER_MODE_XTS)
mbedtls_aes_xts_decode_keys(const unsigned char * key,unsigned int keybits,const unsigned char ** key1,unsigned int * key1bits,const unsigned char ** key2,unsigned int * key2bits)229 static int mbedtls_aes_xts_decode_keys( const unsigned char *key,
230                                         unsigned int keybits,
231                                         const unsigned char **key1,
232                                         unsigned int *key1bits,
233                                         const unsigned char **key2,
234                                         unsigned int *key2bits )
235 {
236     const unsigned int half_keybits = keybits / 2;
237     const unsigned int half_keybytes = half_keybits / 8;
238 
239     switch( keybits )
240     {
241         case 256: break;
242         case 512: break;
243         default : return( MBEDTLS_ERR_AES_INVALID_KEY_LENGTH );
244     }
245 
246     *key1bits = half_keybits;
247     *key2bits = half_keybits;
248     *key1 = &key[0];
249     *key2 = &key[half_keybytes];
250 
251     return ( 0 );
252 }
253 
mbedtls_aes_xts_setkey_enc(mbedtls_aes_xts_context * ctx,const unsigned char * key,unsigned int keybits)254 int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx,
255                                 const unsigned char *key,
256                                 unsigned int keybits)
257 {
258     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
259     const unsigned char *key1, *key2;
260     unsigned int key1bits, key2bits;
261 
262     AES_VALIDATE_RET( ctx != NULL );
263     AES_VALIDATE_RET( key != NULL );
264 
265     ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits,
266                                        &key2, &key2bits );
267     if( ret != 0 )
268         return( ret );
269 
270     /* Set the tweak key. Always set tweak key for the encryption mode. */
271     ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits );
272     if( ret != 0 )
273         return( ret );
274 
275     /* Set crypt key for encryption. */
276     return (mbedtls_aes_setkey_enc( &ctx->crypt, key1, key1bits ));
277 }
278 
mbedtls_aes_xts_setkey_dec(mbedtls_aes_xts_context * ctx,const unsigned char * key,unsigned int keybits)279 int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx,
280                                 const unsigned char *key,
281                                 unsigned int keybits)
282 {
283     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
284     const unsigned char *key1, *key2;
285     unsigned int key1bits, key2bits;
286 
287     AES_VALIDATE_RET( ctx != NULL );
288     AES_VALIDATE_RET( key != NULL );
289 
290     ret = mbedtls_aes_xts_decode_keys( key, keybits, &key1, &key1bits,
291                                        &key2, &key2bits );
292     if( ret != 0 )
293         return( ret );
294 
295     /* Set the tweak key. Always set tweak key for encryption. */
296     ret = mbedtls_aes_setkey_enc( &ctx->tweak, key2, key2bits );
297     if( ret != 0 )
298         return( ret );
299 
300     /* Set crypt key for decryption. */
301     return (mbedtls_aes_setkey_dec( &ctx->crypt, key1, key1bits ));
302 }
303 #endif /* MBEDTLS_CIPHER_MODE_XTS */
304 
305 /*
306  * AES-ECB block encryption/decryption
307  */
mbedtls_aes_crypt_ecb(mbedtls_aes_context * ctx,int mode,const unsigned char input[16],unsigned char output[16])308 int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx,
309                           int mode,
310                           const unsigned char input[16],
311                           unsigned char output[16])
312 {
313     int ret;
314 
315     AES_VALIDATE_RET( ctx != NULL );
316     AES_VALIDATE_RET( input != NULL );
317     AES_VALIDATE_RET( output != NULL );
318     AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT ||
319                       mode == MBEDTLS_AES_DECRYPT );
320 
321     /* allow multi-instance of CRYP use: restore context for CRYP hw module */
322     ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr;
323 
324     /* Set the Algo if not configured till now */
325     if (CRYP_AES_ECB != ctx->hcryp_aes.Init.Algorithm)
326     {
327         ctx->hcryp_aes.Init.Algorithm  = CRYP_AES_ECB;
328 
329         /* Configure the CRYP  */
330         if (HAL_CRYP_SetConfig(&ctx->hcryp_aes, &ctx->hcryp_aes.Init) != HAL_OK)
331             return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
332     }
333 
334     if (mode == MBEDTLS_AES_DECRYPT) { /* AES decryption */
335         ret = mbedtls_internal_aes_decrypt(ctx, input, output);
336         if( ret != 0 )
337             return (ret);
338     } else { /* AES encryption */
339         ret = mbedtls_internal_aes_encrypt(ctx, input, output);
340         if( ret != 0 )
341             return (ret);
342     }
343     /* allow multi-instance of CRYP use: save context for CRYP HW module CR */
344     ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR;
345 
346     return (0);
347 }
348 
349 #if defined(MBEDTLS_CIPHER_MODE_CBC)
350 /*
351  * AES-CBC buffer encryption/decryption
352  */
st_cbc_restore_context(mbedtls_aes_context * ctx)353 static int st_cbc_restore_context(mbedtls_aes_context *ctx)
354 {
355     /* allow multi-instance of CRYP use: restore context for CRYP hw module */
356     ctx->hcryp_aes.Instance->CR = ctx->ctx_save_cr;
357 
358     /* Re-initialize AES processor with proper parameters
359        and (re-)apply key and IV for multi context usecases */
360     if (HAL_CRYP_DeInit(&ctx->hcryp_aes) != HAL_OK) {
361         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
362     }
363 
364     if (HAL_CRYP_Init(&ctx->hcryp_aes) != HAL_OK) {
365         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
366     }
367     return (0);
368 }
369 
mbedtls_aes_crypt_cbc(mbedtls_aes_context * ctx,int mode,size_t length,unsigned char iv[16],const unsigned char * input,unsigned char * output)370 int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx,
371                           int mode,
372                           size_t length,
373                           unsigned char iv[16],
374                           const unsigned char *input,
375                           unsigned char *output)
376 {
377     __ALIGN_BEGIN static uint32_t iv_32B[4] __ALIGN_END;
378     int ret = 0;
379 
380     AES_VALIDATE_RET( ctx != NULL );
381     AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT ||
382                       mode == MBEDTLS_AES_DECRYPT );
383     AES_VALIDATE_RET( iv != NULL );
384     AES_VALIDATE_RET( input != NULL );
385     AES_VALIDATE_RET( output != NULL );
386 
387     if (length % 16) {
388         return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH);
389     }
390 
391     ret = st_cbc_restore_context(ctx);
392     if (ret != 0)
393         return (ret);
394 
395     /* Set the Algo if not configured till now */
396     if (CRYP_AES_CBC != ctx->hcryp_aes.Init.Algorithm)
397     {
398         ctx->hcryp_aes.Init.Algorithm  = CRYP_AES_CBC;
399     }
400 
401     /* Set IV with invert endianness */
402     SWAP_B8_TO_B32(iv_32B[0],iv,0);
403     SWAP_B8_TO_B32(iv_32B[1],iv,4);
404     SWAP_B8_TO_B32(iv_32B[2],iv,8);
405     SWAP_B8_TO_B32(iv_32B[3],iv,12);
406 
407     ctx->hcryp_aes.Init.pInitVect = iv_32B;
408 
409     /* reconfigure the CRYP */
410     if (HAL_CRYP_SetConfig(&ctx->hcryp_aes, &ctx->hcryp_aes.Init) != HAL_OK) {
411         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
412     }
413 
414     if (mode == MBEDTLS_AES_DECRYPT) {
415         if (HAL_CRYP_Decrypt(&ctx->hcryp_aes, (uint32_t *)input, length, (uint32_t *)output, ST_AES_TIMEOUT) != HAL_OK) {
416             return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
417         }
418 
419         /* Get IV vector for the next call */
420         SWAP_B32_TO_B8(ctx->hcryp_aes.Instance->IVR3,iv,0);
421         SWAP_B32_TO_B8(ctx->hcryp_aes.Instance->IVR2,iv,4);
422         SWAP_B32_TO_B8(ctx->hcryp_aes.Instance->IVR1,iv,8);
423         SWAP_B32_TO_B8(ctx->hcryp_aes.Instance->IVR0,iv,12);
424 
425     } else {
426         if (HAL_CRYP_Encrypt(&ctx->hcryp_aes, (uint32_t *)input, length, (uint32_t *)output, ST_AES_TIMEOUT) != HAL_OK) {
427             return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
428         }
429 
430         /* current output is the IV vector for the next call */
431         memcpy(iv, &output[length - 16], 16);
432     }
433 
434     /* Save the internal IV vector for multi context purpose */
435     ctx->ctx_save_cr = ctx->hcryp_aes.Instance->CR; // save here before overwritten
436     ctx->hcryp_aes.Instance->CR &= ~AES_CR_EN;
437 
438     return (0);
439 }
440 #endif /* MBEDTLS_CIPHER_MODE_CBC */
441 
442 #if defined(MBEDTLS_CIPHER_MODE_XTS)
443 
444 /* Endianness with 64 bits values */
445 #ifndef GET_UINT64_LE
446 #define GET_UINT64_LE(n,b,i)                            \
447 {                                                       \
448     (n) = ( (uint64_t) (b)[(i) + 7] << 56 )             \
449         | ( (uint64_t) (b)[(i) + 6] << 48 )             \
450         | ( (uint64_t) (b)[(i) + 5] << 40 )             \
451         | ( (uint64_t) (b)[(i) + 4] << 32 )             \
452         | ( (uint64_t) (b)[(i) + 3] << 24 )             \
453         | ( (uint64_t) (b)[(i) + 2] << 16 )             \
454         | ( (uint64_t) (b)[(i) + 1] <<  8 )             \
455         | ( (uint64_t) (b)[(i)    ]       );            \
456 }
457 #endif
458 
459 #ifndef PUT_UINT64_LE
460 #define PUT_UINT64_LE(n,b,i)                            \
461 {                                                       \
462     (b)[(i) + 7] = (unsigned char) ( (n) >> 56 );       \
463     (b)[(i) + 6] = (unsigned char) ( (n) >> 48 );       \
464     (b)[(i) + 5] = (unsigned char) ( (n) >> 40 );       \
465     (b)[(i) + 4] = (unsigned char) ( (n) >> 32 );       \
466     (b)[(i) + 3] = (unsigned char) ( (n) >> 24 );       \
467     (b)[(i) + 2] = (unsigned char) ( (n) >> 16 );       \
468     (b)[(i) + 1] = (unsigned char) ( (n) >>  8 );       \
469     (b)[(i)    ] = (unsigned char) ( (n)       );       \
470 }
471 #endif
472 
473 /*
474  * GF(2^128) multiplication function
475  *
476  * This function multiplies a field element by x in the polynomial field
477  * representation. It uses 64-bit word operations to gain speed but compensates
478  * for machine endianness and hence works correctly on both big and little
479  * endian machines.
480  */
mbedtls_gf128mul_x_ble(unsigned char r[16],const unsigned char x[16])481 static void mbedtls_gf128mul_x_ble( unsigned char r[16],
482                                     const unsigned char x[16] )
483 {
484     uint64_t a, b, ra, rb;
485 
486     GET_UINT64_LE( a, x, 0 );
487     GET_UINT64_LE( b, x, 8 );
488 
489     ra = ( a << 1 )  ^ 0x0087 >> ( 8 - ( ( b >> 63 ) << 3 ) );
490     rb = ( a >> 63 ) | ( b << 1 );
491 
492     PUT_UINT64_LE( ra, r, 0 );
493     PUT_UINT64_LE( rb, r, 8 );
494 }
495 
496 /*
497  * AES-XTS buffer encryption/decryption
498  */
mbedtls_aes_crypt_xts(mbedtls_aes_xts_context * ctx,int mode,size_t length,const unsigned char data_unit[16],const unsigned char * input,unsigned char * output)499 int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx,
500                            int mode,
501                            size_t length,
502                            const unsigned char data_unit[16],
503                            const unsigned char *input,
504                            unsigned char *output )
505 {
506     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
507     size_t blocks = length / 16;
508     size_t leftover = length % 16;
509     unsigned char tweak[16];
510     unsigned char prev_tweak[16];
511     unsigned char tmp[16];
512 
513     AES_VALIDATE_RET( ctx != NULL );
514     AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT ||
515                       mode == MBEDTLS_AES_DECRYPT );
516     AES_VALIDATE_RET( data_unit != NULL );
517     AES_VALIDATE_RET( input != NULL );
518     AES_VALIDATE_RET( output != NULL );
519 
520     /* Data units must be at least 16 bytes long. */
521     if( length < 16 )
522         return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH);
523 
524     /* NIST SP 800-38E disallows data units larger than 2**20 blocks. */
525     if( length > ( 1 << 20 ) * 16 )
526         return (MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH);
527 
528     /* Compute the tweak. */
529     ret = mbedtls_aes_crypt_ecb( &ctx->tweak, MBEDTLS_AES_ENCRYPT,
530                                  data_unit, tweak );
531     if( ret != 0 )
532         return( ret );
533 
534     while( blocks-- )
535     {
536         size_t i;
537 
538         if( leftover && ( mode == MBEDTLS_AES_DECRYPT ) && blocks == 0 )
539         {
540             /* We are on the last block in a decrypt operation that has
541              * leftover bytes, so we need to use the next tweak for this block,
542              * and this tweak for the lefover bytes. Save the current tweak for
543              * the leftovers and then update the current tweak for use on this,
544              * the last full block. */
545             memcpy( prev_tweak, tweak, sizeof( tweak ) );
546             mbedtls_gf128mul_x_ble( tweak, tweak );
547         }
548 
549         for( i = 0; i < 16; i++ )
550             tmp[i] = input[i] ^ tweak[i];
551 
552         ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );
553         if( ret != 0 )
554             return( ret );
555 
556         for( i = 0; i < 16; i++ )
557             output[i] = tmp[i] ^ tweak[i];
558 
559         /* Update the tweak for the next block. */
560         mbedtls_gf128mul_x_ble( tweak, tweak );
561 
562         output += 16;
563         input += 16;
564     }
565 
566     if( leftover )
567     {
568         /* If we are on the leftover bytes in a decrypt operation, we need to
569          * use the previous tweak for these bytes (as saved in prev_tweak). */
570         unsigned char *t = mode == MBEDTLS_AES_DECRYPT ? prev_tweak : tweak;
571 
572         /* We are now on the final part of the data unit, which doesn't divide
573          * evenly by 16. It's time for ciphertext stealing. */
574         size_t i;
575         unsigned char *prev_output = output - 16;
576 
577         /* Copy ciphertext bytes from the previous block to our output for each
578          * byte of cyphertext we won't steal. At the same time, copy the
579          * remainder of the input for this final round (since the loop bounds
580          * are the same). */
581         for( i = 0; i < leftover; i++ )
582         {
583             output[i] = prev_output[i];
584             tmp[i] = input[i] ^ t[i];
585         }
586 
587         /* Copy ciphertext bytes from the previous block for input in this
588          * round. */
589         for( ; i < 16; i++ )
590             tmp[i] = prev_output[i] ^ t[i];
591 
592         ret = mbedtls_aes_crypt_ecb( &ctx->crypt, mode, tmp, tmp );
593         if( ret != 0 )
594             return (ret);
595 
596         /* Write the result back to the previous block, overriding the previous
597          * output we copied. */
598         for( i = 0; i < 16; i++ )
599             prev_output[i] = tmp[i] ^ t[i];
600     }
601 
602     return( 0 );
603 }
604 #endif /* MBEDTLS_CIPHER_MODE_XTS */
605 
606 #if defined(MBEDTLS_CIPHER_MODE_CFB)
607 /*
608  * AES-CFB128 buffer encryption/decryption
609  */
mbedtls_aes_crypt_cfb128(mbedtls_aes_context * ctx,int mode,size_t length,size_t * iv_off,unsigned char iv[16],const unsigned char * input,unsigned char * output)610 int mbedtls_aes_crypt_cfb128(mbedtls_aes_context *ctx,
611                              int mode,
612                              size_t length,
613                              size_t *iv_off,
614                              unsigned char iv[16],
615                              const unsigned char *input,
616                              unsigned char *output)
617 {
618     int ret;
619     int c;
620     size_t n;
621 
622     AES_VALIDATE_RET( ctx != NULL );
623     AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT ||
624                       mode == MBEDTLS_AES_DECRYPT );
625     AES_VALIDATE_RET( iv_off != NULL );
626     AES_VALIDATE_RET( iv != NULL );
627     AES_VALIDATE_RET( input != NULL );
628     AES_VALIDATE_RET( output != NULL );
629 
630     n = *iv_off;
631 
632     if (mode == MBEDTLS_AES_DECRYPT) {
633         while (length--) {
634             if (n == 0) {
635                 ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv);
636                 if (ret != 0)
637                     return (ret);
638             }
639 
640             c = *input++;
641             *output++ = (unsigned char)(c ^ iv[n]);
642             iv[n] = (unsigned char) c;
643 
644             n = (n + 1) & 0x0F;
645         }
646     } else {
647         while (length--) {
648             if (n == 0) {
649                 ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv);
650                 if (ret != 0)
651                     return (ret);
652             }
653 
654             iv[n] = *output++ = (unsigned char)(iv[n] ^ *input++);
655 
656             n = (n + 1) & 0x0F;
657         }
658     }
659 
660     *iv_off = n;
661 
662     return (0);
663 }
664 
665 /*
666  * AES-CFB8 buffer encryption/decryption
667  */
mbedtls_aes_crypt_cfb8(mbedtls_aes_context * ctx,int mode,size_t length,unsigned char iv[16],const unsigned char * input,unsigned char * output)668 int mbedtls_aes_crypt_cfb8(mbedtls_aes_context *ctx,
669                            int mode,
670                            size_t length,
671                            unsigned char iv[16],
672                            const unsigned char *input,
673                            unsigned char *output)
674 {
675     int ret;
676     unsigned char c;
677     unsigned char ov[17];
678 
679     AES_VALIDATE_RET( ctx != NULL );
680     AES_VALIDATE_RET( mode == MBEDTLS_AES_ENCRYPT ||
681                       mode == MBEDTLS_AES_DECRYPT );
682     AES_VALIDATE_RET( iv != NULL );
683     AES_VALIDATE_RET( input != NULL );
684     AES_VALIDATE_RET( output != NULL );
685 
686     while (length--) {
687         memcpy(ov, iv, 16);
688         ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv);
689         if (ret != 0)
690             return (ret);
691 
692         if (mode == MBEDTLS_AES_DECRYPT) {
693             ov[16] = *input;
694         }
695 
696         c = *output++ = (unsigned char)(iv[0] ^ *input++);
697 
698         if (mode == MBEDTLS_AES_ENCRYPT) {
699             ov[16] = c;
700         }
701 
702         memcpy(iv, ov + 1, 16);
703     }
704 
705     return (0);
706 }
707 
708 #endif /*MBEDTLS_CIPHER_MODE_CFB */
709 
710 #if defined(MBEDTLS_CIPHER_MODE_OFB)
711 /*
712  * AES-OFB (Output Feedback Mode) buffer encryption/decryption
713  */
mbedtls_aes_crypt_ofb(mbedtls_aes_context * ctx,size_t length,size_t * iv_off,unsigned char iv[16],const unsigned char * input,unsigned char * output)714 int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx,
715                            size_t length,
716                            size_t *iv_off,
717                            unsigned char iv[16],
718                            const unsigned char *input,
719                            unsigned char *output )
720 {
721     int ret = 0;
722     size_t n;
723 
724     AES_VALIDATE_RET( ctx != NULL );
725     AES_VALIDATE_RET( iv_off != NULL );
726     AES_VALIDATE_RET( iv != NULL );
727     AES_VALIDATE_RET( input != NULL );
728     AES_VALIDATE_RET( output != NULL );
729 
730     n = *iv_off;
731 
732     if( n > 15 )
733         return( MBEDTLS_ERR_AES_BAD_INPUT_DATA );
734 
735     while( length-- )
736     {
737         if( n == 0 )
738         {
739             ret = mbedtls_aes_crypt_ecb( ctx, MBEDTLS_AES_ENCRYPT, iv, iv );
740             if( ret != 0 )
741                 goto exit;
742         }
743         *output++ =  *input++ ^ iv[n];
744 
745         n = ( n + 1 ) & 0x0F;
746     }
747 
748     *iv_off = n;
749 
750 exit:
751     return( ret );
752 }
753 #endif /* MBEDTLS_CIPHER_MODE_OFB */
754 
755 #if defined(MBEDTLS_CIPHER_MODE_CTR)
756 /*
757  * AES-CTR buffer encryption/decryption
758  */
mbedtls_aes_crypt_ctr(mbedtls_aes_context * ctx,size_t length,size_t * nc_off,unsigned char nonce_counter[16],unsigned char stream_block[16],const unsigned char * input,unsigned char * output)759 int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx,
760                           size_t length,
761                           size_t *nc_off,
762                           unsigned char nonce_counter[16],
763                           unsigned char stream_block[16],
764                           const unsigned char *input,
765                           unsigned char *output)
766 {
767     int c, i;
768     size_t n;
769 
770     AES_VALIDATE_RET( ctx != NULL );
771     AES_VALIDATE_RET( nc_off != NULL );
772     AES_VALIDATE_RET( nonce_counter != NULL );
773     AES_VALIDATE_RET( stream_block != NULL );
774     AES_VALIDATE_RET( input != NULL );
775     AES_VALIDATE_RET( output != NULL );
776 
777     n = *nc_off;
778 
779     while (length--) {
780         if (n == 0) {
781             if (mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block) != 0) {
782                 return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
783             }
784 
785             for (i = 16; i > 0; i--)
786                 if (++nonce_counter[i - 1] != 0) {
787                     break;
788                 }
789         }
790         c = *input++;
791         *output++ = (unsigned char)(c ^ stream_block[n]);
792 
793         n = (n + 1) & 0x0F;
794     }
795 
796     *nc_off = n;
797 
798     return (0);
799 }
800 #endif /* MBEDTLS_CIPHER_MODE_CTR */
801 
mbedtls_internal_aes_encrypt(mbedtls_aes_context * ctx,const unsigned char input[16],unsigned char output[16])802 int mbedtls_internal_aes_encrypt(mbedtls_aes_context *ctx,
803                                  const unsigned char input[16],
804                                  unsigned char output[16])
805 {
806 
807     if (HAL_CRYP_Encrypt(&ctx->hcryp_aes, (uint32_t *)input, 16, (uint32_t *)output, ST_AES_TIMEOUT) != HAL_OK) {
808         return (MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED);
809     }
810     return (0);
811 
812 }
813 
mbedtls_internal_aes_decrypt(mbedtls_aes_context * ctx,const unsigned char input[16],unsigned char output[16])814 int mbedtls_internal_aes_decrypt(mbedtls_aes_context *ctx,
815                                  const unsigned char input[16],
816                                  unsigned char output[16])
817 {
818     if (HAL_CRYP_Decrypt(&ctx->hcryp_aes, (uint32_t *)input, 16, (uint32_t *)output, ST_AES_TIMEOUT) != HAL_OK) {
819         return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
820     }
821     return (0);
822 }
823 
824 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
mbedtls_aes_encrypt(mbedtls_aes_context * ctx,const unsigned char input[16],unsigned char output[16])825 void mbedtls_aes_encrypt(mbedtls_aes_context *ctx,
826                          const unsigned char input[16],
827                          unsigned char output[16])
828 {
829     mbedtls_internal_aes_encrypt(ctx, input, output);
830 }
831 
mbedtls_aes_decrypt(mbedtls_aes_context * ctx,const unsigned char input[16],unsigned char output[16])832 void mbedtls_aes_decrypt(mbedtls_aes_context *ctx,
833                          const unsigned char input[16],
834                          unsigned char output[16])
835 {
836     mbedtls_internal_aes_decrypt(ctx, input, output);
837 }
838 #endif /* MBEDTLS_DEPRECATED_REMOVED */
839 
840 #if defined(HW_CRYPTO_DPA_AES)
841 
mbedtls_aes_unwrap(mbedtls_aes_context * ctx,uint32_t * Encryptedkey,uint32_t * input,size_t length,uint32_t * output)842 int mbedtls_aes_unwrap(mbedtls_aes_context *ctx,
843                        uint32_t *Encryptedkey,
844                        uint32_t *input,
845                        size_t length,
846                        uint32_t *output)
847 {
848     AES_VALIDATE_RET( ctx != NULL );
849     AES_VALIDATE_RET( Encryptedkey != NULL );
850     AES_VALIDATE_RET( input != NULL );
851 
852     ctx->hcryp_aes.Init.KeyMode = CRYP_KEYMODE_WRAPPED;
853     ctx->hcryp_aes.Init.KeyProtection = CRYP_KEYPROT_ENABLE;
854     ctx->hcryp_aes.Init.Algorithm = CRYP_AES_ECB;
855     ctx->hcryp_aes.Init.DataType = CRYP_NO_SWAP;
856     ctx->hcryp_aes.Init.KeySize = CRYP_KEYSIZE_256B;
857     ctx->hcryp_aes.Init.DataWidthUnit = CRYP_DATAWIDTHUNIT_WORD;
858 
859     /* reconfigure the CRYP */
860     if ( HAL_CRYP_SetConfig( &ctx->hcryp_aes, &ctx->hcryp_aes.Init ) != HAL_OK )
861     {
862         return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
863     }
864 
865     /* User key decryption and loading in : SAES_KEYRx registers */
866     if (HAL_CRYPEx_UnwrapKey(&ctx->hcryp_aes,
867                              Encryptedkey,
868                              ST_AES_TIMEOUT) != HAL_OK)
869   {
870       return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
871   }
872 
873   /* Secure AES ECB Encryption */
874   if (HAL_CRYP_Encrypt(&ctx->hcryp_aes,
875                        input,
876                        length,
877                        output,
878                        ST_AES_TIMEOUT) != HAL_OK)
879   {
880       return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
881   }
882 
883   return (0);
884 }
885 #endif /* HW_CRYPTO_DPA_AES */
886 #endif /* MBEDTLS_AES_ALT */
887 #endif /* MBEDTLS_AES_C */
888