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