1 /**
2  * \file cipher.c
3  *
4  * \brief Generic cipher wrapper for mbed TLS
5  *
6  * \author Adriaan de Jong <dejong@fox-it.com>
7  *
8  *  Copyright The Mbed TLS Contributors
9  *  SPDX-License-Identifier: Apache-2.0
10  *
11  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
12  *  not use this file except in compliance with the License.
13  *  You may obtain a copy of the License at
14  *
15  *  http://www.apache.org/licenses/LICENSE-2.0
16  *
17  *  Unless required by applicable law or agreed to in writing, software
18  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  *  See the License for the specific language governing permissions and
21  *  limitations under the License.
22  */
23 
24 #include "common.h"
25 
26 #if defined(MBEDTLS_CIPHER_C)
27 
28 #include "mbedtls/cipher.h"
29 #include "mbedtls/cipher_internal.h"
30 #include "mbedtls/platform_util.h"
31 #include "mbedtls/error.h"
32 #include "mbedtls/constant_time.h"
33 
34 #include <stdlib.h>
35 #include <string.h>
36 
37 #if defined(MBEDTLS_CHACHAPOLY_C)
38 #include "mbedtls/chachapoly.h"
39 #endif
40 
41 #if defined(MBEDTLS_GCM_C)
42 #include "mbedtls/gcm.h"
43 #endif
44 
45 #if defined(MBEDTLS_CCM_C)
46 #include "mbedtls/ccm.h"
47 #endif
48 
49 #if defined(MBEDTLS_CHACHA20_C)
50 #include "mbedtls/chacha20.h"
51 #endif
52 
53 #if defined(MBEDTLS_CMAC_C)
54 #include "mbedtls/cmac.h"
55 #endif
56 
57 #if defined(MBEDTLS_USE_PSA_CRYPTO)
58 #include "psa/crypto.h"
59 #include "mbedtls/psa_util.h"
60 #endif /* MBEDTLS_USE_PSA_CRYPTO */
61 
62 #if defined(MBEDTLS_NIST_KW_C)
63 #include "mbedtls/nist_kw.h"
64 #endif
65 
66 #if defined(MBEDTLS_PLATFORM_C)
67 #include "mbedtls/platform.h"
68 #else
69 #define mbedtls_calloc calloc
70 #define mbedtls_free   free
71 #endif
72 
73 #define CIPHER_VALIDATE_RET( cond )    \
74     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA )
75 #define CIPHER_VALIDATE( cond )        \
76     MBEDTLS_INTERNAL_VALIDATE( cond )
77 
78 static int supported_init = 0;
79 
mbedtls_cipher_list(void)80 const int *mbedtls_cipher_list( void )
81 {
82     const mbedtls_cipher_definition_t *def;
83     int *type;
84 
85     if( ! supported_init )
86     {
87         def = mbedtls_cipher_definitions;
88         type = mbedtls_cipher_supported;
89 
90         while( def->type != 0 )
91             *type++ = (*def++).type;
92 
93         *type = 0;
94 
95         supported_init = 1;
96     }
97 
98     return( mbedtls_cipher_supported );
99 }
100 
mbedtls_cipher_info_from_type(const mbedtls_cipher_type_t cipher_type)101 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type(
102     const mbedtls_cipher_type_t cipher_type )
103 {
104     const mbedtls_cipher_definition_t *def;
105 
106     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
107         if( def->type == cipher_type )
108             return( def->info );
109 
110     return( NULL );
111 }
112 
mbedtls_cipher_info_from_string(const char * cipher_name)113 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string(
114     const char *cipher_name )
115 {
116     const mbedtls_cipher_definition_t *def;
117 
118     if( NULL == cipher_name )
119         return( NULL );
120 
121     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
122         if( !  strcmp( def->info->name, cipher_name ) )
123             return( def->info );
124 
125     return( NULL );
126 }
127 
mbedtls_cipher_info_from_values(const mbedtls_cipher_id_t cipher_id,int key_bitlen,const mbedtls_cipher_mode_t mode)128 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values(
129     const mbedtls_cipher_id_t cipher_id,
130     int key_bitlen,
131     const mbedtls_cipher_mode_t mode )
132 {
133     const mbedtls_cipher_definition_t *def;
134 
135     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
136         if( def->info->base->cipher == cipher_id &&
137             def->info->key_bitlen == (unsigned) key_bitlen &&
138             def->info->mode == mode )
139             return( def->info );
140 
141     return( NULL );
142 }
143 
mbedtls_cipher_init(mbedtls_cipher_context_t * ctx)144 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx )
145 {
146     CIPHER_VALIDATE( ctx != NULL );
147     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
148 }
149 
mbedtls_cipher_free(mbedtls_cipher_context_t * ctx)150 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )
151 {
152     if( ctx == NULL )
153         return;
154 
155 #if defined(MBEDTLS_USE_PSA_CRYPTO)
156     if( ctx->psa_enabled == 1 )
157     {
158         if( ctx->cipher_ctx != NULL )
159         {
160             mbedtls_cipher_context_psa * const cipher_psa =
161                 (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
162 
163             if( cipher_psa->slot_state == MBEDTLS_CIPHER_PSA_KEY_OWNED )
164             {
165                 /* xxx_free() doesn't allow to return failures. */
166                 (void) psa_destroy_key( cipher_psa->slot );
167             }
168 
169             mbedtls_platform_zeroize( cipher_psa, sizeof( *cipher_psa ) );
170             mbedtls_free( cipher_psa );
171         }
172 
173         mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
174         return;
175     }
176 #endif /* MBEDTLS_USE_PSA_CRYPTO */
177 
178 #if defined(MBEDTLS_CMAC_C)
179     if( ctx->cmac_ctx )
180     {
181        mbedtls_platform_zeroize( ctx->cmac_ctx,
182                                  sizeof( mbedtls_cmac_context_t ) );
183        mbedtls_free( ctx->cmac_ctx );
184     }
185 #endif
186 
187     if( ctx->cipher_ctx )
188         ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx );
189 
190     mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
191 }
192 
mbedtls_cipher_setup(mbedtls_cipher_context_t * ctx,const mbedtls_cipher_info_t * cipher_info)193 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx,
194                           const mbedtls_cipher_info_t *cipher_info )
195 {
196     CIPHER_VALIDATE_RET( ctx != NULL );
197     if( cipher_info == NULL )
198         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
199 
200     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
201 
202     if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) )
203         return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
204 
205     ctx->cipher_info = cipher_info;
206 
207 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
208     /*
209      * Ignore possible errors caused by a cipher mode that doesn't use padding
210      */
211 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
212     (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_PKCS7 );
213 #else
214     (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_NONE );
215 #endif
216 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
217 
218     return( 0 );
219 }
220 
221 #if defined(MBEDTLS_USE_PSA_CRYPTO)
mbedtls_cipher_setup_psa(mbedtls_cipher_context_t * ctx,const mbedtls_cipher_info_t * cipher_info,size_t taglen)222 int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx,
223                               const mbedtls_cipher_info_t *cipher_info,
224                               size_t taglen )
225 {
226     psa_algorithm_t alg;
227     mbedtls_cipher_context_psa *cipher_psa;
228 
229     if( NULL == cipher_info || NULL == ctx )
230         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
231 
232     /* Check that the underlying cipher mode and cipher type are
233      * supported by the underlying PSA Crypto implementation. */
234     alg = mbedtls_psa_translate_cipher_mode( cipher_info->mode, taglen );
235     if( alg == 0 )
236         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
237     if( mbedtls_psa_translate_cipher_type( cipher_info->type ) == 0 )
238         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
239 
240     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
241 
242     cipher_psa = mbedtls_calloc( 1, sizeof(mbedtls_cipher_context_psa ) );
243     if( cipher_psa == NULL )
244         return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
245     cipher_psa->alg  = alg;
246     ctx->cipher_ctx  = cipher_psa;
247     ctx->cipher_info = cipher_info;
248     ctx->psa_enabled = 1;
249     return( 0 );
250 }
251 #endif /* MBEDTLS_USE_PSA_CRYPTO */
252 
mbedtls_cipher_setkey(mbedtls_cipher_context_t * ctx,const unsigned char * key,int key_bitlen,const mbedtls_operation_t operation)253 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx,
254                            const unsigned char *key,
255                            int key_bitlen,
256                            const mbedtls_operation_t operation )
257 {
258     CIPHER_VALIDATE_RET( ctx != NULL );
259     CIPHER_VALIDATE_RET( key != NULL );
260     CIPHER_VALIDATE_RET( operation == MBEDTLS_ENCRYPT ||
261                          operation == MBEDTLS_DECRYPT );
262     if( ctx->cipher_info == NULL )
263         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
264 
265 #if defined(MBEDTLS_USE_PSA_CRYPTO)
266     if( ctx->psa_enabled == 1 )
267     {
268         mbedtls_cipher_context_psa * const cipher_psa =
269             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
270 
271         size_t const key_bytelen = ( (size_t) key_bitlen + 7 ) / 8;
272 
273         psa_status_t status;
274         psa_key_type_t key_type;
275         psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
276 
277         /* PSA Crypto API only accepts byte-aligned keys. */
278         if( key_bitlen % 8 != 0 )
279             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
280 
281         /* Don't allow keys to be set multiple times. */
282         if( cipher_psa->slot_state != MBEDTLS_CIPHER_PSA_KEY_UNSET )
283             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
284 
285         key_type = mbedtls_psa_translate_cipher_type(
286             ctx->cipher_info->type );
287         if( key_type == 0 )
288             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
289         psa_set_key_type( &attributes, key_type );
290 
291         /* Mbed TLS' cipher layer doesn't enforce the mode of operation
292          * (encrypt vs. decrypt): it is possible to setup a key for encryption
293          * and use it for AEAD decryption. Until tests relying on this
294          * are changed, allow any usage in PSA. */
295         psa_set_key_usage_flags( &attributes,
296                                  /* mbedtls_psa_translate_cipher_operation( operation ); */
297                                  PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT );
298         psa_set_key_algorithm( &attributes, cipher_psa->alg );
299 
300         status = psa_import_key( &attributes, key, key_bytelen,
301                                  &cipher_psa->slot );
302         switch( status )
303         {
304             case PSA_SUCCESS:
305                 break;
306             case PSA_ERROR_INSUFFICIENT_MEMORY:
307                 return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
308             case PSA_ERROR_NOT_SUPPORTED:
309                 return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
310             default:
311                 return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
312         }
313         /* Indicate that we own the key slot and need to
314          * destroy it in mbedtls_cipher_free(). */
315         cipher_psa->slot_state = MBEDTLS_CIPHER_PSA_KEY_OWNED;
316 
317         ctx->key_bitlen = key_bitlen;
318         ctx->operation = operation;
319         return( 0 );
320     }
321 #endif /* MBEDTLS_USE_PSA_CRYPTO */
322 
323     if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 &&
324         (int) ctx->cipher_info->key_bitlen != key_bitlen )
325     {
326         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
327     }
328 
329     ctx->key_bitlen = key_bitlen;
330     ctx->operation = operation;
331 
332     /*
333      * For OFB, CFB and CTR mode always use the encryption key schedule
334      */
335     if( MBEDTLS_ENCRYPT == operation ||
336         MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
337         MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
338         MBEDTLS_MODE_CTR == ctx->cipher_info->mode )
339     {
340         return( ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key,
341                                                          ctx->key_bitlen ) );
342     }
343 
344     if( MBEDTLS_DECRYPT == operation )
345         return( ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key,
346                                                          ctx->key_bitlen ) );
347 
348     return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
349 }
350 
mbedtls_cipher_set_iv(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len)351 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
352                            const unsigned char *iv,
353                            size_t iv_len )
354 {
355     size_t actual_iv_size;
356 
357     CIPHER_VALIDATE_RET( ctx != NULL );
358     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
359     if( ctx->cipher_info == NULL )
360         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
361 #if defined(MBEDTLS_USE_PSA_CRYPTO)
362     if( ctx->psa_enabled == 1 )
363     {
364         /* While PSA Crypto has an API for multipart
365          * operations, we currently don't make it
366          * accessible through the cipher layer. */
367         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
368     }
369 #endif /* MBEDTLS_USE_PSA_CRYPTO */
370 
371     /* avoid buffer overflow in ctx->iv */
372     if( iv_len > MBEDTLS_MAX_IV_LENGTH )
373         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
374 
375     if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_IV_LEN ) != 0 )
376         actual_iv_size = iv_len;
377     else
378     {
379         actual_iv_size = ctx->cipher_info->iv_size;
380 
381         /* avoid reading past the end of input buffer */
382         if( actual_iv_size > iv_len )
383             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
384     }
385 
386 #if defined(MBEDTLS_CHACHA20_C)
387     if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20 )
388     {
389         if ( 0 != mbedtls_chacha20_starts( (mbedtls_chacha20_context*)ctx->cipher_ctx,
390                                            iv,
391                                            0U ) ) /* Initial counter value */
392         {
393             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
394         }
395     }
396 #endif
397 
398     if ( actual_iv_size != 0 )
399     {
400         memcpy( ctx->iv, iv, actual_iv_size );
401         ctx->iv_size = actual_iv_size;
402     }
403 
404     return( 0 );
405 }
406 
mbedtls_cipher_reset(mbedtls_cipher_context_t * ctx)407 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )
408 {
409     CIPHER_VALIDATE_RET( ctx != NULL );
410     if( ctx->cipher_info == NULL )
411         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
412 
413 #if defined(MBEDTLS_USE_PSA_CRYPTO)
414     if( ctx->psa_enabled == 1 )
415     {
416         /* We don't support resetting PSA-based
417          * cipher contexts, yet. */
418         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
419     }
420 #endif /* MBEDTLS_USE_PSA_CRYPTO */
421 
422     ctx->unprocessed_len = 0;
423 
424     return( 0 );
425 }
426 
427 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
mbedtls_cipher_update_ad(mbedtls_cipher_context_t * ctx,const unsigned char * ad,size_t ad_len)428 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
429                       const unsigned char *ad, size_t ad_len )
430 {
431     CIPHER_VALIDATE_RET( ctx != NULL );
432     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
433     if( ctx->cipher_info == NULL )
434         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
435 
436 #if defined(MBEDTLS_USE_PSA_CRYPTO)
437     if( ctx->psa_enabled == 1 )
438     {
439         /* While PSA Crypto has an API for multipart
440          * operations, we currently don't make it
441          * accessible through the cipher layer. */
442         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
443     }
444 #endif /* MBEDTLS_USE_PSA_CRYPTO */
445 
446 #if defined(MBEDTLS_GCM_C)
447     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
448     {
449         return( mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation,
450                                     ctx->iv, ctx->iv_size, ad, ad_len ) );
451     }
452 #endif
453 
454 #if defined(MBEDTLS_CHACHAPOLY_C)
455     if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
456     {
457         int result;
458         mbedtls_chachapoly_mode_t mode;
459 
460         mode = ( ctx->operation == MBEDTLS_ENCRYPT )
461                 ? MBEDTLS_CHACHAPOLY_ENCRYPT
462                 : MBEDTLS_CHACHAPOLY_DECRYPT;
463 
464         result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
465                                                         ctx->iv,
466                                                         mode );
467         if ( result != 0 )
468             return( result );
469 
470         return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
471                                                ad, ad_len ) );
472     }
473 #endif
474 
475     return( 0 );
476 }
477 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
478 
mbedtls_cipher_update(mbedtls_cipher_context_t * ctx,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen)479 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
480                    size_t ilen, unsigned char *output, size_t *olen )
481 {
482     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
483     size_t block_size;
484 
485     CIPHER_VALIDATE_RET( ctx != NULL );
486     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
487     CIPHER_VALIDATE_RET( output != NULL );
488     CIPHER_VALIDATE_RET( olen != NULL );
489     if( ctx->cipher_info == NULL )
490         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
491 
492 #if defined(MBEDTLS_USE_PSA_CRYPTO)
493     if( ctx->psa_enabled == 1 )
494     {
495         /* While PSA Crypto has an API for multipart
496          * operations, we currently don't make it
497          * accessible through the cipher layer. */
498         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
499     }
500 #endif /* MBEDTLS_USE_PSA_CRYPTO */
501 
502     *olen = 0;
503     block_size = mbedtls_cipher_get_block_size( ctx );
504     if ( 0 == block_size )
505     {
506         return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
507     }
508 
509     if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB )
510     {
511         if( ilen != block_size )
512             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
513 
514         *olen = ilen;
515 
516         if( 0 != ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,
517                     ctx->operation, input, output ) ) )
518         {
519             return( ret );
520         }
521 
522         return( 0 );
523     }
524 
525 #if defined(MBEDTLS_GCM_C)
526     if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM )
527     {
528         *olen = ilen;
529         return( mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input,
530                                     output ) );
531     }
532 #endif
533 
534 #if defined(MBEDTLS_CHACHAPOLY_C)
535     if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )
536     {
537         *olen = ilen;
538         return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
539                                            ilen, input, output ) );
540     }
541 #endif
542 
543     if( input == output &&
544        ( ctx->unprocessed_len != 0 || ilen % block_size ) )
545     {
546         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
547     }
548 
549 #if defined(MBEDTLS_CIPHER_MODE_CBC)
550     if( ctx->cipher_info->mode == MBEDTLS_MODE_CBC )
551     {
552         size_t copy_len = 0;
553 
554         /*
555          * If there is not enough data for a full block, cache it.
556          */
557         if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&
558                 ilen <= block_size - ctx->unprocessed_len ) ||
559             ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&
560                 ilen < block_size - ctx->unprocessed_len ) ||
561              ( ctx->operation == MBEDTLS_ENCRYPT &&
562                 ilen < block_size - ctx->unprocessed_len ) )
563         {
564             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
565                     ilen );
566 
567             ctx->unprocessed_len += ilen;
568             return( 0 );
569         }
570 
571         /*
572          * Process cached data first
573          */
574         if( 0 != ctx->unprocessed_len )
575         {
576             copy_len = block_size - ctx->unprocessed_len;
577 
578             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
579                     copy_len );
580 
581             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
582                     ctx->operation, block_size, ctx->iv,
583                     ctx->unprocessed_data, output ) ) )
584             {
585                 return( ret );
586             }
587 
588             *olen += block_size;
589             output += block_size;
590             ctx->unprocessed_len = 0;
591 
592             input += copy_len;
593             ilen -= copy_len;
594         }
595 
596         /*
597          * Cache final, incomplete block
598          */
599         if( 0 != ilen )
600         {
601             /* Encryption: only cache partial blocks
602              * Decryption w/ padding: always keep at least one whole block
603              * Decryption w/o padding: only cache partial blocks
604              */
605             copy_len = ilen % block_size;
606             if( copy_len == 0 &&
607                 ctx->operation == MBEDTLS_DECRYPT &&
608                 NULL != ctx->add_padding)
609             {
610                 copy_len = block_size;
611             }
612 
613             memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
614                     copy_len );
615 
616             ctx->unprocessed_len += copy_len;
617             ilen -= copy_len;
618         }
619 
620         /*
621          * Process remaining full blocks
622          */
623         if( ilen )
624         {
625             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
626                     ctx->operation, ilen, ctx->iv, input, output ) ) )
627             {
628                 return( ret );
629             }
630 
631             *olen += ilen;
632         }
633 
634         return( 0 );
635     }
636 #endif /* MBEDTLS_CIPHER_MODE_CBC */
637 
638 #if defined(MBEDTLS_CIPHER_MODE_CFB)
639     if( ctx->cipher_info->mode == MBEDTLS_MODE_CFB )
640     {
641         if( 0 != ( ret = ctx->cipher_info->base->cfb_func( ctx->cipher_ctx,
642                 ctx->operation, ilen, &ctx->unprocessed_len, ctx->iv,
643                 input, output ) ) )
644         {
645             return( ret );
646         }
647 
648         *olen = ilen;
649 
650         return( 0 );
651     }
652 #endif /* MBEDTLS_CIPHER_MODE_CFB */
653 
654 #if defined(MBEDTLS_CIPHER_MODE_OFB)
655     if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB )
656     {
657         if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx,
658                 ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) )
659         {
660             return( ret );
661         }
662 
663         *olen = ilen;
664 
665         return( 0 );
666     }
667 #endif /* MBEDTLS_CIPHER_MODE_OFB */
668 
669 #if defined(MBEDTLS_CIPHER_MODE_CTR)
670     if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR )
671     {
672         if( 0 != ( ret = ctx->cipher_info->base->ctr_func( ctx->cipher_ctx,
673                 ilen, &ctx->unprocessed_len, ctx->iv,
674                 ctx->unprocessed_data, input, output ) ) )
675         {
676             return( ret );
677         }
678 
679         *olen = ilen;
680 
681         return( 0 );
682     }
683 #endif /* MBEDTLS_CIPHER_MODE_CTR */
684 
685 #if defined(MBEDTLS_CIPHER_MODE_XTS)
686     if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS )
687     {
688         if( ctx->unprocessed_len > 0 ) {
689             /* We can only process an entire data unit at a time. */
690             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
691         }
692 
693         ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx,
694                 ctx->operation, ilen, ctx->iv, input, output );
695         if( ret != 0 )
696         {
697             return( ret );
698         }
699 
700         *olen = ilen;
701 
702         return( 0 );
703     }
704 #endif /* MBEDTLS_CIPHER_MODE_XTS */
705 
706 #if defined(MBEDTLS_CIPHER_MODE_STREAM)
707     if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM )
708     {
709         if( 0 != ( ret = ctx->cipher_info->base->stream_func( ctx->cipher_ctx,
710                                                     ilen, input, output ) ) )
711         {
712             return( ret );
713         }
714 
715         *olen = ilen;
716 
717         return( 0 );
718     }
719 #endif /* MBEDTLS_CIPHER_MODE_STREAM */
720 
721     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
722 }
723 
724 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
725 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
726 /*
727  * PKCS7 (and PKCS5) padding: fill with ll bytes, with ll = padding_len
728  */
add_pkcs_padding(unsigned char * output,size_t output_len,size_t data_len)729 static void add_pkcs_padding( unsigned char *output, size_t output_len,
730         size_t data_len )
731 {
732     size_t padding_len = output_len - data_len;
733     unsigned char i;
734 
735     for( i = 0; i < padding_len; i++ )
736         output[data_len + i] = (unsigned char) padding_len;
737 }
738 
get_pkcs_padding(unsigned char * input,size_t input_len,size_t * data_len)739 static int get_pkcs_padding( unsigned char *input, size_t input_len,
740         size_t *data_len )
741 {
742     size_t i, pad_idx;
743     unsigned char padding_len, bad = 0;
744 
745     if( NULL == input || NULL == data_len )
746         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
747 
748     padding_len = input[input_len - 1];
749     *data_len = input_len - padding_len;
750 
751     /* Avoid logical || since it results in a branch */
752     bad |= padding_len > input_len;
753     bad |= padding_len == 0;
754 
755     /* The number of bytes checked must be independent of padding_len,
756      * so pick input_len, which is usually 8 or 16 (one block) */
757     pad_idx = input_len - padding_len;
758     for( i = 0; i < input_len; i++ )
759         bad |= ( input[i] ^ padding_len ) * ( i >= pad_idx );
760 
761     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
762 }
763 #endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
764 
765 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
766 /*
767  * One and zeros padding: fill with 80 00 ... 00
768  */
add_one_and_zeros_padding(unsigned char * output,size_t output_len,size_t data_len)769 static void add_one_and_zeros_padding( unsigned char *output,
770                                        size_t output_len, size_t data_len )
771 {
772     size_t padding_len = output_len - data_len;
773     unsigned char i = 0;
774 
775     output[data_len] = 0x80;
776     for( i = 1; i < padding_len; i++ )
777         output[data_len + i] = 0x00;
778 }
779 
get_one_and_zeros_padding(unsigned char * input,size_t input_len,size_t * data_len)780 static int get_one_and_zeros_padding( unsigned char *input, size_t input_len,
781                                       size_t *data_len )
782 {
783     size_t i;
784     unsigned char done = 0, prev_done, bad;
785 
786     if( NULL == input || NULL == data_len )
787         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
788 
789     bad = 0x80;
790     *data_len = 0;
791     for( i = input_len; i > 0; i-- )
792     {
793         prev_done = done;
794         done |= ( input[i - 1] != 0 );
795         *data_len |= ( i - 1 ) * ( done != prev_done );
796         bad ^= input[i - 1] * ( done != prev_done );
797     }
798 
799     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
800 
801 }
802 #endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */
803 
804 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
805 /*
806  * Zeros and len padding: fill with 00 ... 00 ll, where ll is padding length
807  */
add_zeros_and_len_padding(unsigned char * output,size_t output_len,size_t data_len)808 static void add_zeros_and_len_padding( unsigned char *output,
809                                        size_t output_len, size_t data_len )
810 {
811     size_t padding_len = output_len - data_len;
812     unsigned char i = 0;
813 
814     for( i = 1; i < padding_len; i++ )
815         output[data_len + i - 1] = 0x00;
816     output[output_len - 1] = (unsigned char) padding_len;
817 }
818 
get_zeros_and_len_padding(unsigned char * input,size_t input_len,size_t * data_len)819 static int get_zeros_and_len_padding( unsigned char *input, size_t input_len,
820                                       size_t *data_len )
821 {
822     size_t i, pad_idx;
823     unsigned char padding_len, bad = 0;
824 
825     if( NULL == input || NULL == data_len )
826         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
827 
828     padding_len = input[input_len - 1];
829     *data_len = input_len - padding_len;
830 
831     /* Avoid logical || since it results in a branch */
832     bad |= padding_len > input_len;
833     bad |= padding_len == 0;
834 
835     /* The number of bytes checked must be independent of padding_len */
836     pad_idx = input_len - padding_len;
837     for( i = 0; i < input_len - 1; i++ )
838         bad |= input[i] * ( i >= pad_idx );
839 
840     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
841 }
842 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */
843 
844 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
845 /*
846  * Zero padding: fill with 00 ... 00
847  */
add_zeros_padding(unsigned char * output,size_t output_len,size_t data_len)848 static void add_zeros_padding( unsigned char *output,
849                                size_t output_len, size_t data_len )
850 {
851     size_t i;
852 
853     for( i = data_len; i < output_len; i++ )
854         output[i] = 0x00;
855 }
856 
get_zeros_padding(unsigned char * input,size_t input_len,size_t * data_len)857 static int get_zeros_padding( unsigned char *input, size_t input_len,
858                               size_t *data_len )
859 {
860     size_t i;
861     unsigned char done = 0, prev_done;
862 
863     if( NULL == input || NULL == data_len )
864         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
865 
866     *data_len = 0;
867     for( i = input_len; i > 0; i-- )
868     {
869         prev_done = done;
870         done |= ( input[i-1] != 0 );
871         *data_len |= i * ( done != prev_done );
872     }
873 
874     return( 0 );
875 }
876 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS */
877 
878 /*
879  * No padding: don't pad :)
880  *
881  * There is no add_padding function (check for NULL in mbedtls_cipher_finish)
882  * but a trivial get_padding function
883  */
get_no_padding(unsigned char * input,size_t input_len,size_t * data_len)884 static int get_no_padding( unsigned char *input, size_t input_len,
885                               size_t *data_len )
886 {
887     if( NULL == input || NULL == data_len )
888         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
889 
890     *data_len = input_len;
891 
892     return( 0 );
893 }
894 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
895 
mbedtls_cipher_finish(mbedtls_cipher_context_t * ctx,unsigned char * output,size_t * olen)896 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
897                    unsigned char *output, size_t *olen )
898 {
899     CIPHER_VALIDATE_RET( ctx != NULL );
900     CIPHER_VALIDATE_RET( output != NULL );
901     CIPHER_VALIDATE_RET( olen != NULL );
902     if( ctx->cipher_info == NULL )
903         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
904 
905 #if defined(MBEDTLS_USE_PSA_CRYPTO)
906     if( ctx->psa_enabled == 1 )
907     {
908         /* While PSA Crypto has an API for multipart
909          * operations, we currently don't make it
910          * accessible through the cipher layer. */
911         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
912     }
913 #endif /* MBEDTLS_USE_PSA_CRYPTO */
914 
915     *olen = 0;
916 
917     if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
918         MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
919         MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||
920         MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||
921         MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||
922         MBEDTLS_MODE_STREAM == ctx->cipher_info->mode )
923     {
924         return( 0 );
925     }
926 
927     if ( ( MBEDTLS_CIPHER_CHACHA20          == ctx->cipher_info->type ) ||
928          ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) )
929     {
930         return( 0 );
931     }
932 
933     if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode )
934     {
935         if( ctx->unprocessed_len != 0 )
936             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
937 
938         return( 0 );
939     }
940 
941 #if defined(MBEDTLS_CIPHER_MODE_CBC)
942     if( MBEDTLS_MODE_CBC == ctx->cipher_info->mode )
943     {
944         int ret = 0;
945 
946         if( MBEDTLS_ENCRYPT == ctx->operation )
947         {
948             /* check for 'no padding' mode */
949             if( NULL == ctx->add_padding )
950             {
951                 if( 0 != ctx->unprocessed_len )
952                     return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
953 
954                 return( 0 );
955             }
956 
957             ctx->add_padding( ctx->unprocessed_data, mbedtls_cipher_get_iv_size( ctx ),
958                     ctx->unprocessed_len );
959         }
960         else if( mbedtls_cipher_get_block_size( ctx ) != ctx->unprocessed_len )
961         {
962             /*
963              * For decrypt operations, expect a full block,
964              * or an empty block if no padding
965              */
966             if( NULL == ctx->add_padding && 0 == ctx->unprocessed_len )
967                 return( 0 );
968 
969             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
970         }
971 
972         /* cipher block */
973         if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
974                 ctx->operation, mbedtls_cipher_get_block_size( ctx ), ctx->iv,
975                 ctx->unprocessed_data, output ) ) )
976         {
977             return( ret );
978         }
979 
980         /* Set output size for decryption */
981         if( MBEDTLS_DECRYPT == ctx->operation )
982             return( ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),
983                                       olen ) );
984 
985         /* Set output size for encryption */
986         *olen = mbedtls_cipher_get_block_size( ctx );
987         return( 0 );
988     }
989 #else
990     ((void) output);
991 #endif /* MBEDTLS_CIPHER_MODE_CBC */
992 
993     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
994 }
995 
996 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
mbedtls_cipher_set_padding_mode(mbedtls_cipher_context_t * ctx,mbedtls_cipher_padding_t mode)997 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx,
998                                      mbedtls_cipher_padding_t mode )
999 {
1000     CIPHER_VALIDATE_RET( ctx != NULL );
1001 
1002     if( NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode )
1003     {
1004         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1005     }
1006 
1007 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1008     if( ctx->psa_enabled == 1 )
1009     {
1010         /* While PSA Crypto knows about CBC padding
1011          * schemes, we currently don't make them
1012          * accessible through the cipher layer. */
1013         if( mode != MBEDTLS_PADDING_NONE )
1014             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1015 
1016         return( 0 );
1017     }
1018 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1019 
1020     switch( mode )
1021     {
1022 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
1023     case MBEDTLS_PADDING_PKCS7:
1024         ctx->add_padding = add_pkcs_padding;
1025         ctx->get_padding = get_pkcs_padding;
1026         break;
1027 #endif
1028 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
1029     case MBEDTLS_PADDING_ONE_AND_ZEROS:
1030         ctx->add_padding = add_one_and_zeros_padding;
1031         ctx->get_padding = get_one_and_zeros_padding;
1032         break;
1033 #endif
1034 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
1035     case MBEDTLS_PADDING_ZEROS_AND_LEN:
1036         ctx->add_padding = add_zeros_and_len_padding;
1037         ctx->get_padding = get_zeros_and_len_padding;
1038         break;
1039 #endif
1040 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
1041     case MBEDTLS_PADDING_ZEROS:
1042         ctx->add_padding = add_zeros_padding;
1043         ctx->get_padding = get_zeros_padding;
1044         break;
1045 #endif
1046     case MBEDTLS_PADDING_NONE:
1047         ctx->add_padding = NULL;
1048         ctx->get_padding = get_no_padding;
1049         break;
1050 
1051     default:
1052         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1053     }
1054 
1055     return( 0 );
1056 }
1057 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
1058 
1059 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
mbedtls_cipher_write_tag(mbedtls_cipher_context_t * ctx,unsigned char * tag,size_t tag_len)1060 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
1061                       unsigned char *tag, size_t tag_len )
1062 {
1063     CIPHER_VALIDATE_RET( ctx != NULL );
1064     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1065     if( ctx->cipher_info == NULL )
1066         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1067 
1068     if( MBEDTLS_ENCRYPT != ctx->operation )
1069         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1070 
1071 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1072     if( ctx->psa_enabled == 1 )
1073     {
1074         /* While PSA Crypto has an API for multipart
1075          * operations, we currently don't make it
1076          * accessible through the cipher layer. */
1077         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1078     }
1079 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1080 
1081 #if defined(MBEDTLS_GCM_C)
1082     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1083         return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx,
1084                                     tag, tag_len ) );
1085 #endif
1086 
1087 #if defined(MBEDTLS_CHACHAPOLY_C)
1088     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1089     {
1090         /* Don't allow truncated MAC for Poly1305 */
1091         if ( tag_len != 16U )
1092             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1093 
1094         return( mbedtls_chachapoly_finish(
1095                     (mbedtls_chachapoly_context*) ctx->cipher_ctx, tag ) );
1096     }
1097 #endif
1098 
1099     return( 0 );
1100 }
1101 
mbedtls_cipher_check_tag(mbedtls_cipher_context_t * ctx,const unsigned char * tag,size_t tag_len)1102 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
1103                       const unsigned char *tag, size_t tag_len )
1104 {
1105     unsigned char check_tag[16];
1106     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1107 
1108     CIPHER_VALIDATE_RET( ctx != NULL );
1109     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1110     if( ctx->cipher_info == NULL )
1111         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1112 
1113     if( MBEDTLS_DECRYPT != ctx->operation )
1114     {
1115         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1116     }
1117 
1118 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1119     if( ctx->psa_enabled == 1 )
1120     {
1121         /* While PSA Crypto has an API for multipart
1122          * operations, we currently don't make it
1123          * accessible through the cipher layer. */
1124         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1125     }
1126 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1127 
1128     /* Status to return on a non-authenticated algorithm. It would make sense
1129      * to return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT or perhaps
1130      * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, but at the time I write this our
1131      * unit tests assume 0. */
1132     ret = 0;
1133 
1134 #if defined(MBEDTLS_GCM_C)
1135     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1136     {
1137         if( tag_len > sizeof( check_tag ) )
1138             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1139 
1140         if( 0 != ( ret = mbedtls_gcm_finish(
1141                        (mbedtls_gcm_context *) ctx->cipher_ctx,
1142                        check_tag, tag_len ) ) )
1143         {
1144             return( ret );
1145         }
1146 
1147         /* Check the tag in "constant-time" */
1148         if( mbedtls_ct_memcmp( tag, check_tag, tag_len ) != 0 )
1149         {
1150             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1151             goto exit;
1152         }
1153     }
1154 #endif /* MBEDTLS_GCM_C */
1155 
1156 #if defined(MBEDTLS_CHACHAPOLY_C)
1157     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1158     {
1159         /* Don't allow truncated MAC for Poly1305 */
1160         if ( tag_len != sizeof( check_tag ) )
1161             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1162 
1163         ret = mbedtls_chachapoly_finish(
1164             (mbedtls_chachapoly_context*) ctx->cipher_ctx, check_tag );
1165         if ( ret != 0 )
1166         {
1167             return( ret );
1168         }
1169 
1170         /* Check the tag in "constant-time" */
1171         if( mbedtls_ct_memcmp( tag, check_tag, tag_len ) != 0 )
1172         {
1173             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1174             goto exit;
1175         }
1176     }
1177 #endif /* MBEDTLS_CHACHAPOLY_C */
1178 
1179 exit:
1180     mbedtls_platform_zeroize( check_tag, tag_len );
1181     return( ret );
1182 }
1183 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
1184 
1185 /*
1186  * Packet-oriented wrapper for non-AEAD modes
1187  */
mbedtls_cipher_crypt(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen)1188 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
1189                   const unsigned char *iv, size_t iv_len,
1190                   const unsigned char *input, size_t ilen,
1191                   unsigned char *output, size_t *olen )
1192 {
1193     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1194     size_t finish_olen;
1195 
1196     CIPHER_VALIDATE_RET( ctx != NULL );
1197     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1198     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1199     CIPHER_VALIDATE_RET( output != NULL );
1200     CIPHER_VALIDATE_RET( olen != NULL );
1201 
1202 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1203     if( ctx->psa_enabled == 1 )
1204     {
1205         /* As in the non-PSA case, we don't check that
1206          * a key has been set. If not, the key slot will
1207          * still be in its default state of 0, which is
1208          * guaranteed to be invalid, hence the PSA-call
1209          * below will gracefully fail. */
1210         mbedtls_cipher_context_psa * const cipher_psa =
1211             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1212 
1213         psa_status_t status;
1214         psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1215         size_t part_len;
1216 
1217         if( ctx->operation == MBEDTLS_DECRYPT )
1218         {
1219             status = psa_cipher_decrypt_setup( &cipher_op,
1220                                                cipher_psa->slot,
1221                                                cipher_psa->alg );
1222         }
1223         else if( ctx->operation == MBEDTLS_ENCRYPT )
1224         {
1225             status = psa_cipher_encrypt_setup( &cipher_op,
1226                                                cipher_psa->slot,
1227                                                cipher_psa->alg );
1228         }
1229         else
1230             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1231 
1232         /* In the following, we can immediately return on an error,
1233          * because the PSA Crypto API guarantees that cipher operations
1234          * are terminated by unsuccessful calls to psa_cipher_update(),
1235          * and by any call to psa_cipher_finish(). */
1236         if( status != PSA_SUCCESS )
1237             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1238 
1239         if( ctx->cipher_info->mode != MBEDTLS_MODE_ECB )
1240         {
1241             status = psa_cipher_set_iv( &cipher_op, iv, iv_len );
1242             if( status != PSA_SUCCESS )
1243                 return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1244         }
1245 
1246         status = psa_cipher_update( &cipher_op,
1247                                     input, ilen,
1248                                     output, ilen, olen );
1249         if( status != PSA_SUCCESS )
1250             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1251 
1252         status = psa_cipher_finish( &cipher_op,
1253                                     output + *olen, ilen - *olen,
1254                                     &part_len );
1255         if( status != PSA_SUCCESS )
1256             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1257 
1258         *olen += part_len;
1259         return( 0 );
1260     }
1261 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1262 
1263     if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 )
1264         return( ret );
1265 
1266     if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 )
1267         return( ret );
1268 
1269     if( ( ret = mbedtls_cipher_update( ctx, input, ilen,
1270                                        output, olen ) ) != 0 )
1271         return( ret );
1272 
1273     if( ( ret = mbedtls_cipher_finish( ctx, output + *olen,
1274                                        &finish_olen ) ) != 0 )
1275         return( ret );
1276 
1277     *olen += finish_olen;
1278 
1279     return( 0 );
1280 }
1281 
1282 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1283 /*
1284  * Packet-oriented encryption for AEAD modes: internal function shared by
1285  * mbedtls_cipher_auth_encrypt() and mbedtls_cipher_auth_encrypt_ext().
1286  */
mbedtls_cipher_aead_encrypt(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen,unsigned char * tag,size_t tag_len)1287 static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx,
1288                          const unsigned char *iv, size_t iv_len,
1289                          const unsigned char *ad, size_t ad_len,
1290                          const unsigned char *input, size_t ilen,
1291                          unsigned char *output, size_t *olen,
1292                          unsigned char *tag, size_t tag_len )
1293 {
1294 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1295     if( ctx->psa_enabled == 1 )
1296     {
1297         /* As in the non-PSA case, we don't check that
1298          * a key has been set. If not, the key slot will
1299          * still be in its default state of 0, which is
1300          * guaranteed to be invalid, hence the PSA-call
1301          * below will gracefully fail. */
1302         mbedtls_cipher_context_psa * const cipher_psa =
1303             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1304 
1305         psa_status_t status;
1306 
1307         /* PSA Crypto API always writes the authentication tag
1308          * at the end of the encrypted message. */
1309         if( output == NULL || tag != output + ilen )
1310             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1311 
1312         status = psa_aead_encrypt( cipher_psa->slot,
1313                                    cipher_psa->alg,
1314                                    iv, iv_len,
1315                                    ad, ad_len,
1316                                    input, ilen,
1317                                    output, ilen + tag_len, olen );
1318         if( status != PSA_SUCCESS )
1319             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1320 
1321         *olen -= tag_len;
1322         return( 0 );
1323     }
1324 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1325 
1326 #if defined(MBEDTLS_GCM_C)
1327     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1328     {
1329         *olen = ilen;
1330         return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT,
1331                                            ilen, iv, iv_len, ad, ad_len,
1332                                            input, output, tag_len, tag ) );
1333     }
1334 #endif /* MBEDTLS_GCM_C */
1335 #if defined(MBEDTLS_CCM_C)
1336     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1337     {
1338         *olen = ilen;
1339         return( mbedtls_ccm_encrypt_and_tag( ctx->cipher_ctx, ilen,
1340                                      iv, iv_len, ad, ad_len, input, output,
1341                                      tag, tag_len ) );
1342     }
1343 #endif /* MBEDTLS_CCM_C */
1344 #if defined(MBEDTLS_CHACHAPOLY_C)
1345     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1346     {
1347         /* ChachaPoly has fixed length nonce and MAC (tag) */
1348         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1349              ( tag_len != 16U ) )
1350         {
1351             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1352         }
1353 
1354         *olen = ilen;
1355         return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx,
1356                                 ilen, iv, ad, ad_len, input, output, tag ) );
1357     }
1358 #endif /* MBEDTLS_CHACHAPOLY_C */
1359 
1360     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1361 }
1362 
1363 /*
1364  * Packet-oriented encryption for AEAD modes: internal function shared by
1365  * mbedtls_cipher_auth_encrypt() and mbedtls_cipher_auth_encrypt_ext().
1366  */
mbedtls_cipher_aead_decrypt(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen,const unsigned char * tag,size_t tag_len)1367 static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx,
1368                          const unsigned char *iv, size_t iv_len,
1369                          const unsigned char *ad, size_t ad_len,
1370                          const unsigned char *input, size_t ilen,
1371                          unsigned char *output, size_t *olen,
1372                          const unsigned char *tag, size_t tag_len )
1373 {
1374 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1375     if( ctx->psa_enabled == 1 )
1376     {
1377         /* As in the non-PSA case, we don't check that
1378          * a key has been set. If not, the key slot will
1379          * still be in its default state of 0, which is
1380          * guaranteed to be invalid, hence the PSA-call
1381          * below will gracefully fail. */
1382         mbedtls_cipher_context_psa * const cipher_psa =
1383             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1384 
1385         psa_status_t status;
1386 
1387         /* PSA Crypto API always writes the authentication tag
1388          * at the end of the encrypted message. */
1389         if( input == NULL || tag != input + ilen )
1390             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1391 
1392         status = psa_aead_decrypt( cipher_psa->slot,
1393                                    cipher_psa->alg,
1394                                    iv, iv_len,
1395                                    ad, ad_len,
1396                                    input, ilen + tag_len,
1397                                    output, ilen, olen );
1398         if( status == PSA_ERROR_INVALID_SIGNATURE )
1399             return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
1400         else if( status != PSA_SUCCESS )
1401             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1402 
1403         return( 0 );
1404     }
1405 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1406 
1407 #if defined(MBEDTLS_GCM_C)
1408     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1409     {
1410         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1411 
1412         *olen = ilen;
1413         ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen,
1414                                 iv, iv_len, ad, ad_len,
1415                                 tag, tag_len, input, output );
1416 
1417         if( ret == MBEDTLS_ERR_GCM_AUTH_FAILED )
1418             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1419 
1420         return( ret );
1421     }
1422 #endif /* MBEDTLS_GCM_C */
1423 #if defined(MBEDTLS_CCM_C)
1424     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1425     {
1426         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1427 
1428         *olen = ilen;
1429         ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen,
1430                                 iv, iv_len, ad, ad_len,
1431                                 input, output, tag, tag_len );
1432 
1433         if( ret == MBEDTLS_ERR_CCM_AUTH_FAILED )
1434             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1435 
1436         return( ret );
1437     }
1438 #endif /* MBEDTLS_CCM_C */
1439 #if defined(MBEDTLS_CHACHAPOLY_C)
1440     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1441     {
1442         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1443 
1444         /* ChachaPoly has fixed length nonce and MAC (tag) */
1445         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1446              ( tag_len != 16U ) )
1447         {
1448             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1449         }
1450 
1451         *olen = ilen;
1452         ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen,
1453                                 iv, ad, ad_len, tag, input, output );
1454 
1455         if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED )
1456             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1457 
1458         return( ret );
1459     }
1460 #endif /* MBEDTLS_CHACHAPOLY_C */
1461 
1462     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1463 }
1464 
1465 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
1466 /*
1467  * Packet-oriented encryption for AEAD modes: public legacy function.
1468  */
mbedtls_cipher_auth_encrypt(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen,unsigned char * tag,size_t tag_len)1469 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
1470                          const unsigned char *iv, size_t iv_len,
1471                          const unsigned char *ad, size_t ad_len,
1472                          const unsigned char *input, size_t ilen,
1473                          unsigned char *output, size_t *olen,
1474                          unsigned char *tag, size_t tag_len )
1475 {
1476     CIPHER_VALIDATE_RET( ctx != NULL );
1477     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1478     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1479     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1480     CIPHER_VALIDATE_RET( ilen == 0 || output != NULL );
1481     CIPHER_VALIDATE_RET( olen != NULL );
1482     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1483 
1484     return( mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len,
1485                                          input, ilen, output, olen,
1486                                          tag, tag_len ) );
1487 }
1488 
1489 /*
1490  * Packet-oriented decryption for AEAD modes: public legacy function.
1491  */
mbedtls_cipher_auth_decrypt(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen,const unsigned char * tag,size_t tag_len)1492 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
1493                          const unsigned char *iv, size_t iv_len,
1494                          const unsigned char *ad, size_t ad_len,
1495                          const unsigned char *input, size_t ilen,
1496                          unsigned char *output, size_t *olen,
1497                          const unsigned char *tag, size_t tag_len )
1498 {
1499     CIPHER_VALIDATE_RET( ctx != NULL );
1500     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1501     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1502     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1503     CIPHER_VALIDATE_RET( ilen == 0 || output != NULL );
1504     CIPHER_VALIDATE_RET( olen != NULL );
1505     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1506 
1507     return( mbedtls_cipher_aead_decrypt( ctx, iv, iv_len, ad, ad_len,
1508                                          input, ilen, output, olen,
1509                                          tag, tag_len ) );
1510 }
1511 #endif /* !MBEDTLS_DEPRECATED_REMOVED */
1512 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1513 
1514 #if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C)
1515 /*
1516  * Packet-oriented encryption for AEAD/NIST_KW: public function.
1517  */
mbedtls_cipher_auth_encrypt_ext(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t output_len,size_t * olen,size_t tag_len)1518 int mbedtls_cipher_auth_encrypt_ext( mbedtls_cipher_context_t *ctx,
1519                          const unsigned char *iv, size_t iv_len,
1520                          const unsigned char *ad, size_t ad_len,
1521                          const unsigned char *input, size_t ilen,
1522                          unsigned char *output, size_t output_len,
1523                          size_t *olen, size_t tag_len )
1524 {
1525     CIPHER_VALIDATE_RET( ctx != NULL );
1526     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1527     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1528     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1529     CIPHER_VALIDATE_RET( output != NULL );
1530     CIPHER_VALIDATE_RET( olen != NULL );
1531 
1532 #if defined(MBEDTLS_NIST_KW_C)
1533     if(
1534 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1535         ctx->psa_enabled == 0 &&
1536 #endif
1537         ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1538           MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) )
1539     {
1540         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1541                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1542 
1543         /* There is no iv, tag or ad associated with KW and KWP,
1544          * so these length should be 0 as documented. */
1545         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1546             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1547 
1548         (void) iv;
1549         (void) ad;
1550 
1551         return( mbedtls_nist_kw_wrap( ctx->cipher_ctx, mode, input, ilen,
1552                                       output, olen, output_len ) );
1553     }
1554 #endif /* MBEDTLS_NIST_KW_C */
1555 
1556 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1557     /* AEAD case: check length before passing on to shared function */
1558     if( output_len < ilen + tag_len )
1559         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1560 
1561     int ret = mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len,
1562                                        input, ilen, output, olen,
1563                                        output + ilen, tag_len );
1564     *olen += tag_len;
1565     return( ret );
1566 #else
1567     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1568 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1569 }
1570 
1571 /*
1572  * Packet-oriented decryption for AEAD/NIST_KW: public function.
1573  */
mbedtls_cipher_auth_decrypt_ext(mbedtls_cipher_context_t * ctx,const unsigned char * iv,size_t iv_len,const unsigned char * ad,size_t ad_len,const unsigned char * input,size_t ilen,unsigned char * output,size_t output_len,size_t * olen,size_t tag_len)1574 int mbedtls_cipher_auth_decrypt_ext( mbedtls_cipher_context_t *ctx,
1575                          const unsigned char *iv, size_t iv_len,
1576                          const unsigned char *ad, size_t ad_len,
1577                          const unsigned char *input, size_t ilen,
1578                          unsigned char *output, size_t output_len,
1579                          size_t *olen, size_t tag_len )
1580 {
1581     CIPHER_VALIDATE_RET( ctx != NULL );
1582     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1583     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1584     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1585     CIPHER_VALIDATE_RET( output_len == 0 || output != NULL );
1586     CIPHER_VALIDATE_RET( olen != NULL );
1587 
1588 #if defined(MBEDTLS_NIST_KW_C)
1589     if(
1590 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1591         ctx->psa_enabled == 0 &&
1592 #endif
1593         ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1594           MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) )
1595     {
1596         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1597                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1598 
1599         /* There is no iv, tag or ad associated with KW and KWP,
1600          * so these length should be 0 as documented. */
1601         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1602             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1603 
1604         (void) iv;
1605         (void) ad;
1606 
1607         return( mbedtls_nist_kw_unwrap( ctx->cipher_ctx, mode, input, ilen,
1608                                         output, olen, output_len ) );
1609     }
1610 #endif /* MBEDTLS_NIST_KW_C */
1611 
1612 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1613     /* AEAD case: check length before passing on to shared function */
1614     if( ilen < tag_len || output_len < ilen - tag_len )
1615         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1616 
1617     return( mbedtls_cipher_aead_decrypt( ctx, iv, iv_len, ad, ad_len,
1618                                          input, ilen - tag_len, output, olen,
1619                                          input + ilen - tag_len, tag_len ) );
1620 #else
1621     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1622 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1623 }
1624 #endif /* MBEDTLS_CIPHER_MODE_AEAD || MBEDTLS_NIST_KW_C */
1625 
1626 #endif /* MBEDTLS_CIPHER_C */
1627