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