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