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