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