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