Optimize out unneeded up_ref/free of EVP_CIPHER
[openssl.git] / crypto / evp / evp_enc.c
1 /*
2  * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <stdio.h>
14 #include <limits.h>
15 #include <assert.h>
16 #include <openssl/evp.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #ifndef FIPS_MODULE
20 # include <openssl/engine.h>
21 #endif
22 #include <openssl/params.h>
23 #include <openssl/core_names.h>
24 #include "internal/cryptlib.h"
25 #include "internal/provider.h"
26 #include "internal/core.h"
27 #include "internal/safe_math.h"
28 #include "crypto/evp.h"
29 #include "evp_local.h"
30
31 OSSL_SAFE_MATH_SIGNED(int, int)
32
33 int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx)
34 {
35     if (ctx == NULL)
36         return 1;
37
38     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
39         goto legacy;
40
41     if (ctx->algctx != NULL) {
42         if (ctx->cipher->freectx != NULL)
43             ctx->cipher->freectx(ctx->algctx);
44         ctx->algctx = NULL;
45     }
46     if (ctx->fetched_cipher != NULL)
47         EVP_CIPHER_free(ctx->fetched_cipher);
48     memset(ctx, 0, sizeof(*ctx));
49     ctx->iv_len = -1;
50
51     return 1;
52
53     /* Remove legacy code below when legacy support is removed. */
54  legacy:
55
56     if (ctx->cipher != NULL) {
57         if (ctx->cipher->cleanup && !ctx->cipher->cleanup(ctx))
58             return 0;
59         /* Cleanse cipher context data */
60         if (ctx->cipher_data && ctx->cipher->ctx_size)
61             OPENSSL_cleanse(ctx->cipher_data, ctx->cipher->ctx_size);
62     }
63     OPENSSL_free(ctx->cipher_data);
64 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
65     ENGINE_finish(ctx->engine);
66 #endif
67     memset(ctx, 0, sizeof(*ctx));
68     ctx->iv_len = -1;
69     return 1;
70 }
71
72 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
73 {
74     EVP_CIPHER_CTX *ctx;
75
76     ctx = OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX));
77     if (ctx == NULL)
78         return NULL;
79
80     ctx->iv_len = -1;
81     return ctx;
82 }
83
84 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
85 {
86     if (ctx == NULL)
87         return;
88     EVP_CIPHER_CTX_reset(ctx);
89     OPENSSL_free(ctx);
90 }
91
92 static int evp_cipher_init_internal(EVP_CIPHER_CTX *ctx,
93                                     const EVP_CIPHER *cipher,
94                                     ENGINE *impl, const unsigned char *key,
95                                     const unsigned char *iv, int enc,
96                                     const OSSL_PARAM params[])
97 {
98     int n;
99 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
100     ENGINE *tmpimpl = NULL;
101 #endif
102
103     /*
104      * enc == 1 means we are encrypting.
105      * enc == 0 means we are decrypting.
106      * enc == -1 means, use the previously initialised value for encrypt/decrypt
107      */
108     if (enc == -1) {
109         enc = ctx->encrypt;
110     } else {
111         if (enc)
112             enc = 1;
113         ctx->encrypt = enc;
114     }
115
116     if (cipher == NULL && ctx->cipher == NULL) {
117         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
118         return 0;
119     }
120
121     /* Code below to be removed when legacy support is dropped. */
122
123 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
124     /*
125      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
126      * this context may already have an ENGINE! Try to avoid releasing the
127      * previous handle, re-querying for an ENGINE, and having a
128      * reinitialisation, when it may all be unnecessary.
129      */
130     if (ctx->engine && ctx->cipher
131         && (cipher == NULL || cipher->nid == ctx->cipher->nid))
132         goto skip_to_init;
133
134     if (cipher != NULL && impl == NULL) {
135          /* Ask if an ENGINE is reserved for this job */
136         tmpimpl = ENGINE_get_cipher_engine(cipher->nid);
137     }
138 #endif
139
140     /*
141      * If there are engines involved then we should use legacy handling for now.
142      */
143     if (ctx->engine != NULL
144 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
145             || tmpimpl != NULL
146 #endif
147             || impl != NULL
148             || (cipher != NULL && cipher->origin == EVP_ORIG_METH)
149             || (cipher == NULL && ctx->cipher != NULL
150                                && ctx->cipher->origin == EVP_ORIG_METH)) {
151         if (ctx->cipher == ctx->fetched_cipher)
152             ctx->cipher = NULL;
153         EVP_CIPHER_free(ctx->fetched_cipher);
154         ctx->fetched_cipher = NULL;
155         goto legacy;
156     }
157     /*
158      * Ensure a context left lying around from last time is cleared
159      * (legacy code)
160      */
161     if (cipher != NULL && ctx->cipher != NULL) {
162         if (ctx->cipher->cleanup != NULL && !ctx->cipher->cleanup(ctx))
163             return 0;
164         OPENSSL_clear_free(ctx->cipher_data, ctx->cipher->ctx_size);
165         ctx->cipher_data = NULL;
166     }
167
168     /* Start of non-legacy code below */
169
170     /* Ensure a context left lying around from last time is cleared */
171     if (cipher != NULL && ctx->cipher != NULL) {
172         unsigned long flags = ctx->flags;
173
174         EVP_CIPHER_CTX_reset(ctx);
175         /* Restore encrypt and flags */
176         ctx->encrypt = enc;
177         ctx->flags = flags;
178     }
179
180     if (cipher == NULL)
181         cipher = ctx->cipher;
182
183     if (cipher->prov == NULL) {
184 #ifdef FIPS_MODULE
185         /* We only do explicit fetches inside the FIPS module */
186         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
187         return 0;
188 #else
189         EVP_CIPHER *provciph =
190             EVP_CIPHER_fetch(NULL,
191                              cipher->nid == NID_undef ? "NULL"
192                                                       : OBJ_nid2sn(cipher->nid),
193                              "");
194
195         if (provciph == NULL)
196             return 0;
197         cipher = provciph;
198         EVP_CIPHER_free(ctx->fetched_cipher);
199         ctx->fetched_cipher = provciph;
200 #endif
201     }
202
203     if (!ossl_assert(cipher->prov != NULL)) {
204         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
205         return 0;
206     }
207
208     if (cipher != ctx->fetched_cipher) {
209         if (!EVP_CIPHER_up_ref((EVP_CIPHER *)cipher)) {
210             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
211             return 0;
212         }
213         EVP_CIPHER_free(ctx->fetched_cipher);
214         /* Coverity false positive, the reference counting is confusing it */
215         /* coverity[use_after_free] */
216         ctx->fetched_cipher = (EVP_CIPHER *)cipher;
217     }
218     ctx->cipher = cipher;
219     if (ctx->algctx == NULL) {
220         ctx->algctx = ctx->cipher->newctx(ossl_provider_ctx(cipher->prov));
221         if (ctx->algctx == NULL) {
222             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
223             return 0;
224         }
225     }
226
227     if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
228         /*
229          * If this ctx was already set up for no padding then we need to tell
230          * the new cipher about it.
231          */
232         if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
233             return 0;
234     }
235
236     if (enc) {
237         if (ctx->cipher->einit == NULL) {
238             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
239             return 0;
240         }
241
242         return ctx->cipher->einit(ctx->algctx,
243                                   key,
244                                   key == NULL ? 0
245                                               : EVP_CIPHER_CTX_get_key_length(ctx),
246                                   iv,
247                                   iv == NULL ? 0
248                                              : EVP_CIPHER_CTX_get_iv_length(ctx),
249                                   params);
250     }
251
252     if (ctx->cipher->dinit == NULL) {
253         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
254         return 0;
255     }
256
257     return ctx->cipher->dinit(ctx->algctx,
258                               key,
259                               key == NULL ? 0
260                                           : EVP_CIPHER_CTX_get_key_length(ctx),
261                               iv,
262                               iv == NULL ? 0
263                                          : EVP_CIPHER_CTX_get_iv_length(ctx),
264                                   params);
265
266     /* Code below to be removed when legacy support is dropped. */
267  legacy:
268
269     if (cipher != NULL) {
270         /*
271          * Ensure a context left lying around from last time is cleared (we
272          * previously attempted to avoid this if the same ENGINE and
273          * EVP_CIPHER could be used).
274          */
275         if (ctx->cipher) {
276             unsigned long flags = ctx->flags;
277             EVP_CIPHER_CTX_reset(ctx);
278             /* Restore encrypt and flags */
279             ctx->encrypt = enc;
280             ctx->flags = flags;
281         }
282 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
283         if (impl != NULL) {
284             if (!ENGINE_init(impl)) {
285                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
286                 return 0;
287             }
288         } else {
289             impl = tmpimpl;
290         }
291         if (impl != NULL) {
292             /* There's an ENGINE for this job ... (apparently) */
293             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
294
295             if (c == NULL) {
296                 /*
297                  * One positive side-effect of US's export control history,
298                  * is that we should at least be able to avoid using US
299                  * misspellings of "initialisation"?
300                  */
301                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
302                 return 0;
303             }
304             /* We'll use the ENGINE's private cipher definition */
305             cipher = c;
306             /*
307              * Store the ENGINE functional reference so we know 'cipher' came
308              * from an ENGINE and we need to release it when done.
309              */
310             ctx->engine = impl;
311         } else {
312             ctx->engine = NULL;
313         }
314 #endif
315
316         ctx->cipher = cipher;
317         if (ctx->cipher->ctx_size) {
318             ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size);
319             if (ctx->cipher_data == NULL) {
320                 ctx->cipher = NULL;
321                 return 0;
322             }
323         } else {
324             ctx->cipher_data = NULL;
325         }
326         ctx->key_len = cipher->key_len;
327         /* Preserve wrap enable flag, zero everything else */
328         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
329         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
330             if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL) <= 0) {
331                 ctx->cipher = NULL;
332                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
333                 return 0;
334             }
335         }
336     }
337 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
338  skip_to_init:
339 #endif
340     if (ctx->cipher == NULL)
341         return 0;
342
343     /* we assume block size is a power of 2 in *cryptUpdate */
344     OPENSSL_assert(ctx->cipher->block_size == 1
345                    || ctx->cipher->block_size == 8
346                    || ctx->cipher->block_size == 16);
347
348     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
349         && EVP_CIPHER_CTX_get_mode(ctx) == EVP_CIPH_WRAP_MODE) {
350         ERR_raise(ERR_LIB_EVP, EVP_R_WRAP_MODE_NOT_ALLOWED);
351         return 0;
352     }
353
354     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
355                 & EVP_CIPH_CUSTOM_IV) == 0) {
356         switch (EVP_CIPHER_CTX_get_mode(ctx)) {
357
358         case EVP_CIPH_STREAM_CIPHER:
359         case EVP_CIPH_ECB_MODE:
360             break;
361
362         case EVP_CIPH_CFB_MODE:
363         case EVP_CIPH_OFB_MODE:
364
365             ctx->num = 0;
366             /* fall-through */
367
368         case EVP_CIPH_CBC_MODE:
369             n = EVP_CIPHER_CTX_get_iv_length(ctx);
370             if (n < 0 || n > (int)sizeof(ctx->iv)) {
371                 ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH);
372                 return 0;
373             }
374             if (iv != NULL)
375                 memcpy(ctx->oiv, iv, n);
376             memcpy(ctx->iv, ctx->oiv, n);
377             break;
378
379         case EVP_CIPH_CTR_MODE:
380             ctx->num = 0;
381             /* Don't reuse IV for CTR mode */
382             if (iv != NULL) {
383                 n = EVP_CIPHER_CTX_get_iv_length(ctx);
384                 if (n <= 0 || n > (int)sizeof(ctx->iv)) {
385                     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_IV_LENGTH);
386                     return 0;
387                 }
388                 memcpy(ctx->iv, iv, n);
389             }
390             break;
391
392         default:
393             return 0;
394         }
395     }
396
397     if (key != NULL || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
398         if (!ctx->cipher->init(ctx, key, iv, enc))
399             return 0;
400     }
401     ctx->buf_len = 0;
402     ctx->final_used = 0;
403     ctx->block_mask = ctx->cipher->block_size - 1;
404     return 1;
405 }
406
407 int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
408                        const unsigned char *key, const unsigned char *iv,
409                        int enc, const OSSL_PARAM params[])
410 {
411     return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, params);
412 }
413
414 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
415                    const unsigned char *key, const unsigned char *iv, int enc)
416 {
417     if (cipher != NULL)
418         EVP_CIPHER_CTX_reset(ctx);
419     return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, NULL);
420 }
421
422 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
423                       ENGINE *impl, const unsigned char *key,
424                       const unsigned char *iv, int enc)
425 {
426     return evp_cipher_init_internal(ctx, cipher, impl, key, iv, enc, NULL);
427 }
428
429 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
430                      const unsigned char *in, int inl)
431 {
432     if (ctx->encrypt)
433         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
434     else
435         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
436 }
437
438 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
439 {
440     if (ctx->encrypt)
441         return EVP_EncryptFinal_ex(ctx, out, outl);
442     else
443         return EVP_DecryptFinal_ex(ctx, out, outl);
444 }
445
446 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
447 {
448     if (ctx->encrypt)
449         return EVP_EncryptFinal(ctx, out, outl);
450     else
451         return EVP_DecryptFinal(ctx, out, outl);
452 }
453
454 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
455                     const unsigned char *key, const unsigned char *iv)
456 {
457     return EVP_CipherInit(ctx, cipher, key, iv, 1);
458 }
459
460 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
461                        ENGINE *impl, const unsigned char *key,
462                        const unsigned char *iv)
463 {
464     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
465 }
466
467 int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
468                         const unsigned char *key, const unsigned char *iv,
469                         const OSSL_PARAM params[])
470 {
471     return EVP_CipherInit_ex2(ctx, cipher, key, iv, 1, params);
472 }
473
474 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
475                     const unsigned char *key, const unsigned char *iv)
476 {
477     return EVP_CipherInit(ctx, cipher, key, iv, 0);
478 }
479
480 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
481                        ENGINE *impl, const unsigned char *key,
482                        const unsigned char *iv)
483 {
484     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
485 }
486
487 int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
488                         const unsigned char *key, const unsigned char *iv,
489                         const OSSL_PARAM params[])
490 {
491     return EVP_CipherInit_ex2(ctx, cipher, key, iv, 0, params);
492 }
493
494 /*
495  * According to the letter of standard difference between pointers
496  * is specified to be valid only within same object. This makes
497  * it formally challenging to determine if input and output buffers
498  * are not partially overlapping with standard pointer arithmetic.
499  */
500 #ifdef PTRDIFF_T
501 # undef PTRDIFF_T
502 #endif
503 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
504 /*
505  * Then we have VMS that distinguishes itself by adhering to
506  * sizeof(size_t)==4 even in 64-bit builds, which means that
507  * difference between two pointers might be truncated to 32 bits.
508  * In the context one can even wonder how comparison for
509  * equality is implemented. To be on the safe side we adhere to
510  * PTRDIFF_T even for comparison for equality.
511  */
512 # define PTRDIFF_T uint64_t
513 #else
514 # define PTRDIFF_T size_t
515 #endif
516
517 int ossl_is_partially_overlapping(const void *ptr1, const void *ptr2, int len)
518 {
519     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
520     /*
521      * Check for partially overlapping buffers. [Binary logical
522      * operations are used instead of boolean to minimize number
523      * of conditional branches.]
524      */
525     int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
526                                                 (diff > (0 - (PTRDIFF_T)len)));
527
528     return overlapped;
529 }
530
531 static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
532                                     unsigned char *out, int *outl,
533                                     const unsigned char *in, int inl)
534 {
535     int i, j, bl, cmpl = inl;
536
537     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
538         cmpl = safe_div_round_up_int(cmpl, 8, NULL);
539
540     bl = ctx->cipher->block_size;
541
542     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
543         /* If block size > 1 then the cipher will have to do this check */
544         if (bl == 1 && ossl_is_partially_overlapping(out, in, cmpl)) {
545             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
546             return 0;
547         }
548
549         i = ctx->cipher->do_cipher(ctx, out, in, inl);
550         if (i < 0)
551             return 0;
552         else
553             *outl = i;
554         return 1;
555     }
556
557     if (inl <= 0) {
558         *outl = 0;
559         return inl == 0;
560     }
561     if (ossl_is_partially_overlapping(out + ctx->buf_len, in, cmpl)) {
562         ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
563         return 0;
564     }
565
566     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
567         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
568             *outl = inl;
569             return 1;
570         } else {
571             *outl = 0;
572             return 0;
573         }
574     }
575     i = ctx->buf_len;
576     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
577     if (i != 0) {
578         if (bl - i > inl) {
579             memcpy(&(ctx->buf[i]), in, inl);
580             ctx->buf_len += inl;
581             *outl = 0;
582             return 1;
583         } else {
584             j = bl - i;
585
586             /*
587              * Once we've processed the first j bytes from in, the amount of
588              * data left that is a multiple of the block length is:
589              * (inl - j) & ~(bl - 1)
590              * We must ensure that this amount of data, plus the one block that
591              * we process from ctx->buf does not exceed INT_MAX
592              */
593             if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) {
594                 ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW);
595                 return 0;
596             }
597             memcpy(&(ctx->buf[i]), in, j);
598             inl -= j;
599             in += j;
600             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
601                 return 0;
602             out += bl;
603             *outl = bl;
604         }
605     } else
606         *outl = 0;
607     i = inl & (bl - 1);
608     inl -= i;
609     if (inl > 0) {
610         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
611             return 0;
612         *outl += inl;
613     }
614
615     if (i != 0)
616         memcpy(ctx->buf, &(in[inl]), i);
617     ctx->buf_len = i;
618     return 1;
619 }
620
621
622 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
623                       const unsigned char *in, int inl)
624 {
625     int ret;
626     size_t soutl, inl_ = (size_t)inl;
627     int blocksize;
628
629     if (likely(outl != NULL)) {
630         *outl = 0;
631     } else {
632         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
633         return 0;
634     }
635
636     /* Prevent accidental use of decryption context when encrypting */
637     if (unlikely(!ctx->encrypt)) {
638         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
639         return 0;
640     }
641
642     if (unlikely(ctx->cipher == NULL)) {
643         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
644         return 0;
645     }
646
647     if (unlikely(ctx->cipher->prov == NULL))
648         goto legacy;
649
650     blocksize = ctx->cipher->block_size;
651
652     if (unlikely(ctx->cipher->cupdate == NULL || blocksize < 1)) {
653         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
654         return 0;
655     }
656
657     ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl,
658                                inl_ + (size_t)(blocksize == 1 ? 0 : blocksize),
659                                in, inl_);
660
661     if (likely(ret)) {
662         if (soutl > INT_MAX) {
663             ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
664             return 0;
665         }
666         *outl = soutl;
667     }
668
669     return ret;
670
671     /* Code below to be removed when legacy support is dropped. */
672  legacy:
673
674     return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
675 }
676
677 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
678 {
679     int ret;
680     ret = EVP_EncryptFinal_ex(ctx, out, outl);
681     return ret;
682 }
683
684 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
685 {
686     int n, ret;
687     unsigned int i, b, bl;
688     size_t soutl;
689     int blocksize;
690
691     if (outl != NULL) {
692         *outl = 0;
693     } else {
694         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
695         return 0;
696     }
697
698     /* Prevent accidental use of decryption context when encrypting */
699     if (!ctx->encrypt) {
700         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
701         return 0;
702     }
703
704     if (ctx->cipher == NULL) {
705         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
706         return 0;
707     }
708     if (ctx->cipher->prov == NULL)
709         goto legacy;
710
711     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
712
713     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
714         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
715         return 0;
716     }
717
718     ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl,
719                               blocksize == 1 ? 0 : blocksize);
720
721     if (ret) {
722         if (soutl > INT_MAX) {
723             ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
724             return 0;
725         }
726         *outl = soutl;
727     }
728
729     return ret;
730
731     /* Code below to be removed when legacy support is dropped. */
732  legacy:
733
734     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
735         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
736         if (ret < 0)
737             return 0;
738         else
739             *outl = ret;
740         return 1;
741     }
742
743     b = ctx->cipher->block_size;
744     OPENSSL_assert(b <= sizeof(ctx->buf));
745     if (b == 1) {
746         *outl = 0;
747         return 1;
748     }
749     bl = ctx->buf_len;
750     if (ctx->flags & EVP_CIPH_NO_PADDING) {
751         if (bl) {
752             ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
753             return 0;
754         }
755         *outl = 0;
756         return 1;
757     }
758
759     n = b - bl;
760     for (i = bl; i < b; i++)
761         ctx->buf[i] = n;
762     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
763
764     if (ret)
765         *outl = b;
766
767     return ret;
768 }
769
770 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
771                       const unsigned char *in, int inl)
772 {
773     int fix_len, cmpl = inl, ret;
774     unsigned int b;
775     size_t soutl, inl_ = (size_t)inl;
776     int blocksize;
777
778     if (likely(outl != NULL)) {
779         *outl = 0;
780     } else {
781         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
782         return 0;
783     }
784
785     /* Prevent accidental use of encryption context when decrypting */
786     if (unlikely(ctx->encrypt)) {
787         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
788         return 0;
789     }
790
791     if (unlikely(ctx->cipher == NULL)) {
792         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
793         return 0;
794     }
795     if (unlikely(ctx->cipher->prov == NULL))
796         goto legacy;
797
798     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
799
800     if (unlikely(ctx->cipher->cupdate == NULL || blocksize < 1)) {
801         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
802         return 0;
803     }
804     ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl,
805                                inl_ + (size_t)(blocksize == 1 ? 0 : blocksize),
806                                in, inl_);
807
808     if (likely(ret)) {
809         if (soutl > INT_MAX) {
810             ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
811             return 0;
812         }
813         *outl = soutl;
814     }
815
816     return ret;
817
818     /* Code below to be removed when legacy support is dropped. */
819  legacy:
820
821     b = ctx->cipher->block_size;
822
823     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
824         cmpl = safe_div_round_up_int(cmpl, 8, NULL);
825
826     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
827         if (b == 1 && ossl_is_partially_overlapping(out, in, cmpl)) {
828             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
829             return 0;
830         }
831
832         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
833         if (fix_len < 0) {
834             *outl = 0;
835             return 0;
836         } else
837             *outl = fix_len;
838         return 1;
839     }
840
841     if (inl <= 0) {
842         *outl = 0;
843         return inl == 0;
844     }
845
846     if (ctx->flags & EVP_CIPH_NO_PADDING)
847         return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
848
849     OPENSSL_assert(b <= sizeof(ctx->final));
850
851     if (ctx->final_used) {
852         /* see comment about PTRDIFF_T comparison above */
853         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
854             || ossl_is_partially_overlapping(out, in, b)) {
855             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
856             return 0;
857         }
858         /*
859          * final_used is only ever set if buf_len is 0. Therefore the maximum
860          * length output we will ever see from evp_EncryptDecryptUpdate is
861          * the maximum multiple of the block length that is <= inl, or just:
862          * inl & ~(b - 1)
863          * Since final_used has been set then the final output length is:
864          * (inl & ~(b - 1)) + b
865          * This must never exceed INT_MAX
866          */
867         if ((inl & ~(b - 1)) > INT_MAX - b) {
868             ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW);
869             return 0;
870         }
871         memcpy(out, ctx->final, b);
872         out += b;
873         fix_len = 1;
874     } else
875         fix_len = 0;
876
877     if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
878         return 0;
879
880     /*
881      * if we have 'decrypted' a multiple of block size, make sure we have a
882      * copy of this last block
883      */
884     if (b > 1 && !ctx->buf_len) {
885         *outl -= b;
886         ctx->final_used = 1;
887         memcpy(ctx->final, &out[*outl], b);
888     } else
889         ctx->final_used = 0;
890
891     if (fix_len)
892         *outl += b;
893
894     return 1;
895 }
896
897 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
898 {
899     int ret;
900     ret = EVP_DecryptFinal_ex(ctx, out, outl);
901     return ret;
902 }
903
904 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
905 {
906     int i, n;
907     unsigned int b;
908     size_t soutl;
909     int ret;
910     int blocksize;
911
912     if (outl != NULL) {
913         *outl = 0;
914     } else {
915         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
916         return 0;
917     }
918
919     /* Prevent accidental use of encryption context when decrypting */
920     if (ctx->encrypt) {
921         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
922         return 0;
923     }
924
925     if (ctx->cipher == NULL) {
926         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
927         return 0;
928     }
929
930     if (ctx->cipher->prov == NULL)
931         goto legacy;
932
933     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
934
935     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
936         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
937         return 0;
938     }
939
940     ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl,
941                               blocksize == 1 ? 0 : blocksize);
942
943     if (ret) {
944         if (soutl > INT_MAX) {
945             ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
946             return 0;
947         }
948         *outl = soutl;
949     }
950
951     return ret;
952
953     /* Code below to be removed when legacy support is dropped. */
954  legacy:
955
956     *outl = 0;
957     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
958         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
959         if (i < 0)
960             return 0;
961         else
962             *outl = i;
963         return 1;
964     }
965
966     b = ctx->cipher->block_size;
967     if (ctx->flags & EVP_CIPH_NO_PADDING) {
968         if (ctx->buf_len) {
969             ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
970             return 0;
971         }
972         *outl = 0;
973         return 1;
974     }
975     if (b > 1) {
976         if (ctx->buf_len || !ctx->final_used) {
977             ERR_raise(ERR_LIB_EVP, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
978             return 0;
979         }
980         OPENSSL_assert(b <= sizeof(ctx->final));
981
982         /*
983          * The following assumes that the ciphertext has been authenticated.
984          * Otherwise it provides a padding oracle.
985          */
986         n = ctx->final[b - 1];
987         if (n == 0 || n > (int)b) {
988             ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT);
989             return 0;
990         }
991         for (i = 0; i < n; i++) {
992             if (ctx->final[--b] != n) {
993                 ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT);
994                 return 0;
995             }
996         }
997         n = ctx->cipher->block_size - n;
998         for (i = 0; i < n; i++)
999             out[i] = ctx->final[i];
1000         *outl = n;
1001     } else
1002         *outl = 0;
1003     return 1;
1004 }
1005
1006 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
1007 {
1008     if (c->cipher->prov != NULL) {
1009         int ok;
1010         OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1011         size_t len;
1012
1013         if (EVP_CIPHER_CTX_get_key_length(c) == keylen)
1014             return 1;
1015
1016         /* Check the cipher actually understands this parameter */
1017         if (OSSL_PARAM_locate_const(EVP_CIPHER_settable_ctx_params(c->cipher),
1018                                     OSSL_CIPHER_PARAM_KEYLEN) == NULL) {
1019             ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH);
1020             return 0;
1021         }
1022
1023         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &len);
1024         if (!OSSL_PARAM_set_int(params, keylen))
1025             return 0;
1026         ok = evp_do_ciph_ctx_setparams(c->cipher, c->algctx, params);
1027         if (ok <= 0)
1028             return 0;
1029         c->key_len = keylen;
1030         return 1;
1031     }
1032
1033     /* Code below to be removed when legacy support is dropped. */
1034
1035     /*
1036      * Note there have never been any built-in ciphers that define this flag
1037      * since it was first introduced.
1038      */
1039     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
1040         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
1041     if (EVP_CIPHER_CTX_get_key_length(c) == keylen)
1042         return 1;
1043     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
1044         c->key_len = keylen;
1045         return 1;
1046     }
1047     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH);
1048     return 0;
1049 }
1050
1051 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
1052 {
1053     int ok;
1054     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1055     unsigned int pd = pad;
1056
1057     if (pad)
1058         ctx->flags &= ~EVP_CIPH_NO_PADDING;
1059     else
1060         ctx->flags |= EVP_CIPH_NO_PADDING;
1061
1062     if (ctx->cipher != NULL && ctx->cipher->prov == NULL)
1063         return 1;
1064     params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_PADDING, &pd);
1065     ok = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1066
1067     return ok != 0;
1068 }
1069
1070 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1071 {
1072     int ret = EVP_CTRL_RET_UNSUPPORTED;
1073     int set_params = 1;
1074     size_t sz = arg;
1075     unsigned int i;
1076     OSSL_PARAM params[4] = {
1077         OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
1078     };
1079
1080     if (ctx == NULL || ctx->cipher == NULL) {
1081         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
1082         return 0;
1083     }
1084
1085     if (ctx->cipher->prov == NULL)
1086         goto legacy;
1087
1088     switch (type) {
1089     case EVP_CTRL_SET_KEY_LENGTH:
1090         if (arg < 0)
1091             return 0;
1092         if (ctx->key_len == arg)
1093             /* Skip calling into provider if unchanged. */
1094             return 1;
1095         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &sz);
1096         ctx->key_len = -1;
1097         break;
1098     case EVP_CTRL_RAND_KEY:      /* Used by DES */
1099         set_params = 0;
1100         params[0] =
1101             OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_RANDOM_KEY,
1102                                               ptr, sz);
1103         break;
1104
1105     case EVP_CTRL_INIT:
1106         /*
1107          * EVP_CTRL_INIT is purely legacy, no provider counterpart.
1108          * As a matter of fact, this should be dead code, but some caller
1109          * might still do a direct control call with this command, so...
1110          * Legacy methods return 1 except for exceptional circumstances, so
1111          * we do the same here to not be disruptive.
1112          */
1113         return 1;
1114     case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS: /* Used by DASYNC */
1115     default:
1116         goto end;
1117     case EVP_CTRL_AEAD_SET_IVLEN:
1118         if (arg < 0)
1119             return 0;
1120         if (ctx->iv_len == arg)
1121             /* Skip calling into provider if unchanged. */
1122             return 1;
1123         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz);
1124         ctx->iv_len = -1;
1125         break;
1126     case EVP_CTRL_CCM_SET_L:
1127         if (arg < 2 || arg > 8)
1128             return 0;
1129         sz = 15 - arg;
1130         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz);
1131         ctx->iv_len = -1;
1132         break;
1133     case EVP_CTRL_AEAD_SET_IV_FIXED:
1134         params[0] = OSSL_PARAM_construct_octet_string(
1135                         OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED, ptr, sz);
1136         break;
1137     case EVP_CTRL_GCM_IV_GEN:
1138         set_params = 0;
1139         if (arg < 0)
1140             sz = 0; /* special case that uses the iv length */
1141         params[0] = OSSL_PARAM_construct_octet_string(
1142                         OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN, ptr, sz);
1143         break;
1144     case EVP_CTRL_GCM_SET_IV_INV:
1145         if (arg < 0)
1146             return 0;
1147         params[0] = OSSL_PARAM_construct_octet_string(
1148                         OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV, ptr, sz);
1149         break;
1150     case EVP_CTRL_GET_RC5_ROUNDS:
1151         set_params = 0; /* Fall thru */
1152     case EVP_CTRL_SET_RC5_ROUNDS:
1153         if (arg < 0)
1154             return 0;
1155         i = (unsigned int)arg;
1156         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_ROUNDS, &i);
1157         break;
1158     case EVP_CTRL_SET_SPEED:
1159         if (arg < 0)
1160             return 0;
1161         i = (unsigned int)arg;
1162         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_SPEED, &i);
1163         break;
1164     case EVP_CTRL_AEAD_GET_TAG:
1165         set_params = 0; /* Fall thru */
1166     case EVP_CTRL_AEAD_SET_TAG:
1167         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
1168                                                       ptr, sz);
1169         break;
1170     case EVP_CTRL_AEAD_TLS1_AAD:
1171         /* This one does a set and a get - since it returns a size */
1172         params[0] =
1173             OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
1174                                               ptr, sz);
1175         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1176         if (ret <= 0)
1177             goto end;
1178         params[0] =
1179             OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD, &sz);
1180         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1181         if (ret <= 0)
1182             goto end;
1183         return sz;
1184 #ifndef OPENSSL_NO_RC2
1185     case EVP_CTRL_GET_RC2_KEY_BITS:
1186         set_params = 0; /* Fall thru */
1187     case EVP_CTRL_SET_RC2_KEY_BITS:
1188         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_RC2_KEYBITS, &sz);
1189         break;
1190 #endif /* OPENSSL_NO_RC2 */
1191 #if !defined(OPENSSL_NO_MULTIBLOCK)
1192     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
1193         params[0] = OSSL_PARAM_construct_size_t(
1194                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT, &sz);
1195         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1196         if (ret <= 0)
1197             return 0;
1198
1199         params[0] = OSSL_PARAM_construct_size_t(
1200                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE, &sz);
1201         params[1] = OSSL_PARAM_construct_end();
1202         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1203         if (ret <= 0)
1204             return 0;
1205         return sz;
1206     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: {
1207         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1208             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1209
1210         if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
1211             return 0;
1212
1213         params[0] = OSSL_PARAM_construct_octet_string(
1214                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD, (void*)p->inp, p->len);
1215         params[1] = OSSL_PARAM_construct_uint(
1216                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1217         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1218         if (ret <= 0)
1219             return ret;
1220         /* Retrieve the return values changed by the set */
1221         params[0] = OSSL_PARAM_construct_size_t(
1222                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN, &sz);
1223         params[1] = OSSL_PARAM_construct_uint(
1224                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1225         params[2] = OSSL_PARAM_construct_end();
1226         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1227         if (ret <= 0)
1228             return 0;
1229         return sz;
1230     }
1231     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: {
1232         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1233             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1234
1235         params[0] = OSSL_PARAM_construct_octet_string(
1236                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC, p->out, p->len);
1237
1238         params[1] = OSSL_PARAM_construct_octet_string(
1239                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN, (void*)p->inp,
1240                 p->len);
1241         params[2] = OSSL_PARAM_construct_uint(
1242                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1243         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1244         if (ret <= 0)
1245             return ret;
1246         params[0] = OSSL_PARAM_construct_size_t(
1247                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN, &sz);
1248         params[1] = OSSL_PARAM_construct_end();
1249         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1250         if (ret <= 0)
1251             return 0;
1252         return sz;
1253     }
1254 #endif /* OPENSSL_NO_MULTIBLOCK */
1255     case EVP_CTRL_AEAD_SET_MAC_KEY:
1256         if (arg < 0)
1257             return -1;
1258         params[0] = OSSL_PARAM_construct_octet_string(
1259                 OSSL_CIPHER_PARAM_AEAD_MAC_KEY, ptr, sz);
1260         break;
1261     }
1262
1263     if (set_params)
1264         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1265     else
1266         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1267     goto end;
1268
1269     /* Code below to be removed when legacy support is dropped. */
1270 legacy:
1271     if (ctx->cipher->ctrl == NULL) {
1272         ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED);
1273         return 0;
1274     }
1275
1276     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
1277
1278  end:
1279     if (ret == EVP_CTRL_RET_UNSUPPORTED) {
1280         ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
1281         return 0;
1282     }
1283     return ret;
1284 }
1285
1286 int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[])
1287 {
1288     if (cipher != NULL && cipher->get_params != NULL)
1289         return cipher->get_params(params);
1290     return 0;
1291 }
1292
1293 int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[])
1294 {
1295     int r = 0;
1296     const OSSL_PARAM *p;
1297
1298     if (ctx->cipher != NULL && ctx->cipher->set_ctx_params != NULL) {
1299         r = ctx->cipher->set_ctx_params(ctx->algctx, params);
1300         if (r > 0) {
1301             p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_KEYLEN);
1302             if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->key_len)) {
1303                 r = 0;
1304                 ctx->key_len = -1;
1305             }
1306         }
1307         if (r > 0) {
1308             p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_IVLEN);
1309             if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->iv_len)) {
1310                 r = 0;
1311                 ctx->iv_len = -1;
1312             }
1313         }
1314     }
1315     return r;
1316 }
1317
1318 int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[])
1319 {
1320     if (ctx->cipher != NULL && ctx->cipher->get_ctx_params != NULL)
1321         return ctx->cipher->get_ctx_params(ctx->algctx, params);
1322     return 0;
1323 }
1324
1325 const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher)
1326 {
1327     if (cipher != NULL && cipher->gettable_params != NULL)
1328         return cipher->gettable_params(
1329                    ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher)));
1330     return NULL;
1331 }
1332
1333 const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher)
1334 {
1335     void *provctx;
1336
1337     if (cipher != NULL && cipher->settable_ctx_params != NULL) {
1338         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher));
1339         return cipher->settable_ctx_params(NULL, provctx);
1340     }
1341     return NULL;
1342 }
1343
1344 const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher)
1345 {
1346     void *provctx;
1347
1348     if (cipher != NULL && cipher->gettable_ctx_params != NULL) {
1349         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher));
1350         return cipher->gettable_ctx_params(NULL, provctx);
1351     }
1352     return NULL;
1353 }
1354
1355 const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *cctx)
1356 {
1357     void *alg;
1358
1359     if (cctx != NULL && cctx->cipher->settable_ctx_params != NULL) {
1360         alg = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher));
1361         return cctx->cipher->settable_ctx_params(cctx->algctx, alg);
1362     }
1363     return NULL;
1364 }
1365
1366 const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *cctx)
1367 {
1368     void *provctx;
1369
1370     if (cctx != NULL && cctx->cipher->gettable_ctx_params != NULL) {
1371         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher));
1372         return cctx->cipher->gettable_ctx_params(cctx->algctx, provctx);
1373     }
1374     return NULL;
1375 }
1376
1377 #ifndef FIPS_MODULE
1378 static OSSL_LIB_CTX *EVP_CIPHER_CTX_get_libctx(EVP_CIPHER_CTX *ctx)
1379 {
1380     const EVP_CIPHER *cipher = ctx->cipher;
1381     const OSSL_PROVIDER *prov;
1382
1383     if (cipher == NULL)
1384         return NULL;
1385
1386     prov = EVP_CIPHER_get0_provider(cipher);
1387     return ossl_provider_libctx(prov);
1388 }
1389 #endif
1390
1391 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
1392 {
1393     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
1394         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
1395
1396 #ifdef FIPS_MODULE
1397     return 0;
1398 #else
1399     {
1400         int kl;
1401         OSSL_LIB_CTX *libctx = EVP_CIPHER_CTX_get_libctx(ctx);
1402
1403         kl = EVP_CIPHER_CTX_get_key_length(ctx);
1404         if (kl <= 0 || RAND_priv_bytes_ex(libctx, key, kl, 0) <= 0)
1405             return 0;
1406         return 1;
1407     }
1408 #endif /* FIPS_MODULE */
1409 }
1410
1411 EVP_CIPHER_CTX *EVP_CIPHER_CTX_dup(const EVP_CIPHER_CTX *in)
1412 {
1413     EVP_CIPHER_CTX *out = EVP_CIPHER_CTX_new();
1414
1415     if (out != NULL && !EVP_CIPHER_CTX_copy(out, in)) {
1416         EVP_CIPHER_CTX_free(out);
1417         out = NULL;
1418     }
1419     return out;
1420 }
1421
1422 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
1423 {
1424     if ((in == NULL) || (in->cipher == NULL)) {
1425         ERR_raise(ERR_LIB_EVP, EVP_R_INPUT_NOT_INITIALIZED);
1426         return 0;
1427     }
1428
1429     if (in->cipher->prov == NULL)
1430         goto legacy;
1431
1432     if (in->cipher->dupctx == NULL) {
1433         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
1434         return 0;
1435     }
1436
1437     EVP_CIPHER_CTX_reset(out);
1438
1439     *out = *in;
1440     out->algctx = NULL;
1441
1442     if (in->fetched_cipher != NULL && !EVP_CIPHER_up_ref(in->fetched_cipher)) {
1443         out->fetched_cipher = NULL;
1444         return 0;
1445     }
1446
1447     out->algctx = in->cipher->dupctx(in->algctx);
1448     if (out->algctx == NULL) {
1449         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
1450         return 0;
1451     }
1452
1453     return 1;
1454
1455     /* Code below to be removed when legacy support is dropped. */
1456  legacy:
1457
1458 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
1459     /* Make sure it's safe to copy a cipher context using an ENGINE */
1460     if (in->engine && !ENGINE_init(in->engine)) {
1461         ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
1462         return 0;
1463     }
1464 #endif
1465
1466     EVP_CIPHER_CTX_reset(out);
1467     memcpy(out, in, sizeof(*out));
1468
1469     if (in->cipher_data && in->cipher->ctx_size) {
1470         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
1471         if (out->cipher_data == NULL) {
1472             out->cipher = NULL;
1473             return 0;
1474         }
1475         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
1476     }
1477
1478     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
1479         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
1480             out->cipher = NULL;
1481             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
1482             return 0;
1483         }
1484     return 1;
1485 }
1486
1487 EVP_CIPHER *evp_cipher_new(void)
1488 {
1489     EVP_CIPHER *cipher = OPENSSL_zalloc(sizeof(EVP_CIPHER));
1490
1491     if (cipher != NULL && !CRYPTO_NEW_REF(&cipher->refcnt, 1)) {
1492         OPENSSL_free(cipher);
1493         return NULL;
1494     }
1495     return cipher;
1496 }
1497
1498 /*
1499  * FIPS module note: since internal fetches will be entirely
1500  * provider based, we know that none of its code depends on legacy
1501  * NIDs or any functionality that use them.
1502  */
1503 #ifndef FIPS_MODULE
1504 /* After removal of legacy support get rid of the need for legacy NIDs */
1505 static void set_legacy_nid(const char *name, void *vlegacy_nid)
1506 {
1507     int nid;
1508     int *legacy_nid = vlegacy_nid;
1509     /*
1510      * We use lowest level function to get the associated method, because
1511      * higher level functions such as EVP_get_cipherbyname() have changed
1512      * to look at providers too.
1513      */
1514     const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH);
1515
1516     if (*legacy_nid == -1)       /* We found a clash already */
1517         return;
1518     if (legacy_method == NULL)
1519         return;
1520     nid = EVP_CIPHER_get_nid(legacy_method);
1521     if (*legacy_nid != NID_undef && *legacy_nid != nid) {
1522         *legacy_nid = -1;
1523         return;
1524     }
1525     *legacy_nid = nid;
1526 }
1527 #endif
1528
1529 static void *evp_cipher_from_algorithm(const int name_id,
1530                                        const OSSL_ALGORITHM *algodef,
1531                                        OSSL_PROVIDER *prov)
1532 {
1533     const OSSL_DISPATCH *fns = algodef->implementation;
1534     EVP_CIPHER *cipher = NULL;
1535     int fnciphcnt = 0, fnctxcnt = 0;
1536
1537     if ((cipher = evp_cipher_new()) == NULL) {
1538         ERR_raise(ERR_LIB_EVP, ERR_R_EVP_LIB);
1539         return NULL;
1540     }
1541
1542 #ifndef FIPS_MODULE
1543     cipher->nid = NID_undef;
1544     if (!evp_names_do_all(prov, name_id, set_legacy_nid, &cipher->nid)
1545             || cipher->nid == -1) {
1546         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1547         EVP_CIPHER_free(cipher);
1548         return NULL;
1549     }
1550 #endif
1551
1552     cipher->name_id = name_id;
1553     if ((cipher->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) {
1554         EVP_CIPHER_free(cipher);
1555         return NULL;
1556     }
1557     cipher->description = algodef->algorithm_description;
1558
1559     for (; fns->function_id != 0; fns++) {
1560         switch (fns->function_id) {
1561         case OSSL_FUNC_CIPHER_NEWCTX:
1562             if (cipher->newctx != NULL)
1563                 break;
1564             cipher->newctx = OSSL_FUNC_cipher_newctx(fns);
1565             fnctxcnt++;
1566             break;
1567         case OSSL_FUNC_CIPHER_ENCRYPT_INIT:
1568             if (cipher->einit != NULL)
1569                 break;
1570             cipher->einit = OSSL_FUNC_cipher_encrypt_init(fns);
1571             fnciphcnt++;
1572             break;
1573         case OSSL_FUNC_CIPHER_DECRYPT_INIT:
1574             if (cipher->dinit != NULL)
1575                 break;
1576             cipher->dinit = OSSL_FUNC_cipher_decrypt_init(fns);
1577             fnciphcnt++;
1578             break;
1579         case OSSL_FUNC_CIPHER_UPDATE:
1580             if (cipher->cupdate != NULL)
1581                 break;
1582             cipher->cupdate = OSSL_FUNC_cipher_update(fns);
1583             fnciphcnt++;
1584             break;
1585         case OSSL_FUNC_CIPHER_FINAL:
1586             if (cipher->cfinal != NULL)
1587                 break;
1588             cipher->cfinal = OSSL_FUNC_cipher_final(fns);
1589             fnciphcnt++;
1590             break;
1591         case OSSL_FUNC_CIPHER_CIPHER:
1592             if (cipher->ccipher != NULL)
1593                 break;
1594             cipher->ccipher = OSSL_FUNC_cipher_cipher(fns);
1595             break;
1596         case OSSL_FUNC_CIPHER_FREECTX:
1597             if (cipher->freectx != NULL)
1598                 break;
1599             cipher->freectx = OSSL_FUNC_cipher_freectx(fns);
1600             fnctxcnt++;
1601             break;
1602         case OSSL_FUNC_CIPHER_DUPCTX:
1603             if (cipher->dupctx != NULL)
1604                 break;
1605             cipher->dupctx = OSSL_FUNC_cipher_dupctx(fns);
1606             break;
1607         case OSSL_FUNC_CIPHER_GET_PARAMS:
1608             if (cipher->get_params != NULL)
1609                 break;
1610             cipher->get_params = OSSL_FUNC_cipher_get_params(fns);
1611             break;
1612         case OSSL_FUNC_CIPHER_GET_CTX_PARAMS:
1613             if (cipher->get_ctx_params != NULL)
1614                 break;
1615             cipher->get_ctx_params = OSSL_FUNC_cipher_get_ctx_params(fns);
1616             break;
1617         case OSSL_FUNC_CIPHER_SET_CTX_PARAMS:
1618             if (cipher->set_ctx_params != NULL)
1619                 break;
1620             cipher->set_ctx_params = OSSL_FUNC_cipher_set_ctx_params(fns);
1621             break;
1622         case OSSL_FUNC_CIPHER_GETTABLE_PARAMS:
1623             if (cipher->gettable_params != NULL)
1624                 break;
1625             cipher->gettable_params = OSSL_FUNC_cipher_gettable_params(fns);
1626             break;
1627         case OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS:
1628             if (cipher->gettable_ctx_params != NULL)
1629                 break;
1630             cipher->gettable_ctx_params =
1631                 OSSL_FUNC_cipher_gettable_ctx_params(fns);
1632             break;
1633         case OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS:
1634             if (cipher->settable_ctx_params != NULL)
1635                 break;
1636             cipher->settable_ctx_params =
1637                 OSSL_FUNC_cipher_settable_ctx_params(fns);
1638             break;
1639         }
1640     }
1641     if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4)
1642             || (fnciphcnt == 0 && cipher->ccipher == NULL)
1643             || fnctxcnt != 2) {
1644         /*
1645          * In order to be a consistent set of functions we must have at least
1646          * a complete set of "encrypt" functions, or a complete set of "decrypt"
1647          * functions, or a single "cipher" function. In all cases we need both
1648          * the "newctx" and "freectx" functions.
1649          */
1650         EVP_CIPHER_free(cipher);
1651         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1652         return NULL;
1653     }
1654     cipher->prov = prov;
1655     if (prov != NULL)
1656         ossl_provider_up_ref(prov);
1657
1658     if (!evp_cipher_cache_constants(cipher)) {
1659         EVP_CIPHER_free(cipher);
1660         ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED);
1661         cipher = NULL;
1662     }
1663
1664     return cipher;
1665 }
1666
1667 static int evp_cipher_up_ref(void *cipher)
1668 {
1669     return EVP_CIPHER_up_ref(cipher);
1670 }
1671
1672 static void evp_cipher_free(void *cipher)
1673 {
1674     EVP_CIPHER_free(cipher);
1675 }
1676
1677 EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
1678                              const char *properties)
1679 {
1680     EVP_CIPHER *cipher =
1681         evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties,
1682                           evp_cipher_from_algorithm, evp_cipher_up_ref,
1683                           evp_cipher_free);
1684
1685     return cipher;
1686 }
1687
1688 int EVP_CIPHER_up_ref(EVP_CIPHER *cipher)
1689 {
1690     int ref = 0;
1691
1692     if (cipher->origin == EVP_ORIG_DYNAMIC)
1693         CRYPTO_UP_REF(&cipher->refcnt, &ref);
1694     return 1;
1695 }
1696
1697 void evp_cipher_free_int(EVP_CIPHER *cipher)
1698 {
1699     OPENSSL_free(cipher->type_name);
1700     ossl_provider_free(cipher->prov);
1701     CRYPTO_FREE_REF(&cipher->refcnt);
1702     OPENSSL_free(cipher);
1703 }
1704
1705 void EVP_CIPHER_free(EVP_CIPHER *cipher)
1706 {
1707     int i;
1708
1709     if (cipher == NULL || cipher->origin != EVP_ORIG_DYNAMIC)
1710         return;
1711
1712     CRYPTO_DOWN_REF(&cipher->refcnt, &i);
1713     if (i > 0)
1714         return;
1715     evp_cipher_free_int(cipher);
1716 }
1717
1718 void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
1719                                 void (*fn)(EVP_CIPHER *mac, void *arg),
1720                                 void *arg)
1721 {
1722     evp_generic_do_all(libctx, OSSL_OP_CIPHER,
1723                        (void (*)(void *, void *))fn, arg,
1724                        evp_cipher_from_algorithm, evp_cipher_up_ref,
1725                        evp_cipher_free);
1726 }