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