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