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