rand_drbg: remove RAND_DRBG.
[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_GET_IV:
975         set_params = 0;
976         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_IV,
977                                                       ptr, sz);
978         break;
979     case EVP_CTRL_AEAD_SET_IVLEN:
980         if (arg < 0)
981             return 0;
982         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz);
983         break;
984     case EVP_CTRL_AEAD_SET_IV_FIXED:
985         params[0] = OSSL_PARAM_construct_octet_string(
986                         OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED, ptr, sz);
987         break;
988     case EVP_CTRL_GCM_IV_GEN:
989         set_params = 0;
990         if (arg < 0)
991             sz = 0; /* special case that uses the iv length */
992         params[0] = OSSL_PARAM_construct_octet_string(
993                         OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN, ptr, sz);
994         break;
995     case EVP_CTRL_GCM_SET_IV_INV:
996         if (arg < 0)
997             return 0;
998         params[0] = OSSL_PARAM_construct_octet_string(
999                         OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV, ptr, sz);
1000         break;
1001     case EVP_CTRL_GET_RC5_ROUNDS:
1002         set_params = 0; /* Fall thru */
1003     case EVP_CTRL_SET_RC5_ROUNDS:
1004         if (arg < 0)
1005             return 0;
1006         i = (unsigned int)arg;
1007         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_ROUNDS, &i);
1008         break;
1009     case EVP_CTRL_SET_SPEED:
1010         if (arg < 0)
1011             return 0;
1012         i = (unsigned int)arg;
1013         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_SPEED, &i);
1014         break;
1015     case EVP_CTRL_AEAD_GET_TAG:
1016         set_params = 0; /* Fall thru */
1017     case EVP_CTRL_AEAD_SET_TAG:
1018         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
1019                                                       ptr, sz);
1020         break;
1021     case EVP_CTRL_AEAD_TLS1_AAD:
1022         /* This one does a set and a get - since it returns a size */
1023         params[0] =
1024             OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
1025                                               ptr, sz);
1026         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
1027         if (ret <= 0)
1028             goto end;
1029         params[0] =
1030             OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD, &sz);
1031         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
1032         if (ret <= 0)
1033             goto end;
1034         return sz;
1035 #ifndef OPENSSL_NO_RC2
1036     case EVP_CTRL_GET_RC2_KEY_BITS:
1037         set_params = 0; /* Fall thru */
1038     case EVP_CTRL_SET_RC2_KEY_BITS:
1039         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_RC2_KEYBITS, &sz);
1040         break;
1041 #endif /* OPENSSL_NO_RC2 */
1042 #if !defined(OPENSSL_NO_MULTIBLOCK)
1043     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
1044         params[0] = OSSL_PARAM_construct_size_t(
1045                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT, &sz);
1046         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
1047         if (ret <= 0)
1048             return 0;
1049
1050         params[0] = OSSL_PARAM_construct_size_t(
1051                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE, &sz);
1052         params[1] = OSSL_PARAM_construct_end();
1053         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
1054         if (ret <= 0)
1055             return 0;
1056         return sz;
1057     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: {
1058         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1059             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1060
1061         if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
1062             return 0;
1063
1064         params[0] = OSSL_PARAM_construct_octet_string(
1065                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD, (void*)p->inp, p->len);
1066         params[1] = OSSL_PARAM_construct_uint(
1067                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1068         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
1069         if (ret <= 0)
1070             return ret;
1071         /* Retrieve the return values changed by the set */
1072         params[0] = OSSL_PARAM_construct_size_t(
1073                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN, &sz);
1074         params[1] = OSSL_PARAM_construct_uint(
1075                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1076         params[2] = OSSL_PARAM_construct_end();
1077         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
1078         if (ret <= 0)
1079             return 0;
1080         return sz;
1081     }
1082     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: {
1083         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1084             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1085
1086         params[0] = OSSL_PARAM_construct_octet_string(
1087                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC, p->out, p->len);
1088
1089         params[1] = OSSL_PARAM_construct_octet_string(
1090                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN, (void*)p->inp,
1091                 p->len);
1092         params[2] = OSSL_PARAM_construct_uint(
1093                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1094         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
1095         if (ret <= 0)
1096             return ret;
1097         params[0] = OSSL_PARAM_construct_size_t(
1098                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN, &sz);
1099         params[1] = OSSL_PARAM_construct_end();
1100         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
1101         if (ret <= 0)
1102             return 0;
1103         return sz;
1104     }
1105 #endif /* OPENSSL_NO_MULTIBLOCK */
1106     case EVP_CTRL_AEAD_SET_MAC_KEY:
1107         if (arg < 0)
1108             return -1;
1109         params[0] = OSSL_PARAM_construct_octet_string(
1110                 OSSL_CIPHER_PARAM_AEAD_MAC_KEY, ptr, sz);
1111         break;
1112     }
1113
1114     if (set_params)
1115         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->provctx, params);
1116     else
1117         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->provctx, params);
1118     goto end;
1119
1120 /* TODO(3.0): Remove legacy code below */
1121 legacy:
1122     if (ctx->cipher->ctrl == NULL) {
1123         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
1124         return 0;
1125     }
1126
1127     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
1128
1129  end:
1130     if (ret == EVP_CTRL_RET_UNSUPPORTED) {
1131         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
1132                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
1133         return 0;
1134     }
1135     return ret;
1136 }
1137
1138 int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[])
1139 {
1140     if (cipher != NULL && cipher->get_params != NULL)
1141         return cipher->get_params(params);
1142     return 0;
1143 }
1144
1145 int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[])
1146 {
1147     if (ctx->cipher != NULL && ctx->cipher->set_ctx_params != NULL)
1148         return ctx->cipher->set_ctx_params(ctx->provctx, params);
1149     return 0;
1150 }
1151
1152 int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[])
1153 {
1154     if (ctx->cipher != NULL && ctx->cipher->get_ctx_params != NULL)
1155         return ctx->cipher->get_ctx_params(ctx->provctx, params);
1156     return 0;
1157 }
1158
1159 const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher)
1160 {
1161     if (cipher != NULL && cipher->gettable_params != NULL)
1162         return cipher->gettable_params(
1163                    ossl_provider_ctx(EVP_CIPHER_provider(cipher)));
1164     return NULL;
1165 }
1166
1167 const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher)
1168 {
1169     if (cipher != NULL && cipher->settable_ctx_params != NULL)
1170         return cipher->settable_ctx_params(
1171                    ossl_provider_ctx(EVP_CIPHER_provider(cipher)));
1172     return NULL;
1173 }
1174
1175 const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher)
1176 {
1177     if (cipher != NULL && cipher->gettable_ctx_params != NULL)
1178         return cipher->gettable_ctx_params(
1179                    ossl_provider_ctx(EVP_CIPHER_provider(cipher)));
1180     return NULL;
1181 }
1182
1183 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
1184 {
1185     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
1186         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
1187
1188 #ifdef FIPS_MODULE
1189     return 0;
1190 #else
1191     {
1192         int kl;
1193
1194         kl = EVP_CIPHER_CTX_key_length(ctx);
1195         if (kl <= 0 || RAND_priv_bytes(key, kl) <= 0)
1196             return 0;
1197         return 1;
1198     }
1199 #endif /* FIPS_MODULE */
1200 }
1201
1202 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
1203 {
1204     if ((in == NULL) || (in->cipher == NULL)) {
1205         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
1206         return 0;
1207     }
1208
1209     if (in->cipher->prov == NULL)
1210         goto legacy;
1211
1212     if (in->cipher->dupctx == NULL) {
1213         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
1214         return 0;
1215     }
1216
1217     EVP_CIPHER_CTX_reset(out);
1218
1219     *out = *in;
1220     out->provctx = NULL;
1221
1222     if (in->fetched_cipher != NULL && !EVP_CIPHER_up_ref(in->fetched_cipher)) {
1223         out->fetched_cipher = NULL;
1224         return 0;
1225     }
1226
1227     out->provctx = in->cipher->dupctx(in->provctx);
1228     if (out->provctx == NULL) {
1229         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
1230         return 0;
1231     }
1232
1233     return 1;
1234
1235     /* TODO(3.0): Remove legacy code below */
1236  legacy:
1237
1238 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
1239     /* Make sure it's safe to copy a cipher context using an ENGINE */
1240     if (in->engine && !ENGINE_init(in->engine)) {
1241         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
1242         return 0;
1243     }
1244 #endif
1245
1246     EVP_CIPHER_CTX_reset(out);
1247     memcpy(out, in, sizeof(*out));
1248
1249     if (in->cipher_data && in->cipher->ctx_size) {
1250         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
1251         if (out->cipher_data == NULL) {
1252             out->cipher = NULL;
1253             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
1254             return 0;
1255         }
1256         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
1257     }
1258
1259     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
1260         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
1261             out->cipher = NULL;
1262             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
1263             return 0;
1264         }
1265     return 1;
1266 }
1267
1268 EVP_CIPHER *evp_cipher_new(void)
1269 {
1270     EVP_CIPHER *cipher = OPENSSL_zalloc(sizeof(EVP_CIPHER));
1271
1272     if (cipher != NULL) {
1273         cipher->lock = CRYPTO_THREAD_lock_new();
1274         if (cipher->lock == NULL) {
1275             OPENSSL_free(cipher);
1276             return NULL;
1277         }
1278         cipher->refcnt = 1;
1279     }
1280     return cipher;
1281 }
1282
1283 /*
1284  * FIPS module note: since internal fetches will be entirely
1285  * provider based, we know that none of its code depends on legacy
1286  * NIDs or any functionality that use them.
1287  */
1288 #ifndef FIPS_MODULE
1289 /* TODO(3.x) get rid of the need for legacy NIDs */
1290 static void set_legacy_nid(const char *name, void *vlegacy_nid)
1291 {
1292     int nid;
1293     int *legacy_nid = vlegacy_nid;
1294     /*
1295      * We use lowest level function to get the associated method, because
1296      * higher level functions such as EVP_get_cipherbyname() have changed
1297      * to look at providers too.
1298      */
1299     const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH);
1300
1301     if (*legacy_nid == -1)       /* We found a clash already */
1302         return;
1303     if (legacy_method == NULL)
1304         return;
1305     nid = EVP_CIPHER_nid(legacy_method);
1306     if (*legacy_nid != NID_undef && *legacy_nid != nid) {
1307         *legacy_nid = -1;
1308         return;
1309     }
1310     *legacy_nid = nid;
1311 }
1312 #endif
1313
1314 static void *evp_cipher_from_dispatch(const int name_id,
1315                                       const OSSL_DISPATCH *fns,
1316                                       OSSL_PROVIDER *prov)
1317 {
1318     EVP_CIPHER *cipher = NULL;
1319     int fnciphcnt = 0, fnctxcnt = 0;
1320
1321     if ((cipher = evp_cipher_new()) == NULL) {
1322         EVPerr(0, ERR_R_MALLOC_FAILURE);
1323         return NULL;
1324     }
1325
1326 #ifndef FIPS_MODULE
1327     /* TODO(3.x) get rid of the need for legacy NIDs */
1328     cipher->nid = NID_undef;
1329     evp_names_do_all(prov, name_id, set_legacy_nid, &cipher->nid);
1330     if (cipher->nid == -1) {
1331         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1332         EVP_CIPHER_free(cipher);
1333         return NULL;
1334     }
1335 #endif
1336
1337     cipher->name_id = name_id;
1338
1339     for (; fns->function_id != 0; fns++) {
1340         switch (fns->function_id) {
1341         case OSSL_FUNC_CIPHER_NEWCTX:
1342             if (cipher->newctx != NULL)
1343                 break;
1344             cipher->newctx = OSSL_FUNC_cipher_newctx(fns);
1345             fnctxcnt++;
1346             break;
1347         case OSSL_FUNC_CIPHER_ENCRYPT_INIT:
1348             if (cipher->einit != NULL)
1349                 break;
1350             cipher->einit = OSSL_FUNC_cipher_encrypt_init(fns);
1351             fnciphcnt++;
1352             break;
1353         case OSSL_FUNC_CIPHER_DECRYPT_INIT:
1354             if (cipher->dinit != NULL)
1355                 break;
1356             cipher->dinit = OSSL_FUNC_cipher_decrypt_init(fns);
1357             fnciphcnt++;
1358             break;
1359         case OSSL_FUNC_CIPHER_UPDATE:
1360             if (cipher->cupdate != NULL)
1361                 break;
1362             cipher->cupdate = OSSL_FUNC_cipher_update(fns);
1363             fnciphcnt++;
1364             break;
1365         case OSSL_FUNC_CIPHER_FINAL:
1366             if (cipher->cfinal != NULL)
1367                 break;
1368             cipher->cfinal = OSSL_FUNC_cipher_final(fns);
1369             fnciphcnt++;
1370             break;
1371         case OSSL_FUNC_CIPHER_CIPHER:
1372             if (cipher->ccipher != NULL)
1373                 break;
1374             cipher->ccipher = OSSL_FUNC_cipher_cipher(fns);
1375             break;
1376         case OSSL_FUNC_CIPHER_FREECTX:
1377             if (cipher->freectx != NULL)
1378                 break;
1379             cipher->freectx = OSSL_FUNC_cipher_freectx(fns);
1380             fnctxcnt++;
1381             break;
1382         case OSSL_FUNC_CIPHER_DUPCTX:
1383             if (cipher->dupctx != NULL)
1384                 break;
1385             cipher->dupctx = OSSL_FUNC_cipher_dupctx(fns);
1386             break;
1387         case OSSL_FUNC_CIPHER_GET_PARAMS:
1388             if (cipher->get_params != NULL)
1389                 break;
1390             cipher->get_params = OSSL_FUNC_cipher_get_params(fns);
1391             break;
1392         case OSSL_FUNC_CIPHER_GET_CTX_PARAMS:
1393             if (cipher->get_ctx_params != NULL)
1394                 break;
1395             cipher->get_ctx_params = OSSL_FUNC_cipher_get_ctx_params(fns);
1396             break;
1397         case OSSL_FUNC_CIPHER_SET_CTX_PARAMS:
1398             if (cipher->set_ctx_params != NULL)
1399                 break;
1400             cipher->set_ctx_params = OSSL_FUNC_cipher_set_ctx_params(fns);
1401             break;
1402         case OSSL_FUNC_CIPHER_GETTABLE_PARAMS:
1403             if (cipher->gettable_params != NULL)
1404                 break;
1405             cipher->gettable_params = OSSL_FUNC_cipher_gettable_params(fns);
1406             break;
1407         case OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS:
1408             if (cipher->gettable_ctx_params != NULL)
1409                 break;
1410             cipher->gettable_ctx_params =
1411                 OSSL_FUNC_cipher_gettable_ctx_params(fns);
1412             break;
1413         case OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS:
1414             if (cipher->settable_ctx_params != NULL)
1415                 break;
1416             cipher->settable_ctx_params =
1417                 OSSL_FUNC_cipher_settable_ctx_params(fns);
1418             break;
1419         }
1420     }
1421     if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4)
1422             || (fnciphcnt == 0 && cipher->ccipher == NULL)
1423             || fnctxcnt != 2) {
1424         /*
1425          * In order to be a consistent set of functions we must have at least
1426          * a complete set of "encrypt" functions, or a complete set of "decrypt"
1427          * functions, or a single "cipher" function. In all cases we need both
1428          * the "newctx" and "freectx" functions.
1429          */
1430         EVP_CIPHER_free(cipher);
1431         EVPerr(EVP_F_EVP_CIPHER_FROM_DISPATCH, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1432         return NULL;
1433     }
1434     cipher->prov = prov;
1435     if (prov != NULL)
1436         ossl_provider_up_ref(prov);
1437
1438     return cipher;
1439 }
1440
1441 static int evp_cipher_up_ref(void *cipher)
1442 {
1443     return EVP_CIPHER_up_ref(cipher);
1444 }
1445
1446 static void evp_cipher_free(void *cipher)
1447 {
1448     EVP_CIPHER_free(cipher);
1449 }
1450
1451 EVP_CIPHER *EVP_CIPHER_fetch(OPENSSL_CTX *ctx, const char *algorithm,
1452                              const char *properties)
1453 {
1454     EVP_CIPHER *cipher =
1455         evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties,
1456                           evp_cipher_from_dispatch, evp_cipher_up_ref,
1457                           evp_cipher_free);
1458
1459     if (cipher != NULL && !evp_cipher_cache_constants(cipher)) {
1460         EVP_CIPHER_free(cipher);
1461         cipher = NULL;
1462     }
1463     return cipher;
1464 }
1465
1466 int EVP_CIPHER_up_ref(EVP_CIPHER *cipher)
1467 {
1468     int ref = 0;
1469
1470     CRYPTO_UP_REF(&cipher->refcnt, &ref, cipher->lock);
1471     return 1;
1472 }
1473
1474 void EVP_CIPHER_free(EVP_CIPHER *cipher)
1475 {
1476     int i;
1477
1478     if (cipher == NULL)
1479         return;
1480
1481     CRYPTO_DOWN_REF(&cipher->refcnt, &i, cipher->lock);
1482     if (i > 0)
1483         return;
1484     ossl_provider_free(cipher->prov);
1485     CRYPTO_THREAD_lock_free(cipher->lock);
1486     OPENSSL_free(cipher);
1487 }
1488
1489 void EVP_CIPHER_do_all_provided(OPENSSL_CTX *libctx,
1490                                 void (*fn)(EVP_CIPHER *mac, void *arg),
1491                                 void *arg)
1492 {
1493     evp_generic_do_all(libctx, OSSL_OP_CIPHER,
1494                        (void (*)(void *, void *))fn, arg,
1495                        evp_cipher_from_dispatch, evp_cipher_free);
1496 }