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