• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "cipher_wrap.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_PLATFORM_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 defined(MBEDTLS_GCM_C)
399     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
400     {
401         return( mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx,
402                                     ctx->operation,
403                                     iv, iv_len ) );
404     }
405 #endif
406 
407 #if defined(MBEDTLS_CCM_C)
408     if( MBEDTLS_MODE_CCM_STAR_NO_TAG == ctx->cipher_info->mode )
409     {
410         int set_lengths_result;
411         int ccm_star_mode;
412 
413         set_lengths_result = mbedtls_ccm_set_lengths(
414                                 (mbedtls_ccm_context *) ctx->cipher_ctx,
415                                 0, 0, 0 );
416         if( set_lengths_result != 0 )
417             return set_lengths_result;
418 
419         if( ctx->operation == MBEDTLS_DECRYPT )
420             ccm_star_mode = MBEDTLS_CCM_STAR_DECRYPT;
421         else if( ctx->operation == MBEDTLS_ENCRYPT )
422             ccm_star_mode = MBEDTLS_CCM_STAR_ENCRYPT;
423         else
424             return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
425 
426         return( mbedtls_ccm_starts( (mbedtls_ccm_context *) ctx->cipher_ctx,
427                                     ccm_star_mode,
428                                     iv, iv_len ) );
429     }
430 #endif
431 
432     if ( actual_iv_size != 0 )
433     {
434         memcpy( ctx->iv, iv, actual_iv_size );
435         ctx->iv_size = actual_iv_size;
436     }
437 
438     return( 0 );
439 }
440 
mbedtls_cipher_reset(mbedtls_cipher_context_t * ctx)441 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )
442 {
443     CIPHER_VALIDATE_RET( ctx != NULL );
444     if( ctx->cipher_info == NULL )
445         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
446 
447 #if defined(MBEDTLS_USE_PSA_CRYPTO)
448     if( ctx->psa_enabled == 1 )
449     {
450         /* We don't support resetting PSA-based
451          * cipher contexts, yet. */
452         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
453     }
454 #endif /* MBEDTLS_USE_PSA_CRYPTO */
455 
456     ctx->unprocessed_len = 0;
457 
458     return( 0 );
459 }
460 
461 #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)462 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
463                       const unsigned char *ad, size_t ad_len )
464 {
465     CIPHER_VALIDATE_RET( ctx != NULL );
466     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
467     if( ctx->cipher_info == NULL )
468         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
469 
470 #if defined(MBEDTLS_USE_PSA_CRYPTO)
471     if( ctx->psa_enabled == 1 )
472     {
473         /* While PSA Crypto has an API for multipart
474          * operations, we currently don't make it
475          * accessible through the cipher layer. */
476         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
477     }
478 #endif /* MBEDTLS_USE_PSA_CRYPTO */
479 
480 #if defined(MBEDTLS_GCM_C)
481     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
482     {
483         return( mbedtls_gcm_update_ad( (mbedtls_gcm_context *) ctx->cipher_ctx,
484                                        ad, ad_len ) );
485     }
486 #endif
487 
488 #if defined(MBEDTLS_CHACHAPOLY_C)
489     if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
490     {
491         int result;
492         mbedtls_chachapoly_mode_t mode;
493 
494         mode = ( ctx->operation == MBEDTLS_ENCRYPT )
495                 ? MBEDTLS_CHACHAPOLY_ENCRYPT
496                 : MBEDTLS_CHACHAPOLY_DECRYPT;
497 
498         result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
499                                                         ctx->iv,
500                                                         mode );
501         if ( result != 0 )
502             return( result );
503 
504         return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
505                                                ad, ad_len ) );
506     }
507 #endif
508 
509     return( 0 );
510 }
511 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
512 
mbedtls_cipher_update(mbedtls_cipher_context_t * ctx,const unsigned char * input,size_t ilen,unsigned char * output,size_t * olen)513 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
514                    size_t ilen, unsigned char *output, size_t *olen )
515 {
516     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
517     size_t block_size;
518 
519     CIPHER_VALIDATE_RET( ctx != NULL );
520     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
521     CIPHER_VALIDATE_RET( output != NULL );
522     CIPHER_VALIDATE_RET( olen != NULL );
523     if( ctx->cipher_info == NULL )
524         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
525 
526 #if defined(MBEDTLS_USE_PSA_CRYPTO)
527     if( ctx->psa_enabled == 1 )
528     {
529         /* While PSA Crypto has an API for multipart
530          * operations, we currently don't make it
531          * accessible through the cipher layer. */
532         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
533     }
534 #endif /* MBEDTLS_USE_PSA_CRYPTO */
535 
536     *olen = 0;
537     block_size = mbedtls_cipher_get_block_size( ctx );
538     if ( 0 == block_size )
539     {
540         return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
541     }
542 
543     if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB )
544     {
545         if( ilen != block_size )
546             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
547 
548         *olen = ilen;
549 
550         if( 0 != ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,
551                     ctx->operation, input, output ) ) )
552         {
553             return( ret );
554         }
555 
556         return( 0 );
557     }
558 
559 #if defined(MBEDTLS_GCM_C)
560     if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM )
561     {
562         return( mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx,
563                                     input, ilen,
564                                     output, ilen, olen ) );
565     }
566 #endif
567 
568 #if defined(MBEDTLS_CCM_C)
569     if( ctx->cipher_info->mode == MBEDTLS_MODE_CCM_STAR_NO_TAG )
570     {
571         return( mbedtls_ccm_update( (mbedtls_ccm_context *) ctx->cipher_ctx,
572                                     input, ilen,
573                                     output, ilen, olen ) );
574     }
575 #endif
576 
577 #if defined(MBEDTLS_CHACHAPOLY_C)
578     if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )
579     {
580         *olen = ilen;
581         return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
582                                            ilen, input, output ) );
583     }
584 #endif
585 
586     if( input == output &&
587        ( ctx->unprocessed_len != 0 || ilen % block_size ) )
588     {
589         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
590     }
591 
592 #if defined(MBEDTLS_CIPHER_MODE_CBC)
593     if( ctx->cipher_info->mode == MBEDTLS_MODE_CBC )
594     {
595         size_t copy_len = 0;
596 
597         /*
598          * If there is not enough data for a full block, cache it.
599          */
600         if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&
601                 ilen <= block_size - ctx->unprocessed_len ) ||
602             ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&
603                 ilen < block_size - ctx->unprocessed_len ) ||
604              ( ctx->operation == MBEDTLS_ENCRYPT &&
605                 ilen < block_size - ctx->unprocessed_len ) )
606         {
607             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
608                     ilen );
609 
610             ctx->unprocessed_len += ilen;
611             return( 0 );
612         }
613 
614         /*
615          * Process cached data first
616          */
617         if( 0 != ctx->unprocessed_len )
618         {
619             copy_len = block_size - ctx->unprocessed_len;
620 
621             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
622                     copy_len );
623 
624             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
625                     ctx->operation, block_size, ctx->iv,
626                     ctx->unprocessed_data, output ) ) )
627             {
628                 return( ret );
629             }
630 
631             *olen += block_size;
632             output += block_size;
633             ctx->unprocessed_len = 0;
634 
635             input += copy_len;
636             ilen -= copy_len;
637         }
638 
639         /*
640          * Cache final, incomplete block
641          */
642         if( 0 != ilen )
643         {
644             /* Encryption: only cache partial blocks
645              * Decryption w/ padding: always keep at least one whole block
646              * Decryption w/o padding: only cache partial blocks
647              */
648             copy_len = ilen % block_size;
649             if( copy_len == 0 &&
650                 ctx->operation == MBEDTLS_DECRYPT &&
651                 NULL != ctx->add_padding)
652             {
653                 copy_len = block_size;
654             }
655 
656             memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
657                     copy_len );
658 
659             ctx->unprocessed_len += copy_len;
660             ilen -= copy_len;
661         }
662 
663         /*
664          * Process remaining full blocks
665          */
666         if( ilen )
667         {
668             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
669                     ctx->operation, ilen, ctx->iv, input, output ) ) )
670             {
671                 return( ret );
672             }
673 
674             *olen += ilen;
675         }
676 
677         return( 0 );
678     }
679 #endif /* MBEDTLS_CIPHER_MODE_CBC */
680 
681 #if defined(MBEDTLS_CIPHER_MODE_CFB)
682     if( ctx->cipher_info->mode == MBEDTLS_MODE_CFB )
683     {
684         if( 0 != ( ret = ctx->cipher_info->base->cfb_func( ctx->cipher_ctx,
685                 ctx->operation, ilen, &ctx->unprocessed_len, ctx->iv,
686                 input, output ) ) )
687         {
688             return( ret );
689         }
690 
691         *olen = ilen;
692 
693         return( 0 );
694     }
695 #endif /* MBEDTLS_CIPHER_MODE_CFB */
696 
697 #if defined(MBEDTLS_CIPHER_MODE_OFB)
698     if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB )
699     {
700         if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx,
701                 ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) )
702         {
703             return( ret );
704         }
705 
706         *olen = ilen;
707 
708         return( 0 );
709     }
710 #endif /* MBEDTLS_CIPHER_MODE_OFB */
711 
712 #if defined(MBEDTLS_CIPHER_MODE_CTR)
713     if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR )
714     {
715         if( 0 != ( ret = ctx->cipher_info->base->ctr_func( ctx->cipher_ctx,
716                 ilen, &ctx->unprocessed_len, ctx->iv,
717                 ctx->unprocessed_data, input, output ) ) )
718         {
719             return( ret );
720         }
721 
722         *olen = ilen;
723 
724         return( 0 );
725     }
726 #endif /* MBEDTLS_CIPHER_MODE_CTR */
727 
728 #if defined(MBEDTLS_CIPHER_MODE_XTS)
729     if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS )
730     {
731         if( ctx->unprocessed_len > 0 ) {
732             /* We can only process an entire data unit at a time. */
733             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
734         }
735 
736         ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx,
737                 ctx->operation, ilen, ctx->iv, input, output );
738         if( ret != 0 )
739         {
740             return( ret );
741         }
742 
743         *olen = ilen;
744 
745         return( 0 );
746     }
747 #endif /* MBEDTLS_CIPHER_MODE_XTS */
748 
749 #if defined(MBEDTLS_CIPHER_MODE_STREAM)
750     if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM )
751     {
752         if( 0 != ( ret = ctx->cipher_info->base->stream_func( ctx->cipher_ctx,
753                                                     ilen, input, output ) ) )
754         {
755             return( ret );
756         }
757 
758         *olen = ilen;
759 
760         return( 0 );
761     }
762 #endif /* MBEDTLS_CIPHER_MODE_STREAM */
763 
764     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
765 }
766 
767 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
768 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
769 /*
770  * PKCS7 (and PKCS5) padding: fill with ll bytes, with ll = padding_len
771  */
add_pkcs_padding(unsigned char * output,size_t output_len,size_t data_len)772 static void add_pkcs_padding( unsigned char *output, size_t output_len,
773         size_t data_len )
774 {
775     size_t padding_len = output_len - data_len;
776     unsigned char i;
777 
778     for( i = 0; i < padding_len; i++ )
779         output[data_len + i] = (unsigned char) padding_len;
780 }
781 
get_pkcs_padding(unsigned char * input,size_t input_len,size_t * data_len)782 static int get_pkcs_padding( unsigned char *input, size_t input_len,
783         size_t *data_len )
784 {
785     size_t i, pad_idx;
786     unsigned char padding_len, bad = 0;
787 
788     if( NULL == input || NULL == data_len )
789         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
790 
791     padding_len = input[input_len - 1];
792     *data_len = input_len - padding_len;
793 
794     /* Avoid logical || since it results in a branch */
795     bad |= padding_len > input_len;
796     bad |= padding_len == 0;
797 
798     /* The number of bytes checked must be independent of padding_len,
799      * so pick input_len, which is usually 8 or 16 (one block) */
800     pad_idx = input_len - padding_len;
801     for( i = 0; i < input_len; i++ )
802         bad |= ( input[i] ^ padding_len ) * ( i >= pad_idx );
803 
804     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
805 }
806 #endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
807 
808 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
809 /*
810  * One and zeros padding: fill with 80 00 ... 00
811  */
add_one_and_zeros_padding(unsigned char * output,size_t output_len,size_t data_len)812 static void add_one_and_zeros_padding( unsigned char *output,
813                                        size_t output_len, size_t data_len )
814 {
815     size_t padding_len = output_len - data_len;
816     unsigned char i = 0;
817 
818     output[data_len] = 0x80;
819     for( i = 1; i < padding_len; i++ )
820         output[data_len + i] = 0x00;
821 }
822 
get_one_and_zeros_padding(unsigned char * input,size_t input_len,size_t * data_len)823 static int get_one_and_zeros_padding( unsigned char *input, size_t input_len,
824                                       size_t *data_len )
825 {
826     size_t i;
827     unsigned char done = 0, prev_done, bad;
828 
829     if( NULL == input || NULL == data_len )
830         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
831 
832     bad = 0x80;
833     *data_len = 0;
834     for( i = input_len; i > 0; i-- )
835     {
836         prev_done = done;
837         done |= ( input[i - 1] != 0 );
838         *data_len |= ( i - 1 ) * ( done != prev_done );
839         bad ^= input[i - 1] * ( done != prev_done );
840     }
841 
842     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
843 
844 }
845 #endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */
846 
847 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
848 /*
849  * Zeros and len padding: fill with 00 ... 00 ll, where ll is padding length
850  */
add_zeros_and_len_padding(unsigned char * output,size_t output_len,size_t data_len)851 static void add_zeros_and_len_padding( unsigned char *output,
852                                        size_t output_len, size_t data_len )
853 {
854     size_t padding_len = output_len - data_len;
855     unsigned char i = 0;
856 
857     for( i = 1; i < padding_len; i++ )
858         output[data_len + i - 1] = 0x00;
859     output[output_len - 1] = (unsigned char) padding_len;
860 }
861 
get_zeros_and_len_padding(unsigned char * input,size_t input_len,size_t * data_len)862 static int get_zeros_and_len_padding( unsigned char *input, size_t input_len,
863                                       size_t *data_len )
864 {
865     size_t i, pad_idx;
866     unsigned char padding_len, bad = 0;
867 
868     if( NULL == input || NULL == data_len )
869         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
870 
871     padding_len = input[input_len - 1];
872     *data_len = input_len - padding_len;
873 
874     /* Avoid logical || since it results in a branch */
875     bad |= padding_len > input_len;
876     bad |= padding_len == 0;
877 
878     /* The number of bytes checked must be independent of padding_len */
879     pad_idx = input_len - padding_len;
880     for( i = 0; i < input_len - 1; i++ )
881         bad |= input[i] * ( i >= pad_idx );
882 
883     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
884 }
885 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */
886 
887 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
888 /*
889  * Zero padding: fill with 00 ... 00
890  */
add_zeros_padding(unsigned char * output,size_t output_len,size_t data_len)891 static void add_zeros_padding( unsigned char *output,
892                                size_t output_len, size_t data_len )
893 {
894     size_t i;
895 
896     for( i = data_len; i < output_len; i++ )
897         output[i] = 0x00;
898 }
899 
get_zeros_padding(unsigned char * input,size_t input_len,size_t * data_len)900 static int get_zeros_padding( unsigned char *input, size_t input_len,
901                               size_t *data_len )
902 {
903     size_t i;
904     unsigned char done = 0, prev_done;
905 
906     if( NULL == input || NULL == data_len )
907         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
908 
909     *data_len = 0;
910     for( i = input_len; i > 0; i-- )
911     {
912         prev_done = done;
913         done |= ( input[i-1] != 0 );
914         *data_len |= i * ( done != prev_done );
915     }
916 
917     return( 0 );
918 }
919 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS */
920 
921 /*
922  * No padding: don't pad :)
923  *
924  * There is no add_padding function (check for NULL in mbedtls_cipher_finish)
925  * but a trivial get_padding function
926  */
get_no_padding(unsigned char * input,size_t input_len,size_t * data_len)927 static int get_no_padding( unsigned char *input, size_t input_len,
928                               size_t *data_len )
929 {
930     if( NULL == input || NULL == data_len )
931         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
932 
933     *data_len = input_len;
934 
935     return( 0 );
936 }
937 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
938 
mbedtls_cipher_finish(mbedtls_cipher_context_t * ctx,unsigned char * output,size_t * olen)939 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
940                    unsigned char *output, size_t *olen )
941 {
942     CIPHER_VALIDATE_RET( ctx != NULL );
943     CIPHER_VALIDATE_RET( output != NULL );
944     CIPHER_VALIDATE_RET( olen != NULL );
945     if( ctx->cipher_info == NULL )
946         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
947 
948 #if defined(MBEDTLS_USE_PSA_CRYPTO)
949     if( ctx->psa_enabled == 1 )
950     {
951         /* While PSA Crypto has an API for multipart
952          * operations, we currently don't make it
953          * accessible through the cipher layer. */
954         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
955     }
956 #endif /* MBEDTLS_USE_PSA_CRYPTO */
957 
958     *olen = 0;
959 
960     if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
961         MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
962         MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||
963         MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||
964         MBEDTLS_MODE_CCM_STAR_NO_TAG == ctx->cipher_info->mode ||
965         MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||
966         MBEDTLS_MODE_STREAM == ctx->cipher_info->mode )
967     {
968         return( 0 );
969     }
970 
971     if ( ( MBEDTLS_CIPHER_CHACHA20          == ctx->cipher_info->type ) ||
972          ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) )
973     {
974         return( 0 );
975     }
976 
977     if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode )
978     {
979         if( ctx->unprocessed_len != 0 )
980             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
981 
982         return( 0 );
983     }
984 
985 #if defined(MBEDTLS_CIPHER_MODE_CBC)
986     if( MBEDTLS_MODE_CBC == ctx->cipher_info->mode )
987     {
988         int ret = 0;
989 
990         if( MBEDTLS_ENCRYPT == ctx->operation )
991         {
992             /* check for 'no padding' mode */
993             if( NULL == ctx->add_padding )
994             {
995                 if( 0 != ctx->unprocessed_len )
996                     return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
997 
998                 return( 0 );
999             }
1000 
1001             ctx->add_padding( ctx->unprocessed_data, mbedtls_cipher_get_iv_size( ctx ),
1002                     ctx->unprocessed_len );
1003         }
1004         else if( mbedtls_cipher_get_block_size( ctx ) != ctx->unprocessed_len )
1005         {
1006             /*
1007              * For decrypt operations, expect a full block,
1008              * or an empty block if no padding
1009              */
1010             if( NULL == ctx->add_padding && 0 == ctx->unprocessed_len )
1011                 return( 0 );
1012 
1013             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
1014         }
1015 
1016         /* cipher block */
1017         if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
1018                 ctx->operation, mbedtls_cipher_get_block_size( ctx ), ctx->iv,
1019                 ctx->unprocessed_data, output ) ) )
1020         {
1021             return( ret );
1022         }
1023 
1024         /* Set output size for decryption */
1025         if( MBEDTLS_DECRYPT == ctx->operation )
1026             return( ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),
1027                                       olen ) );
1028 
1029         /* Set output size for encryption */
1030         *olen = mbedtls_cipher_get_block_size( ctx );
1031         return( 0 );
1032     }
1033 #else
1034     ((void) output);
1035 #endif /* MBEDTLS_CIPHER_MODE_CBC */
1036 
1037     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1038 }
1039 
1040 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
mbedtls_cipher_set_padding_mode(mbedtls_cipher_context_t * ctx,mbedtls_cipher_padding_t mode)1041 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx,
1042                                      mbedtls_cipher_padding_t mode )
1043 {
1044     CIPHER_VALIDATE_RET( ctx != NULL );
1045 
1046     if( NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode )
1047     {
1048         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1049     }
1050 
1051 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1052     if( ctx->psa_enabled == 1 )
1053     {
1054         /* While PSA Crypto knows about CBC padding
1055          * schemes, we currently don't make them
1056          * accessible through the cipher layer. */
1057         if( mode != MBEDTLS_PADDING_NONE )
1058             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1059 
1060         return( 0 );
1061     }
1062 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1063 
1064     switch( mode )
1065     {
1066 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
1067     case MBEDTLS_PADDING_PKCS7:
1068         ctx->add_padding = add_pkcs_padding;
1069         ctx->get_padding = get_pkcs_padding;
1070         break;
1071 #endif
1072 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
1073     case MBEDTLS_PADDING_ONE_AND_ZEROS:
1074         ctx->add_padding = add_one_and_zeros_padding;
1075         ctx->get_padding = get_one_and_zeros_padding;
1076         break;
1077 #endif
1078 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
1079     case MBEDTLS_PADDING_ZEROS_AND_LEN:
1080         ctx->add_padding = add_zeros_and_len_padding;
1081         ctx->get_padding = get_zeros_and_len_padding;
1082         break;
1083 #endif
1084 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
1085     case MBEDTLS_PADDING_ZEROS:
1086         ctx->add_padding = add_zeros_padding;
1087         ctx->get_padding = get_zeros_padding;
1088         break;
1089 #endif
1090     case MBEDTLS_PADDING_NONE:
1091         ctx->add_padding = NULL;
1092         ctx->get_padding = get_no_padding;
1093         break;
1094 
1095     default:
1096         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1097     }
1098 
1099     return( 0 );
1100 }
1101 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
1102 
1103 #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)1104 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
1105                       unsigned char *tag, size_t tag_len )
1106 {
1107     CIPHER_VALIDATE_RET( ctx != NULL );
1108     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1109     if( ctx->cipher_info == NULL )
1110         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1111 
1112     if( MBEDTLS_ENCRYPT != ctx->operation )
1113         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1114 
1115 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1116     if( ctx->psa_enabled == 1 )
1117     {
1118         /* While PSA Crypto has an API for multipart
1119          * operations, we currently don't make it
1120          * accessible through the cipher layer. */
1121         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1122     }
1123 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1124 
1125 #if defined(MBEDTLS_GCM_C)
1126     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1127     {
1128         size_t output_length;
1129         /* The code here doesn't yet support alternative implementations
1130          * that can delay up to a block of output. */
1131         return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx,
1132                                     NULL, 0, &output_length,
1133                                     tag, tag_len ) );
1134     }
1135 #endif
1136 
1137 #if defined(MBEDTLS_CHACHAPOLY_C)
1138     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1139     {
1140         /* Don't allow truncated MAC for Poly1305 */
1141         if ( tag_len != 16U )
1142             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1143 
1144         return( mbedtls_chachapoly_finish(
1145                     (mbedtls_chachapoly_context*) ctx->cipher_ctx, tag ) );
1146     }
1147 #endif
1148 
1149     return( 0 );
1150 }
1151 
mbedtls_cipher_check_tag(mbedtls_cipher_context_t * ctx,const unsigned char * tag,size_t tag_len)1152 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
1153                       const unsigned char *tag, size_t tag_len )
1154 {
1155     unsigned char check_tag[16];
1156     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1157 
1158     CIPHER_VALIDATE_RET( ctx != NULL );
1159     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1160     if( ctx->cipher_info == NULL )
1161         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1162 
1163     if( MBEDTLS_DECRYPT != ctx->operation )
1164     {
1165         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1166     }
1167 
1168 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1169     if( ctx->psa_enabled == 1 )
1170     {
1171         /* While PSA Crypto has an API for multipart
1172          * operations, we currently don't make it
1173          * accessible through the cipher layer. */
1174         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1175     }
1176 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1177 
1178     /* Status to return on a non-authenticated algorithm. It would make sense
1179      * to return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT or perhaps
1180      * MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA, but at the time I write this our
1181      * unit tests assume 0. */
1182     ret = 0;
1183 
1184 #if defined(MBEDTLS_GCM_C)
1185     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1186     {
1187         size_t output_length;
1188         /* The code here doesn't yet support alternative implementations
1189          * that can delay up to a block of output. */
1190 
1191         if( tag_len > sizeof( check_tag ) )
1192             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1193 
1194         if( 0 != ( ret = mbedtls_gcm_finish(
1195                        (mbedtls_gcm_context *) ctx->cipher_ctx,
1196                        NULL, 0, &output_length,
1197                        check_tag, tag_len ) ) )
1198         {
1199             return( ret );
1200         }
1201 
1202         /* Check the tag in "constant-time" */
1203         if( mbedtls_ct_memcmp( tag, check_tag, tag_len ) != 0 )
1204         {
1205             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1206             goto exit;
1207         }
1208     }
1209 #endif /* MBEDTLS_GCM_C */
1210 
1211 #if defined(MBEDTLS_CHACHAPOLY_C)
1212     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1213     {
1214         /* Don't allow truncated MAC for Poly1305 */
1215         if ( tag_len != sizeof( check_tag ) )
1216             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1217 
1218         ret = mbedtls_chachapoly_finish(
1219             (mbedtls_chachapoly_context*) ctx->cipher_ctx, check_tag );
1220         if ( ret != 0 )
1221         {
1222             return( ret );
1223         }
1224 
1225         /* Check the tag in "constant-time" */
1226         if( mbedtls_ct_memcmp( tag, check_tag, tag_len ) != 0 )
1227         {
1228             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1229             goto exit;
1230         }
1231     }
1232 #endif /* MBEDTLS_CHACHAPOLY_C */
1233 
1234 exit:
1235     mbedtls_platform_zeroize( check_tag, tag_len );
1236     return( ret );
1237 }
1238 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
1239 
1240 /*
1241  * Packet-oriented wrapper for non-AEAD modes
1242  */
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)1243 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
1244                   const unsigned char *iv, size_t iv_len,
1245                   const unsigned char *input, size_t ilen,
1246                   unsigned char *output, size_t *olen )
1247 {
1248     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1249     size_t finish_olen;
1250 
1251     CIPHER_VALIDATE_RET( ctx != NULL );
1252     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1253     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1254     CIPHER_VALIDATE_RET( output != NULL );
1255     CIPHER_VALIDATE_RET( olen != NULL );
1256 
1257 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1258     if( ctx->psa_enabled == 1 )
1259     {
1260         /* As in the non-PSA case, we don't check that
1261          * a key has been set. If not, the key slot will
1262          * still be in its default state of 0, which is
1263          * guaranteed to be invalid, hence the PSA-call
1264          * below will gracefully fail. */
1265         mbedtls_cipher_context_psa * const cipher_psa =
1266             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1267 
1268         psa_status_t status;
1269         psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1270         size_t part_len;
1271 
1272         if( ctx->operation == MBEDTLS_DECRYPT )
1273         {
1274             status = psa_cipher_decrypt_setup( &cipher_op,
1275                                                cipher_psa->slot,
1276                                                cipher_psa->alg );
1277         }
1278         else if( ctx->operation == MBEDTLS_ENCRYPT )
1279         {
1280             status = psa_cipher_encrypt_setup( &cipher_op,
1281                                                cipher_psa->slot,
1282                                                cipher_psa->alg );
1283         }
1284         else
1285             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1286 
1287         /* In the following, we can immediately return on an error,
1288          * because the PSA Crypto API guarantees that cipher operations
1289          * are terminated by unsuccessful calls to psa_cipher_update(),
1290          * and by any call to psa_cipher_finish(). */
1291         if( status != PSA_SUCCESS )
1292             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1293 
1294         if( ctx->cipher_info->mode != MBEDTLS_MODE_ECB )
1295         {
1296             status = psa_cipher_set_iv( &cipher_op, iv, iv_len );
1297             if( status != PSA_SUCCESS )
1298                 return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1299         }
1300 
1301         status = psa_cipher_update( &cipher_op,
1302                                     input, ilen,
1303                                     output, ilen, olen );
1304         if( status != PSA_SUCCESS )
1305             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1306 
1307         status = psa_cipher_finish( &cipher_op,
1308                                     output + *olen, ilen - *olen,
1309                                     &part_len );
1310         if( status != PSA_SUCCESS )
1311             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1312 
1313         *olen += part_len;
1314         return( 0 );
1315     }
1316 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1317 
1318     if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 )
1319         return( ret );
1320 
1321     if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 )
1322         return( ret );
1323 
1324     if( ( ret = mbedtls_cipher_update( ctx, input, ilen,
1325                                        output, olen ) ) != 0 )
1326         return( ret );
1327 
1328     if( ( ret = mbedtls_cipher_finish( ctx, output + *olen,
1329                                        &finish_olen ) ) != 0 )
1330         return( ret );
1331 
1332     *olen += finish_olen;
1333 
1334     return( 0 );
1335 }
1336 
1337 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1338 /*
1339  * Packet-oriented encryption for AEAD modes: internal function used by
1340  * mbedtls_cipher_auth_encrypt_ext().
1341  */
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)1342 static int mbedtls_cipher_aead_encrypt( mbedtls_cipher_context_t *ctx,
1343                          const unsigned char *iv, size_t iv_len,
1344                          const unsigned char *ad, size_t ad_len,
1345                          const unsigned char *input, size_t ilen,
1346                          unsigned char *output, size_t *olen,
1347                          unsigned char *tag, size_t tag_len )
1348 {
1349 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1350     if( ctx->psa_enabled == 1 )
1351     {
1352         /* As in the non-PSA case, we don't check that
1353          * a key has been set. If not, the key slot will
1354          * still be in its default state of 0, which is
1355          * guaranteed to be invalid, hence the PSA-call
1356          * below will gracefully fail. */
1357         mbedtls_cipher_context_psa * const cipher_psa =
1358             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1359 
1360         psa_status_t status;
1361 
1362         /* PSA Crypto API always writes the authentication tag
1363          * at the end of the encrypted message. */
1364         if( output == NULL || tag != output + ilen )
1365             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1366 
1367         status = psa_aead_encrypt( cipher_psa->slot,
1368                                    cipher_psa->alg,
1369                                    iv, iv_len,
1370                                    ad, ad_len,
1371                                    input, ilen,
1372                                    output, ilen + tag_len, olen );
1373         if( status != PSA_SUCCESS )
1374             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1375 
1376         *olen -= tag_len;
1377         return( 0 );
1378     }
1379 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1380 
1381 #if defined(MBEDTLS_GCM_C)
1382     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1383     {
1384         *olen = ilen;
1385         return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT,
1386                                            ilen, iv, iv_len, ad, ad_len,
1387                                            input, output, tag_len, tag ) );
1388     }
1389 #endif /* MBEDTLS_GCM_C */
1390 #if defined(MBEDTLS_CCM_C)
1391     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1392     {
1393         *olen = ilen;
1394         return( mbedtls_ccm_encrypt_and_tag( ctx->cipher_ctx, ilen,
1395                                      iv, iv_len, ad, ad_len, input, output,
1396                                      tag, tag_len ) );
1397     }
1398 #endif /* MBEDTLS_CCM_C */
1399 #if defined(MBEDTLS_CHACHAPOLY_C)
1400     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1401     {
1402         /* ChachaPoly has fixed length nonce and MAC (tag) */
1403         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1404              ( tag_len != 16U ) )
1405         {
1406             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1407         }
1408 
1409         *olen = ilen;
1410         return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx,
1411                                 ilen, iv, ad, ad_len, input, output, tag ) );
1412     }
1413 #endif /* MBEDTLS_CHACHAPOLY_C */
1414 
1415     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1416 }
1417 
1418 /*
1419  * Packet-oriented encryption for AEAD modes: internal function used by
1420  * mbedtls_cipher_auth_encrypt_ext().
1421  */
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)1422 static int mbedtls_cipher_aead_decrypt( mbedtls_cipher_context_t *ctx,
1423                          const unsigned char *iv, size_t iv_len,
1424                          const unsigned char *ad, size_t ad_len,
1425                          const unsigned char *input, size_t ilen,
1426                          unsigned char *output, size_t *olen,
1427                          const unsigned char *tag, size_t tag_len )
1428 {
1429 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1430     if( ctx->psa_enabled == 1 )
1431     {
1432         /* As in the non-PSA case, we don't check that
1433          * a key has been set. If not, the key slot will
1434          * still be in its default state of 0, which is
1435          * guaranteed to be invalid, hence the PSA-call
1436          * below will gracefully fail. */
1437         mbedtls_cipher_context_psa * const cipher_psa =
1438             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1439 
1440         psa_status_t status;
1441 
1442         /* PSA Crypto API always writes the authentication tag
1443          * at the end of the encrypted message. */
1444         if( input == NULL || tag != input + ilen )
1445             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1446 
1447         status = psa_aead_decrypt( cipher_psa->slot,
1448                                    cipher_psa->alg,
1449                                    iv, iv_len,
1450                                    ad, ad_len,
1451                                    input, ilen + tag_len,
1452                                    output, ilen, olen );
1453         if( status == PSA_ERROR_INVALID_SIGNATURE )
1454             return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
1455         else if( status != PSA_SUCCESS )
1456             return( MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED );
1457 
1458         return( 0 );
1459     }
1460 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1461 
1462 #if defined(MBEDTLS_GCM_C)
1463     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1464     {
1465         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1466 
1467         *olen = ilen;
1468         ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen,
1469                                 iv, iv_len, ad, ad_len,
1470                                 tag, tag_len, input, output );
1471 
1472         if( ret == MBEDTLS_ERR_GCM_AUTH_FAILED )
1473             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1474 
1475         return( ret );
1476     }
1477 #endif /* MBEDTLS_GCM_C */
1478 #if defined(MBEDTLS_CCM_C)
1479     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1480     {
1481         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1482 
1483         *olen = ilen;
1484         ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen,
1485                                 iv, iv_len, ad, ad_len,
1486                                 input, output, tag, tag_len );
1487 
1488         if( ret == MBEDTLS_ERR_CCM_AUTH_FAILED )
1489             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1490 
1491         return( ret );
1492     }
1493 #endif /* MBEDTLS_CCM_C */
1494 #if defined(MBEDTLS_CHACHAPOLY_C)
1495     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1496     {
1497         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1498 
1499         /* ChachaPoly has fixed length nonce and MAC (tag) */
1500         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1501              ( tag_len != 16U ) )
1502         {
1503             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1504         }
1505 
1506         *olen = ilen;
1507         ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen,
1508                                 iv, ad, ad_len, tag, input, output );
1509 
1510         if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED )
1511             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1512 
1513         return( ret );
1514     }
1515 #endif /* MBEDTLS_CHACHAPOLY_C */
1516 
1517     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1518 }
1519 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1520 
1521 #if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C)
1522 /*
1523  * Packet-oriented encryption for AEAD/NIST_KW: public function.
1524  */
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)1525 int mbedtls_cipher_auth_encrypt_ext( mbedtls_cipher_context_t *ctx,
1526                          const unsigned char *iv, size_t iv_len,
1527                          const unsigned char *ad, size_t ad_len,
1528                          const unsigned char *input, size_t ilen,
1529                          unsigned char *output, size_t output_len,
1530                          size_t *olen, size_t tag_len )
1531 {
1532     CIPHER_VALIDATE_RET( ctx != NULL );
1533     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1534     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1535     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1536     CIPHER_VALIDATE_RET( output != NULL );
1537     CIPHER_VALIDATE_RET( olen != NULL );
1538 
1539 #if defined(MBEDTLS_NIST_KW_C)
1540     if(
1541 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1542         ctx->psa_enabled == 0 &&
1543 #endif
1544         ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1545           MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) )
1546     {
1547         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1548                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1549 
1550         /* There is no iv, tag or ad associated with KW and KWP,
1551          * so these length should be 0 as documented. */
1552         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1553             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1554 
1555         (void) iv;
1556         (void) ad;
1557 
1558         return( mbedtls_nist_kw_wrap( ctx->cipher_ctx, mode, input, ilen,
1559                                       output, olen, output_len ) );
1560     }
1561 #endif /* MBEDTLS_NIST_KW_C */
1562 
1563 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1564     /* AEAD case: check length before passing on to shared function */
1565     if( output_len < ilen + tag_len )
1566         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1567 
1568     int ret = mbedtls_cipher_aead_encrypt( ctx, iv, iv_len, ad, ad_len,
1569                                        input, ilen, output, olen,
1570                                        output + ilen, tag_len );
1571     *olen += tag_len;
1572     return( ret );
1573 #else
1574     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1575 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1576 }
1577 
1578 /*
1579  * Packet-oriented decryption for AEAD/NIST_KW: public function.
1580  */
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)1581 int mbedtls_cipher_auth_decrypt_ext( mbedtls_cipher_context_t *ctx,
1582                          const unsigned char *iv, size_t iv_len,
1583                          const unsigned char *ad, size_t ad_len,
1584                          const unsigned char *input, size_t ilen,
1585                          unsigned char *output, size_t output_len,
1586                          size_t *olen, size_t tag_len )
1587 {
1588     CIPHER_VALIDATE_RET( ctx != NULL );
1589     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1590     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1591     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1592     CIPHER_VALIDATE_RET( output_len == 0 || output != NULL );
1593     CIPHER_VALIDATE_RET( olen != NULL );
1594 
1595 #if defined(MBEDTLS_NIST_KW_C)
1596     if(
1597 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1598         ctx->psa_enabled == 0 &&
1599 #endif
1600         ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1601           MBEDTLS_MODE_KWP == ctx->cipher_info->mode ) )
1602     {
1603         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1604                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1605 
1606         /* There is no iv, tag or ad associated with KW and KWP,
1607          * so these length should be 0 as documented. */
1608         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1609             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1610 
1611         (void) iv;
1612         (void) ad;
1613 
1614         return( mbedtls_nist_kw_unwrap( ctx->cipher_ctx, mode, input, ilen,
1615                                         output, olen, output_len ) );
1616     }
1617 #endif /* MBEDTLS_NIST_KW_C */
1618 
1619 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1620     /* AEAD case: check length before passing on to shared function */
1621     if( ilen < tag_len || output_len < ilen - tag_len )
1622         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1623 
1624     return( mbedtls_cipher_aead_decrypt( ctx, iv, iv_len, ad, ad_len,
1625                                          input, ilen - tag_len, output, olen,
1626                                          input + ilen - tag_len, tag_len ) );
1627 #else
1628     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1629 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1630 }
1631 #endif /* MBEDTLS_CIPHER_MODE_AEAD || MBEDTLS_NIST_KW_C */
1632 
1633 #endif /* MBEDTLS_CIPHER_C */
1634