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