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