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