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