1 /*
2  * Copyright 1995-2022 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 <openssl/objects.h>
15 #include <openssl/evp.h>
16 #include <openssl/ec.h>
17 #ifndef FIPS_MODULE
18 # include <openssl/engine.h>
19 #endif
20 #include <openssl/params.h>
21 #include <openssl/core_names.h>
22 #include "internal/cryptlib.h"
23 #include "internal/provider.h"
24 #include "internal/core.h"
25 #include "crypto/evp.h"
26 #include "evp_local.h"
27 
cleanup_old_md_data(EVP_MD_CTX * ctx,int force)28 static void cleanup_old_md_data(EVP_MD_CTX *ctx, int force)
29 {
30     if (ctx->digest != NULL) {
31         if (ctx->digest->cleanup != NULL
32                 && !EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_CLEANED))
33             ctx->digest->cleanup(ctx);
34         if (ctx->md_data != NULL && ctx->digest->ctx_size > 0
35                 && (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_REUSE)
36                     || force)) {
37             OPENSSL_clear_free(ctx->md_data, ctx->digest->ctx_size);
38             ctx->md_data = NULL;
39         }
40     }
41 }
42 
evp_md_ctx_clear_digest(EVP_MD_CTX * ctx,int force,int keep_fetched)43 void evp_md_ctx_clear_digest(EVP_MD_CTX *ctx, int force, int keep_fetched)
44 {
45     if (ctx->algctx != NULL) {
46         if (ctx->digest != NULL && ctx->digest->freectx != NULL)
47             ctx->digest->freectx(ctx->algctx);
48         ctx->algctx = NULL;
49         EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
50     }
51 
52     /* Code below to be removed when legacy support is dropped. */
53 
54     /*
55      * Don't assume ctx->md_data was cleaned in EVP_Digest_Final, because
56      * sometimes only copies of the context are ever finalised.
57      */
58     cleanup_old_md_data(ctx, force);
59     if (force)
60         ctx->digest = NULL;
61 
62 #if !defined(FIPS_MODULE) && !defined(OPENSSL_NO_ENGINE)
63     ENGINE_finish(ctx->engine);
64     ctx->engine = NULL;
65 #endif
66 
67     /* Non legacy code, this has to be later than the ctx->digest cleaning */
68     if (!keep_fetched) {
69         EVP_MD_free(ctx->fetched_digest);
70         ctx->fetched_digest = NULL;
71         ctx->reqdigest = NULL;
72     }
73 }
74 
evp_md_ctx_reset_ex(EVP_MD_CTX * ctx,int keep_fetched)75 static int evp_md_ctx_reset_ex(EVP_MD_CTX *ctx, int keep_fetched)
76 {
77     if (ctx == NULL)
78         return 1;
79 
80 #ifndef FIPS_MODULE
81     /*
82      * pctx should be freed by the user of EVP_MD_CTX
83      * if EVP_MD_CTX_FLAG_KEEP_PKEY_CTX is set
84      */
85     if (!EVP_MD_CTX_test_flags(ctx, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX)) {
86         EVP_PKEY_CTX_free(ctx->pctx);
87         ctx->pctx = NULL;
88     }
89 #endif
90 
91     evp_md_ctx_clear_digest(ctx, 0, keep_fetched);
92     if (!keep_fetched)
93         OPENSSL_cleanse(ctx, sizeof(*ctx));
94 
95     return 1;
96 }
97 
98 /* This call frees resources associated with the context */
EVP_MD_CTX_reset(EVP_MD_CTX * ctx)99 int EVP_MD_CTX_reset(EVP_MD_CTX *ctx)
100 {
101     return evp_md_ctx_reset_ex(ctx, 0);
102 }
103 
104 #ifndef FIPS_MODULE
evp_md_ctx_new_ex(EVP_PKEY * pkey,const ASN1_OCTET_STRING * id,OSSL_LIB_CTX * libctx,const char * propq)105 EVP_MD_CTX *evp_md_ctx_new_ex(EVP_PKEY *pkey, const ASN1_OCTET_STRING *id,
106                               OSSL_LIB_CTX *libctx, const char *propq)
107 {
108     EVP_MD_CTX *ctx;
109     EVP_PKEY_CTX *pctx = NULL;
110 
111     if ((ctx = EVP_MD_CTX_new()) == NULL
112         || (pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq)) == NULL) {
113         ERR_raise(ERR_LIB_ASN1, ERR_R_MALLOC_FAILURE);
114         goto err;
115     }
116 
117     if (id != NULL && EVP_PKEY_CTX_set1_id(pctx, id->data, id->length) <= 0)
118         goto err;
119 
120     EVP_MD_CTX_set_pkey_ctx(ctx, pctx);
121     return ctx;
122 
123  err:
124     EVP_PKEY_CTX_free(pctx);
125     EVP_MD_CTX_free(ctx);
126     return NULL;
127 }
128 #endif
129 
EVP_MD_CTX_new(void)130 EVP_MD_CTX *EVP_MD_CTX_new(void)
131 {
132     return OPENSSL_zalloc(sizeof(EVP_MD_CTX));
133 }
134 
EVP_MD_CTX_free(EVP_MD_CTX * ctx)135 void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
136 {
137     if (ctx == NULL)
138         return;
139 
140     EVP_MD_CTX_reset(ctx);
141     OPENSSL_free(ctx);
142 }
143 
evp_md_init_internal(EVP_MD_CTX * ctx,const EVP_MD * type,const OSSL_PARAM params[],ENGINE * impl)144 static int evp_md_init_internal(EVP_MD_CTX *ctx, const EVP_MD *type,
145                                 const OSSL_PARAM params[], ENGINE *impl)
146 {
147 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
148     ENGINE *tmpimpl = NULL;
149 #endif
150 
151 #if !defined(FIPS_MODULE)
152     if (ctx->pctx != NULL
153             && EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
154             && ctx->pctx->op.sig.algctx != NULL) {
155         /*
156          * Prior to OpenSSL 3.0 calling EVP_DigestInit_ex() on an mdctx
157          * previously initialised with EVP_DigestSignInit() would retain
158          * information about the key, and re-initialise for another sign
159          * operation. So in that case we redirect to EVP_DigestSignInit()
160          */
161         if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX)
162             return EVP_DigestSignInit(ctx, NULL, type, impl, NULL);
163         if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX)
164             return EVP_DigestVerifyInit(ctx, NULL, type, impl, NULL);
165         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
166         return 0;
167     }
168 #endif
169 
170     EVP_MD_CTX_clear_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
171 
172     if (ctx->algctx != NULL) {
173         if (!ossl_assert(ctx->digest != NULL)) {
174             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
175             return 0;
176         }
177         if (ctx->digest->freectx != NULL)
178             ctx->digest->freectx(ctx->algctx);
179         ctx->algctx = NULL;
180     }
181 
182     if (type != NULL) {
183         ctx->reqdigest = type;
184     } else {
185         if (ctx->digest == NULL) {
186             ERR_raise(ERR_LIB_EVP, EVP_R_NO_DIGEST_SET);
187             return 0;
188         }
189         type = ctx->digest;
190     }
191 
192     /* Code below to be removed when legacy support is dropped. */
193 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
194     /*
195      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
196      * this context may already have an ENGINE! Try to avoid releasing the
197      * previous handle, re-querying for an ENGINE, and having a
198      * reinitialisation, when it may all be unnecessary.
199      */
200     if (ctx->engine && ctx->digest &&
201         (type == NULL || (type->type == ctx->digest->type)))
202         goto skip_to_init;
203 
204     if (type != NULL) {
205         /*
206          * Ensure an ENGINE left lying around from last time is cleared (the
207          * previous check attempted to avoid this if the same ENGINE and
208          * EVP_MD could be used).
209          */
210         ENGINE_finish(ctx->engine);
211         ctx->engine = NULL;
212     }
213 
214     if (type != NULL && impl == NULL)
215         tmpimpl = ENGINE_get_digest_engine(type->type);
216 #endif
217 
218     /*
219      * If there are engines involved or EVP_MD_CTX_FLAG_NO_INIT is set then we
220      * should use legacy handling for now.
221      */
222     if (ctx->engine != NULL
223             || impl != NULL
224 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
225             || tmpimpl != NULL
226 #endif
227             || (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0
228             || type->origin == EVP_ORIG_METH) {
229         if (ctx->digest == ctx->fetched_digest)
230             ctx->digest = NULL;
231         EVP_MD_free(ctx->fetched_digest);
232         ctx->fetched_digest = NULL;
233         goto legacy;
234     }
235 
236     cleanup_old_md_data(ctx, 1);
237 
238     /* Start of non-legacy code below */
239 
240     if (type->prov == NULL) {
241 #ifdef FIPS_MODULE
242         /* We only do explicit fetches inside the FIPS module */
243         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
244         return 0;
245 #else
246         /* The NULL digest is a special case */
247         EVP_MD *provmd = EVP_MD_fetch(NULL,
248                                       type->type != NID_undef ? OBJ_nid2sn(type->type)
249                                                               : "NULL", "");
250 
251         if (provmd == NULL) {
252             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
253             return 0;
254         }
255         type = provmd;
256         EVP_MD_free(ctx->fetched_digest);
257         ctx->fetched_digest = provmd;
258 #endif
259     }
260 
261     if (ctx->algctx != NULL && ctx->digest != NULL && ctx->digest != type) {
262         if (ctx->digest->freectx != NULL)
263             ctx->digest->freectx(ctx->algctx);
264         ctx->algctx = NULL;
265     }
266     if (type->prov != NULL && ctx->fetched_digest != type) {
267         if (!EVP_MD_up_ref((EVP_MD *)type)) {
268             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
269             return 0;
270         }
271         EVP_MD_free(ctx->fetched_digest);
272         ctx->fetched_digest = (EVP_MD *)type;
273     }
274     ctx->digest = type;
275     if (ctx->algctx == NULL) {
276         ctx->algctx = ctx->digest->newctx(ossl_provider_ctx(type->prov));
277         if (ctx->algctx == NULL) {
278             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
279             return 0;
280         }
281     }
282 
283     if (ctx->digest->dinit == NULL) {
284         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
285         return 0;
286     }
287 
288     return ctx->digest->dinit(ctx->algctx, params);
289 
290     /* Code below to be removed when legacy support is dropped. */
291  legacy:
292 
293 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
294     if (type) {
295         if (impl != NULL) {
296             if (!ENGINE_init(impl)) {
297                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
298                 return 0;
299             }
300         } else {
301             /* Ask if an ENGINE is reserved for this job */
302             impl = tmpimpl;
303         }
304         if (impl != NULL) {
305             /* There's an ENGINE for this job ... (apparently) */
306             const EVP_MD *d = ENGINE_get_digest(impl, type->type);
307 
308             if (d == NULL) {
309                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
310                 ENGINE_finish(impl);
311                 return 0;
312             }
313             /* We'll use the ENGINE's private digest definition */
314             type = d;
315             /*
316              * Store the ENGINE functional reference so we know 'type' came
317              * from an ENGINE and we need to release it when done.
318              */
319             ctx->engine = impl;
320         } else
321             ctx->engine = NULL;
322     }
323 #endif
324     if (ctx->digest != type) {
325         cleanup_old_md_data(ctx, 1);
326 
327         ctx->digest = type;
328         if (!(ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) && type->ctx_size) {
329             ctx->update = type->update;
330             ctx->md_data = OPENSSL_zalloc(type->ctx_size);
331             if (ctx->md_data == NULL) {
332                 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
333                 return 0;
334             }
335         }
336     }
337 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
338  skip_to_init:
339 #endif
340 #ifndef FIPS_MODULE
341     if (ctx->pctx != NULL
342             && (!EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
343                  || ctx->pctx->op.sig.signature == NULL)) {
344         int r;
345         r = EVP_PKEY_CTX_ctrl(ctx->pctx, -1, EVP_PKEY_OP_TYPE_SIG,
346                               EVP_PKEY_CTRL_DIGESTINIT, 0, ctx);
347         if (r <= 0 && (r != -2))
348             return 0;
349     }
350 #endif
351     if (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT)
352         return 1;
353     return ctx->digest->init(ctx);
354 }
355 
EVP_DigestInit_ex2(EVP_MD_CTX * ctx,const EVP_MD * type,const OSSL_PARAM params[])356 int EVP_DigestInit_ex2(EVP_MD_CTX *ctx, const EVP_MD *type,
357                        const OSSL_PARAM params[])
358 {
359     return evp_md_init_internal(ctx, type, params, NULL);
360 }
361 
EVP_DigestInit(EVP_MD_CTX * ctx,const EVP_MD * type)362 int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type)
363 {
364     EVP_MD_CTX_reset(ctx);
365     return evp_md_init_internal(ctx, type, NULL, NULL);
366 }
367 
EVP_DigestInit_ex(EVP_MD_CTX * ctx,const EVP_MD * type,ENGINE * impl)368 int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *impl)
369 {
370     return evp_md_init_internal(ctx, type, NULL, impl);
371 }
372 
EVP_DigestUpdate(EVP_MD_CTX * ctx,const void * data,size_t count)373 int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t count)
374 {
375     if (count == 0)
376         return 1;
377 
378     if (ctx->pctx != NULL
379             && EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx->pctx)
380             && ctx->pctx->op.sig.algctx != NULL) {
381         /*
382          * Prior to OpenSSL 3.0 EVP_DigestSignUpdate() and
383          * EVP_DigestVerifyUpdate() were just macros for EVP_DigestUpdate().
384          * Some code calls EVP_DigestUpdate() directly even when initialised
385          * with EVP_DigestSignInit_ex() or
386          * EVP_DigestVerifyInit_ex(), so we detect that and redirect to
387          * the correct EVP_Digest*Update() function
388          */
389         if (ctx->pctx->operation == EVP_PKEY_OP_SIGNCTX)
390             return EVP_DigestSignUpdate(ctx, data, count);
391         if (ctx->pctx->operation == EVP_PKEY_OP_VERIFYCTX)
392             return EVP_DigestVerifyUpdate(ctx, data, count);
393         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
394         return 0;
395     }
396 
397     if (ctx->digest == NULL
398             || ctx->digest->prov == NULL
399             || (ctx->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0)
400         goto legacy;
401 
402     if (ctx->digest->dupdate == NULL) {
403         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
404         return 0;
405     }
406     return ctx->digest->dupdate(ctx->algctx, data, count);
407 
408     /* Code below to be removed when legacy support is dropped. */
409  legacy:
410     return ctx->update(ctx, data, count);
411 }
412 
413 /* The caller can assume that this removes any secret data from the context */
EVP_DigestFinal(EVP_MD_CTX * ctx,unsigned char * md,unsigned int * size)414 int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *size)
415 {
416     int ret;
417     ret = EVP_DigestFinal_ex(ctx, md, size);
418     EVP_MD_CTX_reset(ctx);
419     return ret;
420 }
421 
422 /* The caller can assume that this removes any secret data from the context */
EVP_DigestFinal_ex(EVP_MD_CTX * ctx,unsigned char * md,unsigned int * isize)423 int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *isize)
424 {
425     int ret, sz;
426     size_t size = 0;
427     size_t mdsize = 0;
428 
429     if (ctx->digest == NULL)
430         return 0;
431 
432     sz = EVP_MD_get_size(ctx->digest);
433     if (sz < 0)
434         return 0;
435     mdsize = sz;
436     if (ctx->digest->prov == NULL)
437         goto legacy;
438 
439     if (ctx->digest->dfinal == NULL) {
440         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
441         return 0;
442     }
443 
444     ret = ctx->digest->dfinal(ctx->algctx, md, &size, mdsize);
445 
446     if (isize != NULL) {
447         if (size <= UINT_MAX) {
448             *isize = (int)size;
449         } else {
450             ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
451             ret = 0;
452         }
453     }
454 
455     return ret;
456 
457     /* Code below to be removed when legacy support is dropped. */
458  legacy:
459     OPENSSL_assert(mdsize <= EVP_MAX_MD_SIZE);
460     ret = ctx->digest->final(ctx, md);
461     if (isize != NULL)
462         *isize = mdsize;
463     if (ctx->digest->cleanup) {
464         ctx->digest->cleanup(ctx);
465         EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
466     }
467     OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size);
468     return ret;
469 }
470 
EVP_DigestFinalXOF(EVP_MD_CTX * ctx,unsigned char * md,size_t size)471 int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md, size_t size)
472 {
473     int ret = 0;
474     OSSL_PARAM params[2];
475     size_t i = 0;
476 
477     if (ctx->digest == NULL) {
478         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_NULL_ALGORITHM);
479         return 0;
480     }
481 
482     if (ctx->digest->prov == NULL)
483         goto legacy;
484 
485     if (ctx->digest->dfinal == NULL) {
486         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
487         return 0;
488     }
489 
490     params[i++] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &size);
491     params[i++] = OSSL_PARAM_construct_end();
492 
493     if (EVP_MD_CTX_set_params(ctx, params) > 0)
494         ret = ctx->digest->dfinal(ctx->algctx, md, &size, size);
495 
496     return ret;
497 
498 legacy:
499     if (ctx->digest->flags & EVP_MD_FLAG_XOF
500         && size <= INT_MAX
501         && ctx->digest->md_ctrl(ctx, EVP_MD_CTRL_XOF_LEN, (int)size, NULL)) {
502         ret = ctx->digest->final(ctx, md);
503         if (ctx->digest->cleanup != NULL) {
504             ctx->digest->cleanup(ctx);
505             EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_CLEANED);
506         }
507         OPENSSL_cleanse(ctx->md_data, ctx->digest->ctx_size);
508     } else {
509         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_XOF_OR_INVALID_LENGTH);
510     }
511 
512     return ret;
513 }
514 
EVP_MD_CTX_copy(EVP_MD_CTX * out,const EVP_MD_CTX * in)515 int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in)
516 {
517     EVP_MD_CTX_reset(out);
518     return EVP_MD_CTX_copy_ex(out, in);
519 }
520 
EVP_MD_CTX_copy_ex(EVP_MD_CTX * out,const EVP_MD_CTX * in)521 int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in)
522 {
523     int digest_change = 0;
524     unsigned char *tmp_buf;
525 
526     if (in == NULL) {
527         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
528         return 0;
529     }
530 
531     if (in->digest == NULL) {
532         /* copying uninitialized digest context */
533         EVP_MD_CTX_reset(out);
534         if (out->fetched_digest != NULL)
535             EVP_MD_free(out->fetched_digest);
536         *out = *in;
537         goto clone_pkey;
538     }
539 
540     if (in->digest->prov == NULL
541             || (in->flags & EVP_MD_CTX_FLAG_NO_INIT) != 0)
542         goto legacy;
543 
544     if (in->digest->dupctx == NULL) {
545         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
546         return 0;
547     }
548 
549     evp_md_ctx_reset_ex(out, 1);
550     digest_change = (out->fetched_digest != in->fetched_digest);
551     if (digest_change && out->fetched_digest != NULL)
552         EVP_MD_free(out->fetched_digest);
553     *out = *in;
554     /* NULL out pointers in case of error */
555     out->pctx = NULL;
556     out->algctx = NULL;
557 
558     if (digest_change && in->fetched_digest != NULL)
559         EVP_MD_up_ref(in->fetched_digest);
560 
561     if (in->algctx != NULL) {
562         out->algctx = in->digest->dupctx(in->algctx);
563         if (out->algctx == NULL) {
564             ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
565             return 0;
566         }
567     }
568 
569  clone_pkey:
570     /* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */
571     EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
572 #ifndef FIPS_MODULE
573     if (in->pctx != NULL) {
574         out->pctx = EVP_PKEY_CTX_dup(in->pctx);
575         if (out->pctx == NULL) {
576             ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
577             EVP_MD_CTX_reset(out);
578             return 0;
579         }
580     }
581 #endif
582 
583     return 1;
584 
585     /* Code below to be removed when legacy support is dropped. */
586  legacy:
587 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
588     /* Make sure it's safe to copy a digest context using an ENGINE */
589     if (in->engine && !ENGINE_init(in->engine)) {
590         ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
591         return 0;
592     }
593 #endif
594 
595     if (out->digest == in->digest) {
596         tmp_buf = out->md_data;
597         EVP_MD_CTX_set_flags(out, EVP_MD_CTX_FLAG_REUSE);
598     } else
599         tmp_buf = NULL;
600     EVP_MD_CTX_reset(out);
601     memcpy(out, in, sizeof(*out));
602 
603     /* copied EVP_MD_CTX should free the copied EVP_PKEY_CTX */
604     EVP_MD_CTX_clear_flags(out, EVP_MD_CTX_FLAG_KEEP_PKEY_CTX);
605 
606     /* Null these variables, since they are getting fixed up
607      * properly below.  Anything else may cause a memleak and/or
608      * double free if any of the memory allocations below fail
609      */
610     out->md_data = NULL;
611     out->pctx = NULL;
612 
613     if (in->md_data && out->digest->ctx_size) {
614         if (tmp_buf)
615             out->md_data = tmp_buf;
616         else {
617             out->md_data = OPENSSL_malloc(out->digest->ctx_size);
618             if (out->md_data == NULL) {
619                 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
620                 return 0;
621             }
622         }
623         memcpy(out->md_data, in->md_data, out->digest->ctx_size);
624     }
625 
626     out->update = in->update;
627 
628 #ifndef FIPS_MODULE
629     if (in->pctx) {
630         out->pctx = EVP_PKEY_CTX_dup(in->pctx);
631         if (!out->pctx) {
632             EVP_MD_CTX_reset(out);
633             return 0;
634         }
635     }
636 #endif
637 
638     if (out->digest->copy)
639         return out->digest->copy(out, in);
640 
641     return 1;
642 }
643 
EVP_Digest(const void * data,size_t count,unsigned char * md,unsigned int * size,const EVP_MD * type,ENGINE * impl)644 int EVP_Digest(const void *data, size_t count,
645                unsigned char *md, unsigned int *size, const EVP_MD *type,
646                ENGINE *impl)
647 {
648     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
649     int ret;
650 
651     if (ctx == NULL)
652         return 0;
653     EVP_MD_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_ONESHOT);
654     ret = EVP_DigestInit_ex(ctx, type, impl)
655         && EVP_DigestUpdate(ctx, data, count)
656         && EVP_DigestFinal_ex(ctx, md, size);
657     EVP_MD_CTX_free(ctx);
658 
659     return ret;
660 }
661 
EVP_Q_digest(OSSL_LIB_CTX * libctx,const char * name,const char * propq,const void * data,size_t datalen,unsigned char * md,size_t * mdlen)662 int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name, const char *propq,
663                  const void *data, size_t datalen,
664                  unsigned char *md, size_t *mdlen)
665 {
666     EVP_MD *digest = EVP_MD_fetch(libctx, name, propq);
667     unsigned int temp = 0;
668     int ret = 0;
669 
670     if (digest != NULL) {
671         ret = EVP_Digest(data, datalen, md, &temp, digest, NULL);
672         EVP_MD_free(digest);
673     }
674     if (mdlen != NULL)
675         *mdlen = temp;
676     return ret;
677 }
678 
EVP_MD_get_params(const EVP_MD * digest,OSSL_PARAM params[])679 int EVP_MD_get_params(const EVP_MD *digest, OSSL_PARAM params[])
680 {
681     if (digest != NULL && digest->get_params != NULL)
682         return digest->get_params(params);
683     return 0;
684 }
685 
EVP_MD_gettable_params(const EVP_MD * digest)686 const OSSL_PARAM *EVP_MD_gettable_params(const EVP_MD *digest)
687 {
688     if (digest != NULL && digest->gettable_params != NULL)
689         return digest->gettable_params(
690                            ossl_provider_ctx(EVP_MD_get0_provider(digest)));
691     return NULL;
692 }
693 
EVP_MD_CTX_set_params(EVP_MD_CTX * ctx,const OSSL_PARAM params[])694 int EVP_MD_CTX_set_params(EVP_MD_CTX *ctx, const OSSL_PARAM params[])
695 {
696     EVP_PKEY_CTX *pctx = ctx->pctx;
697 
698     /* If we have a pctx then we should try that first */
699     if (pctx != NULL
700             && (pctx->operation == EVP_PKEY_OP_VERIFYCTX
701                 || pctx->operation == EVP_PKEY_OP_SIGNCTX)
702             && pctx->op.sig.algctx != NULL
703             && pctx->op.sig.signature->set_ctx_md_params != NULL)
704         return pctx->op.sig.signature->set_ctx_md_params(pctx->op.sig.algctx,
705                                                          params);
706 
707     if (ctx->digest != NULL && ctx->digest->set_ctx_params != NULL)
708         return ctx->digest->set_ctx_params(ctx->algctx, params);
709 
710     return 0;
711 }
712 
EVP_MD_settable_ctx_params(const EVP_MD * md)713 const OSSL_PARAM *EVP_MD_settable_ctx_params(const EVP_MD *md)
714 {
715     void *provctx;
716 
717     if (md != NULL && md->settable_ctx_params != NULL) {
718         provctx = ossl_provider_ctx(EVP_MD_get0_provider(md));
719         return md->settable_ctx_params(NULL, provctx);
720     }
721     return NULL;
722 }
723 
EVP_MD_CTX_settable_params(EVP_MD_CTX * ctx)724 const OSSL_PARAM *EVP_MD_CTX_settable_params(EVP_MD_CTX *ctx)
725 {
726     EVP_PKEY_CTX *pctx;
727     void *alg;
728 
729     if (ctx == NULL)
730         return NULL;
731 
732     /* If we have a pctx then we should try that first */
733     pctx = ctx->pctx;
734     if (pctx != NULL
735             && (pctx->operation == EVP_PKEY_OP_VERIFYCTX
736                 || pctx->operation == EVP_PKEY_OP_SIGNCTX)
737             && pctx->op.sig.algctx != NULL
738             && pctx->op.sig.signature->settable_ctx_md_params != NULL)
739         return pctx->op.sig.signature->settable_ctx_md_params(
740                    pctx->op.sig.algctx);
741 
742     if (ctx->digest != NULL && ctx->digest->settable_ctx_params != NULL) {
743         alg = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest));
744         return ctx->digest->settable_ctx_params(ctx->algctx, alg);
745     }
746 
747     return NULL;
748 }
749 
EVP_MD_CTX_get_params(EVP_MD_CTX * ctx,OSSL_PARAM params[])750 int EVP_MD_CTX_get_params(EVP_MD_CTX *ctx, OSSL_PARAM params[])
751 {
752     EVP_PKEY_CTX *pctx = ctx->pctx;
753 
754     /* If we have a pctx then we should try that first */
755     if (pctx != NULL
756             && (pctx->operation == EVP_PKEY_OP_VERIFYCTX
757                 || pctx->operation == EVP_PKEY_OP_SIGNCTX)
758             && pctx->op.sig.algctx != NULL
759             && pctx->op.sig.signature->get_ctx_md_params != NULL)
760         return pctx->op.sig.signature->get_ctx_md_params(pctx->op.sig.algctx,
761                                                          params);
762 
763     if (ctx->digest != NULL && ctx->digest->get_params != NULL)
764         return ctx->digest->get_ctx_params(ctx->algctx, params);
765 
766     return 0;
767 }
768 
EVP_MD_gettable_ctx_params(const EVP_MD * md)769 const OSSL_PARAM *EVP_MD_gettable_ctx_params(const EVP_MD *md)
770 {
771     void *provctx;
772 
773     if (md != NULL && md->gettable_ctx_params != NULL) {
774         provctx = ossl_provider_ctx(EVP_MD_get0_provider(md));
775         return md->gettable_ctx_params(NULL, provctx);
776     }
777     return NULL;
778 }
779 
EVP_MD_CTX_gettable_params(EVP_MD_CTX * ctx)780 const OSSL_PARAM *EVP_MD_CTX_gettable_params(EVP_MD_CTX *ctx)
781 {
782     EVP_PKEY_CTX *pctx;
783     void *provctx;
784 
785     if (ctx == NULL)
786         return NULL;
787 
788     /* If we have a pctx then we should try that first */
789     pctx = ctx->pctx;
790     if (pctx != NULL
791             && (pctx->operation == EVP_PKEY_OP_VERIFYCTX
792                 || pctx->operation == EVP_PKEY_OP_SIGNCTX)
793             && pctx->op.sig.algctx != NULL
794             && pctx->op.sig.signature->gettable_ctx_md_params != NULL)
795         return pctx->op.sig.signature->gettable_ctx_md_params(
796                     pctx->op.sig.algctx);
797 
798     if (ctx->digest != NULL && ctx->digest->gettable_ctx_params != NULL) {
799         provctx = ossl_provider_ctx(EVP_MD_get0_provider(ctx->digest));
800         return ctx->digest->gettable_ctx_params(ctx->algctx, provctx);
801     }
802     return NULL;
803 }
804 
EVP_MD_CTX_ctrl(EVP_MD_CTX * ctx,int cmd,int p1,void * p2)805 int EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2)
806 {
807     int ret = EVP_CTRL_RET_UNSUPPORTED;
808     int set_params = 1;
809     size_t sz;
810     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
811 
812     if (ctx == NULL) {
813         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
814         return 0;
815     }
816 
817     if (ctx->digest != NULL && ctx->digest->prov == NULL)
818         goto legacy;
819 
820     switch (cmd) {
821     case EVP_MD_CTRL_XOF_LEN:
822         sz = (size_t)p1;
823         params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_XOFLEN, &sz);
824         break;
825     case EVP_MD_CTRL_MICALG:
826         set_params = 0;
827         params[0] = OSSL_PARAM_construct_utf8_string(OSSL_DIGEST_PARAM_MICALG,
828                                                      p2, p1 ? p1 : 9999);
829         break;
830     case EVP_CTRL_SSL3_MASTER_SECRET:
831         params[0] = OSSL_PARAM_construct_octet_string(OSSL_DIGEST_PARAM_SSL3_MS,
832                                                       p2, p1);
833         break;
834     default:
835         goto conclude;
836     }
837 
838     if (set_params)
839         ret = EVP_MD_CTX_set_params(ctx, params);
840     else
841         ret = EVP_MD_CTX_get_params(ctx, params);
842     goto conclude;
843 
844 
845     /* Code below to be removed when legacy support is dropped. */
846  legacy:
847     if (ctx->digest->md_ctrl == NULL) {
848         ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED);
849         return 0;
850     }
851 
852     ret = ctx->digest->md_ctrl(ctx, cmd, p1, p2);
853  conclude:
854     if (ret <= 0)
855         return 0;
856     return ret;
857 }
858 
evp_md_new(void)859 EVP_MD *evp_md_new(void)
860 {
861     EVP_MD *md = OPENSSL_zalloc(sizeof(*md));
862 
863     if (md != NULL) {
864         md->lock = CRYPTO_THREAD_lock_new();
865         if (md->lock == NULL) {
866             OPENSSL_free(md);
867             return NULL;
868         }
869         md->refcnt = 1;
870     }
871     return md;
872 }
873 
874 /*
875  * FIPS module note: since internal fetches will be entirely
876  * provider based, we know that none of its code depends on legacy
877  * NIDs or any functionality that use them.
878  */
879 #ifndef FIPS_MODULE
set_legacy_nid(const char * name,void * vlegacy_nid)880 static void set_legacy_nid(const char *name, void *vlegacy_nid)
881 {
882     int nid;
883     int *legacy_nid = vlegacy_nid;
884     /*
885      * We use lowest level function to get the associated method, because
886      * higher level functions such as EVP_get_digestbyname() have changed
887      * to look at providers too.
888      */
889     const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_MD_METH);
890 
891     if (*legacy_nid == -1)       /* We found a clash already */
892         return;
893 
894     if (legacy_method == NULL)
895         return;
896     nid = EVP_MD_nid(legacy_method);
897     if (*legacy_nid != NID_undef && *legacy_nid != nid) {
898         *legacy_nid = -1;
899         return;
900     }
901     *legacy_nid = nid;
902 }
903 #endif
904 
evp_md_cache_constants(EVP_MD * md)905 static int evp_md_cache_constants(EVP_MD *md)
906 {
907     int ok, xof = 0, algid_absent = 0;
908     size_t blksz = 0;
909     size_t mdsize = 0;
910     OSSL_PARAM params[5];
911 
912     params[0] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_BLOCK_SIZE, &blksz);
913     params[1] = OSSL_PARAM_construct_size_t(OSSL_DIGEST_PARAM_SIZE, &mdsize);
914     params[2] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_XOF, &xof);
915     params[3] = OSSL_PARAM_construct_int(OSSL_DIGEST_PARAM_ALGID_ABSENT,
916                                          &algid_absent);
917     params[4] = OSSL_PARAM_construct_end();
918     ok = evp_do_md_getparams(md, params) > 0;
919     if (mdsize > INT_MAX || blksz > INT_MAX)
920         ok = 0;
921     if (ok) {
922         md->block_size = (int)blksz;
923         md->md_size = (int)mdsize;
924         if (xof)
925             md->flags |= EVP_MD_FLAG_XOF;
926         if (algid_absent)
927             md->flags |= EVP_MD_FLAG_DIGALGID_ABSENT;
928     }
929     return ok;
930 }
931 
evp_md_from_algorithm(int name_id,const OSSL_ALGORITHM * algodef,OSSL_PROVIDER * prov)932 static void *evp_md_from_algorithm(int name_id,
933                                    const OSSL_ALGORITHM *algodef,
934                                    OSSL_PROVIDER *prov)
935 {
936     const OSSL_DISPATCH *fns = algodef->implementation;
937     EVP_MD *md = NULL;
938     int fncnt = 0;
939 
940     /* EVP_MD_fetch() will set the legacy NID if available */
941     if ((md = evp_md_new()) == NULL) {
942         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
943         return NULL;
944     }
945 
946 #ifndef FIPS_MODULE
947     md->type = NID_undef;
948     if (!evp_names_do_all(prov, name_id, set_legacy_nid, &md->type)
949             || md->type == -1) {
950         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
951         EVP_MD_free(md);
952         return NULL;
953     }
954 #endif
955 
956     md->name_id = name_id;
957     if ((md->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) {
958         EVP_MD_free(md);
959         return NULL;
960     }
961     md->description = algodef->algorithm_description;
962 
963     for (; fns->function_id != 0; fns++) {
964         switch (fns->function_id) {
965         case OSSL_FUNC_DIGEST_NEWCTX:
966             if (md->newctx == NULL) {
967                 md->newctx = OSSL_FUNC_digest_newctx(fns);
968                 fncnt++;
969             }
970             break;
971         case OSSL_FUNC_DIGEST_INIT:
972             if (md->dinit == NULL) {
973                 md->dinit = OSSL_FUNC_digest_init(fns);
974                 fncnt++;
975             }
976             break;
977         case OSSL_FUNC_DIGEST_UPDATE:
978             if (md->dupdate == NULL) {
979                 md->dupdate = OSSL_FUNC_digest_update(fns);
980                 fncnt++;
981             }
982             break;
983         case OSSL_FUNC_DIGEST_FINAL:
984             if (md->dfinal == NULL) {
985                 md->dfinal = OSSL_FUNC_digest_final(fns);
986                 fncnt++;
987             }
988             break;
989         case OSSL_FUNC_DIGEST_DIGEST:
990             if (md->digest == NULL)
991                 md->digest = OSSL_FUNC_digest_digest(fns);
992             /* We don't increment fnct for this as it is stand alone */
993             break;
994         case OSSL_FUNC_DIGEST_FREECTX:
995             if (md->freectx == NULL) {
996                 md->freectx = OSSL_FUNC_digest_freectx(fns);
997                 fncnt++;
998             }
999             break;
1000         case OSSL_FUNC_DIGEST_DUPCTX:
1001             if (md->dupctx == NULL)
1002                 md->dupctx = OSSL_FUNC_digest_dupctx(fns);
1003             break;
1004         case OSSL_FUNC_DIGEST_GET_PARAMS:
1005             if (md->get_params == NULL)
1006                 md->get_params = OSSL_FUNC_digest_get_params(fns);
1007             break;
1008         case OSSL_FUNC_DIGEST_SET_CTX_PARAMS:
1009             if (md->set_ctx_params == NULL)
1010                 md->set_ctx_params = OSSL_FUNC_digest_set_ctx_params(fns);
1011             break;
1012         case OSSL_FUNC_DIGEST_GET_CTX_PARAMS:
1013             if (md->get_ctx_params == NULL)
1014                 md->get_ctx_params = OSSL_FUNC_digest_get_ctx_params(fns);
1015             break;
1016         case OSSL_FUNC_DIGEST_GETTABLE_PARAMS:
1017             if (md->gettable_params == NULL)
1018                 md->gettable_params = OSSL_FUNC_digest_gettable_params(fns);
1019             break;
1020         case OSSL_FUNC_DIGEST_SETTABLE_CTX_PARAMS:
1021             if (md->settable_ctx_params == NULL)
1022                 md->settable_ctx_params =
1023                     OSSL_FUNC_digest_settable_ctx_params(fns);
1024             break;
1025         case OSSL_FUNC_DIGEST_GETTABLE_CTX_PARAMS:
1026             if (md->gettable_ctx_params == NULL)
1027                 md->gettable_ctx_params =
1028                     OSSL_FUNC_digest_gettable_ctx_params(fns);
1029             break;
1030         }
1031     }
1032     if ((fncnt != 0 && fncnt != 5)
1033         || (fncnt == 0 && md->digest == NULL)) {
1034         /*
1035          * In order to be a consistent set of functions we either need the
1036          * whole set of init/update/final etc functions or none of them.
1037          * The "digest" function can standalone. We at least need one way to
1038          * generate digests.
1039          */
1040         EVP_MD_free(md);
1041         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1042         return NULL;
1043     }
1044     md->prov = prov;
1045     if (prov != NULL)
1046         ossl_provider_up_ref(prov);
1047 
1048     if (!evp_md_cache_constants(md)) {
1049         EVP_MD_free(md);
1050         ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED);
1051         md = NULL;
1052     }
1053 
1054     return md;
1055 }
1056 
evp_md_up_ref(void * md)1057 static int evp_md_up_ref(void *md)
1058 {
1059     return EVP_MD_up_ref(md);
1060 }
1061 
evp_md_free(void * md)1062 static void evp_md_free(void *md)
1063 {
1064     EVP_MD_free(md);
1065 }
1066 
EVP_MD_fetch(OSSL_LIB_CTX * ctx,const char * algorithm,const char * properties)1067 EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
1068                      const char *properties)
1069 {
1070     EVP_MD *md =
1071         evp_generic_fetch(ctx, OSSL_OP_DIGEST, algorithm, properties,
1072                           evp_md_from_algorithm, evp_md_up_ref, evp_md_free);
1073 
1074     return md;
1075 }
1076 
EVP_MD_up_ref(EVP_MD * md)1077 int EVP_MD_up_ref(EVP_MD *md)
1078 {
1079     int ref = 0;
1080 
1081     if (md->origin == EVP_ORIG_DYNAMIC)
1082         CRYPTO_UP_REF(&md->refcnt, &ref, md->lock);
1083     return 1;
1084 }
1085 
EVP_MD_free(EVP_MD * md)1086 void EVP_MD_free(EVP_MD *md)
1087 {
1088     int i;
1089 
1090     if (md == NULL || md->origin != EVP_ORIG_DYNAMIC)
1091         return;
1092 
1093     CRYPTO_DOWN_REF(&md->refcnt, &i, md->lock);
1094     if (i > 0)
1095         return;
1096     evp_md_free_int(md);
1097 }
1098 
EVP_MD_do_all_provided(OSSL_LIB_CTX * libctx,void (* fn)(EVP_MD * mac,void * arg),void * arg)1099 void EVP_MD_do_all_provided(OSSL_LIB_CTX *libctx,
1100                             void (*fn)(EVP_MD *mac, void *arg),
1101                             void *arg)
1102 {
1103     evp_generic_do_all(libctx, OSSL_OP_DIGEST,
1104                        (void (*)(void *, void *))fn, arg,
1105                        evp_md_from_algorithm, evp_md_up_ref, evp_md_free);
1106 }
1107