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