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