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