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