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