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