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