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