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