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