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