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