Fix an EVP_MD_CTX leak
[openssl.git] / crypto / evp / m_sigver.c
1 /*
2  * Copyright 2006-2020 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 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/evp.h>
13 #include <openssl/objects.h>
14 #include <openssl/x509.h>
15 #include "crypto/evp.h"
16 #include "internal/provider.h"
17 #include "evp_local.h"
18
19 #ifndef FIPS_MODULE
20
21 static int update(EVP_MD_CTX *ctx, const void *data, size_t datalen)
22 {
23     EVPerr(EVP_F_UPDATE, EVP_R_ONLY_ONESHOT_SUPPORTED);
24     return 0;
25 }
26
27 /*
28  * If we get the "NULL" md then the name comes back as "UNDEF". We want to use
29  * NULL for this.
30  */
31 static const char *canon_mdname(const char *mdname)
32 {
33     if (mdname != NULL && strcmp(mdname, "UNDEF") == 0)
34         return NULL;
35
36     return mdname;
37 }
38
39 static int do_sigver_init(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
40                           const EVP_MD *type, const char *mdname,
41                           OPENSSL_CTX *libctx, const char *props,
42                           ENGINE *e, EVP_PKEY *pkey, int ver)
43 {
44     EVP_PKEY_CTX *locpctx = NULL;
45     EVP_SIGNATURE *signature = NULL;
46     EVP_KEYMGMT *tmp_keymgmt = NULL;
47     const char *supported_sig = NULL;
48     char locmdname[80] = "";     /* 80 chars should be enough */
49     void *provkey = NULL;
50     int ret;
51
52     if (ctx->provctx != NULL) {
53         if (!ossl_assert(ctx->digest != NULL)) {
54             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
55             return 0;
56         }
57         if (ctx->digest->freectx != NULL)
58             ctx->digest->freectx(ctx->provctx);
59         ctx->provctx = NULL;
60     }
61
62     if (ctx->pctx == NULL) {
63         if (libctx != NULL)
64             ctx->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, props);
65         else
66             ctx->pctx = EVP_PKEY_CTX_new(pkey, e);
67     }
68     if (ctx->pctx == NULL)
69         return 0;
70
71     locpctx = ctx->pctx;
72     evp_pkey_ctx_free_old_ops(locpctx);
73
74     if (props == NULL)
75         props = locpctx->propquery;
76
77     /*
78      * TODO when we stop falling back to legacy, this and the ERR_pop_to_mark()
79      * calls can be removed.
80      */
81     ERR_set_mark();
82
83     if (locpctx->engine != NULL || locpctx->keytype == NULL)
84         goto legacy;
85
86     /*
87      * Ensure that the key is provided, either natively, or as a cached export.
88      */
89     tmp_keymgmt = locpctx->keymgmt;
90     provkey = evp_pkey_export_to_provider(locpctx->pkey, locpctx->libctx,
91                                           &tmp_keymgmt, locpctx->propquery);
92     if (provkey == NULL) {
93         /*
94          * If we couldn't find a keymgmt at all try legacy.
95          * TODO(3.0): Once all legacy algorithms (SM2, HMAC etc) have provider
96          * based implementations this fallback shouldn't be necessary. Either
97          * we have an ENGINE based implementation (in which case we should have
98          * already fallen back in the test above here), or we don't have the
99          * provider based implementation loaded (in which case this is an
100          * application config error)
101          */
102         if (locpctx->keymgmt == NULL)
103             goto legacy;
104         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
105         goto err;
106     }
107     if (!EVP_KEYMGMT_up_ref(tmp_keymgmt)) {
108         ERR_clear_last_mark();
109         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
110         goto err;
111     }
112     EVP_KEYMGMT_free(locpctx->keymgmt);
113     locpctx->keymgmt = tmp_keymgmt;
114
115     if (locpctx->keymgmt->query_operation_name != NULL)
116         supported_sig =
117             locpctx->keymgmt->query_operation_name(OSSL_OP_SIGNATURE);
118
119     /*
120      * If we didn't get a supported sig, assume there is one with the
121      * same name as the key type.
122      */
123     if (supported_sig == NULL)
124         supported_sig = locpctx->keytype;
125
126     /*
127      * Because we cleared out old ops, we shouldn't need to worry about
128      * checking if signature is already there.
129      */
130     signature = EVP_SIGNATURE_fetch(locpctx->libctx, supported_sig,
131                                     locpctx->propquery);
132
133     if (signature == NULL
134         || (EVP_KEYMGMT_provider(locpctx->keymgmt)
135             != EVP_SIGNATURE_provider(signature))) {
136         /*
137          * We don't need to free ctx->keymgmt here, as it's not necessarily
138          * tied to this operation.  It will be freed by EVP_PKEY_CTX_free().
139          */
140         EVP_SIGNATURE_free(signature);
141         goto legacy;
142     }
143
144     /*
145      * TODO remove this when legacy is gone
146      * If we don't have the full support we need with provided methods,
147      * let's go see if legacy does.
148      */
149     ERR_pop_to_mark();
150
151     /* No more legacy from here down to legacy: */
152
153     if (pctx != NULL)
154         *pctx = locpctx;
155
156     locpctx->op.sig.signature = signature;
157     locpctx->operation = ver ? EVP_PKEY_OP_VERIFYCTX
158                              : EVP_PKEY_OP_SIGNCTX;
159     locpctx->op.sig.sigprovctx
160         = signature->newctx(ossl_provider_ctx(signature->prov), props);
161     if (locpctx->op.sig.sigprovctx == NULL) {
162         ERR_raise(ERR_LIB_EVP,  EVP_R_INITIALIZATION_ERROR);
163         goto err;
164     }
165     if (type != NULL) {
166         ctx->reqdigest = type;
167         if (mdname == NULL)
168             mdname = canon_mdname(EVP_MD_name(type));
169     } else {
170         if (mdname == NULL) {
171             if (evp_keymgmt_util_get_deflt_digest_name(tmp_keymgmt, provkey,
172                                                        locmdname,
173                                                        sizeof(locmdname)) > 0) {
174                 mdname = canon_mdname(locmdname);
175             }
176         }
177
178         if (mdname != NULL) {
179             /*
180              * We're about to get a new digest so clear anything associated with
181              * an old digest.
182              */
183             evp_md_ctx_clear_digest(ctx, 1);
184
185             /*
186              * This might be requested by a later call to EVP_MD_CTX_md().
187              * In that case the "explicit fetch" rules apply for that
188              * function (as per man pages), i.e. the ref count is not updated
189              * so the EVP_MD should not be used beyound the lifetime of the
190              * EVP_MD_CTX.
191              */
192             ctx->digest = ctx->reqdigest = ctx->fetched_digest =
193                 EVP_MD_fetch(locpctx->libctx, mdname, props);
194             if (ctx->digest == NULL) {
195                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
196                 goto err;
197             }
198         }
199     }
200
201     if (ver) {
202         if (signature->digest_verify_init == NULL) {
203             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
204             goto err;
205         }
206         ret = signature->digest_verify_init(locpctx->op.sig.sigprovctx,
207                                             mdname, provkey);
208     } else {
209         if (signature->digest_sign_init == NULL) {
210             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
211             goto err;
212         }
213         ret = signature->digest_sign_init(locpctx->op.sig.sigprovctx,
214                                           mdname, provkey);
215     }
216
217     goto end;
218
219  err:
220     evp_pkey_ctx_free_old_ops(locpctx);
221     locpctx->operation = EVP_PKEY_OP_UNDEFINED;
222     return 0;
223
224  legacy:
225     /*
226      * TODO remove this when legacy is gone
227      * If we don't have the full support we need with provided methods,
228      * let's go see if legacy does.
229      */
230     ERR_pop_to_mark();
231
232     if (type == NULL && mdname != NULL)
233         type = evp_get_digestbyname_ex(locpctx->libctx, mdname);
234
235     if (ctx->pctx->pmeth == NULL) {
236         EVPerr(0, EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE);
237         return 0;
238     }
239
240     if (!(ctx->pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM)) {
241
242         if (type == NULL) {
243             int def_nid;
244             if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) > 0)
245                 type = EVP_get_digestbynid(def_nid);
246         }
247
248         if (type == NULL) {
249             EVPerr(EVP_F_DO_SIGVER_INIT, EVP_R_NO_DEFAULT_DIGEST);
250             return 0;
251         }
252     }
253
254     if (ver) {
255         if (ctx->pctx->pmeth->verifyctx_init) {
256             if (ctx->pctx->pmeth->verifyctx_init(ctx->pctx, ctx) <= 0)
257                 return 0;
258             ctx->pctx->operation = EVP_PKEY_OP_VERIFYCTX;
259         } else if (ctx->pctx->pmeth->digestverify != 0) {
260             ctx->pctx->operation = EVP_PKEY_OP_VERIFY;
261             ctx->update = update;
262         } else if (EVP_PKEY_verify_init(ctx->pctx) <= 0) {
263             return 0;
264         }
265     } else {
266         if (ctx->pctx->pmeth->signctx_init) {
267             if (ctx->pctx->pmeth->signctx_init(ctx->pctx, ctx) <= 0)
268                 return 0;
269             ctx->pctx->operation = EVP_PKEY_OP_SIGNCTX;
270         } else if (ctx->pctx->pmeth->digestsign != 0) {
271             ctx->pctx->operation = EVP_PKEY_OP_SIGN;
272             ctx->update = update;
273         } else if (EVP_PKEY_sign_init(ctx->pctx) <= 0) {
274             return 0;
275         }
276     }
277     if (EVP_PKEY_CTX_set_signature_md(ctx->pctx, type) <= 0)
278         return 0;
279     if (pctx)
280         *pctx = ctx->pctx;
281     if (ctx->pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM)
282         return 1;
283     if (!EVP_DigestInit_ex(ctx, type, e))
284         return 0;
285     /*
286      * This indicates the current algorithm requires
287      * special treatment before hashing the tbs-message.
288      */
289     ctx->pctx->flag_call_digest_custom = 0;
290     if (ctx->pctx->pmeth->digest_custom != NULL)
291         ctx->pctx->flag_call_digest_custom = 1;
292
293     ret = 1;
294
295  end:
296 #ifndef FIPS_MODULE
297     if (ret > 0)
298         ret = evp_pkey_ctx_use_cached_data(locpctx);
299 #endif
300
301     return ret > 0 ? 1 : 0;
302 }
303
304 int EVP_DigestSignInit_with_libctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
305                                    const char *mdname,
306                                    OPENSSL_CTX *libctx, const char *props,
307                                    EVP_PKEY *pkey)
308 {
309     return do_sigver_init(ctx, pctx, NULL, mdname, libctx, props, NULL, pkey, 0);
310 }
311
312 int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
313                        const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey)
314 {
315     return do_sigver_init(ctx, pctx, type, NULL, NULL, NULL, e, pkey, 0);
316 }
317
318 int EVP_DigestVerifyInit_with_libctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
319                                      const char *mdname,
320                                      OPENSSL_CTX *libctx, const char *props,
321                                      EVP_PKEY *pkey)
322 {
323     return do_sigver_init(ctx, pctx, NULL, mdname, libctx, props, NULL, pkey, 1);
324 }
325
326 int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
327                          const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey)
328 {
329     return do_sigver_init(ctx, pctx, type, NULL, NULL, NULL, e, pkey, 1);
330 }
331 #endif /* FIPS_MDOE */
332
333 int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize)
334 {
335     EVP_PKEY_CTX *pctx = ctx->pctx;
336
337     if (pctx == NULL
338             || pctx->operation != EVP_PKEY_OP_SIGNCTX
339             || pctx->op.sig.sigprovctx == NULL
340             || pctx->op.sig.signature == NULL)
341         goto legacy;
342
343     if (pctx->op.sig.signature->digest_sign_update == NULL) {
344         ERR_raise(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
345         return 0;
346     }
347
348     return pctx->op.sig.signature->digest_sign_update(pctx->op.sig.sigprovctx,
349                                                       data, dsize);
350
351  legacy:
352     if (pctx != NULL) {
353         /* do_sigver_init() checked that |digest_custom| is non-NULL */
354         if (pctx->flag_call_digest_custom
355             && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx))
356             return 0;
357         pctx->flag_call_digest_custom = 0;
358     }
359
360     return EVP_DigestUpdate(ctx, data, dsize);
361 }
362
363 int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize)
364 {
365     EVP_PKEY_CTX *pctx = ctx->pctx;
366
367     if (pctx == NULL
368             || pctx->operation != EVP_PKEY_OP_VERIFYCTX
369             || pctx->op.sig.sigprovctx == NULL
370             || pctx->op.sig.signature == NULL)
371         goto legacy;
372
373     if (pctx->op.sig.signature->digest_verify_update == NULL) {
374         ERR_raise(ERR_LIB_EVP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
375         return 0;
376     }
377
378     return pctx->op.sig.signature->digest_verify_update(pctx->op.sig.sigprovctx,
379                                                         data, dsize);
380
381  legacy:
382     if (pctx != NULL) {
383         /* do_sigver_init() checked that |digest_custom| is non-NULL */
384         if (pctx->flag_call_digest_custom
385             && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx))
386             return 0;
387         pctx->flag_call_digest_custom = 0;
388     }
389
390     return EVP_DigestUpdate(ctx, data, dsize);
391 }
392
393 #ifndef FIPS_MODULE
394 int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret,
395                         size_t *siglen)
396 {
397     int sctx = 0, r = 0;
398     EVP_PKEY_CTX *pctx = ctx->pctx;
399
400     if (pctx == NULL
401             || pctx->operation != EVP_PKEY_OP_SIGNCTX
402             || pctx->op.sig.sigprovctx == NULL
403             || pctx->op.sig.signature == NULL)
404         goto legacy;
405
406     return pctx->op.sig.signature->digest_sign_final(pctx->op.sig.sigprovctx,
407                                                      sigret, siglen, SIZE_MAX);
408
409  legacy:
410     if (pctx == NULL || pctx->pmeth == NULL) {
411         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
412         return 0;
413     }
414
415     /* do_sigver_init() checked that |digest_custom| is non-NULL */
416     if (pctx->flag_call_digest_custom
417         && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx))
418         return 0;
419     pctx->flag_call_digest_custom = 0;
420
421     if (pctx->pmeth->flags & EVP_PKEY_FLAG_SIGCTX_CUSTOM) {
422         if (sigret == NULL)
423             return pctx->pmeth->signctx(pctx, sigret, siglen, ctx);
424         if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE)
425             r = pctx->pmeth->signctx(pctx, sigret, siglen, ctx);
426         else {
427             EVP_PKEY_CTX *dctx = EVP_PKEY_CTX_dup(pctx);
428
429             if (dctx == NULL)
430                 return 0;
431             r = dctx->pmeth->signctx(dctx, sigret, siglen, ctx);
432             EVP_PKEY_CTX_free(dctx);
433         }
434         return r;
435     }
436     if (pctx->pmeth->signctx != NULL)
437         sctx = 1;
438     else
439         sctx = 0;
440     if (sigret != NULL) {
441         unsigned char md[EVP_MAX_MD_SIZE];
442         unsigned int mdlen = 0;
443
444         if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) {
445             if (sctx)
446                 r = pctx->pmeth->signctx(pctx, sigret, siglen, ctx);
447             else
448                 r = EVP_DigestFinal_ex(ctx, md, &mdlen);
449         } else {
450             EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new();
451
452             if (tmp_ctx == NULL)
453                 return 0;
454             if (!EVP_MD_CTX_copy_ex(tmp_ctx, ctx)) {
455                 EVP_MD_CTX_free(tmp_ctx);
456                 return 0;
457             }
458             if (sctx)
459                 r = tmp_ctx->pctx->pmeth->signctx(tmp_ctx->pctx,
460                                                   sigret, siglen, tmp_ctx);
461             else
462                 r = EVP_DigestFinal_ex(tmp_ctx, md, &mdlen);
463             EVP_MD_CTX_free(tmp_ctx);
464         }
465         if (sctx || !r)
466             return r;
467         if (EVP_PKEY_sign(pctx, sigret, siglen, md, mdlen) <= 0)
468             return 0;
469     } else {
470         if (sctx) {
471             if (pctx->pmeth->signctx(pctx, sigret, siglen, ctx) <= 0)
472                 return 0;
473         } else {
474             int s = EVP_MD_size(ctx->digest);
475
476             if (s < 0 || EVP_PKEY_sign(pctx, sigret, siglen, NULL, s) <= 0)
477                 return 0;
478         }
479     }
480     return 1;
481 }
482
483 int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret, size_t *siglen,
484                    const unsigned char *tbs, size_t tbslen)
485 {
486     EVP_PKEY_CTX *pctx = ctx->pctx;
487
488     if (pctx != NULL
489             && pctx->operation == EVP_PKEY_OP_SIGNCTX
490             && pctx->op.sig.sigprovctx != NULL
491             && pctx->op.sig.signature != NULL) {
492         if (pctx->op.sig.signature->digest_sign != NULL)
493             return pctx->op.sig.signature->digest_sign(pctx->op.sig.sigprovctx,
494                                                        sigret, siglen, SIZE_MAX,
495                                                        tbs, tbslen);
496     } else {
497         /* legacy */
498         if (ctx->pctx->pmeth != NULL && ctx->pctx->pmeth->digestsign != NULL)
499             return ctx->pctx->pmeth->digestsign(ctx, sigret, siglen, tbs, tbslen);
500     }
501
502     if (sigret != NULL && EVP_DigestSignUpdate(ctx, tbs, tbslen) <= 0)
503         return 0;
504     return EVP_DigestSignFinal(ctx, sigret, siglen);
505 }
506
507 int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig,
508                           size_t siglen)
509 {
510     unsigned char md[EVP_MAX_MD_SIZE];
511     int r = 0;
512     unsigned int mdlen = 0;
513     int vctx = 0;
514     EVP_PKEY_CTX *pctx = ctx->pctx;
515
516     if (pctx == NULL
517             || pctx->operation != EVP_PKEY_OP_VERIFYCTX
518             || pctx->op.sig.sigprovctx == NULL
519             || pctx->op.sig.signature == NULL)
520         goto legacy;
521
522     return pctx->op.sig.signature->digest_verify_final(pctx->op.sig.sigprovctx,
523                                                        sig, siglen);
524
525  legacy:
526     if (pctx == NULL || pctx->pmeth == NULL) {
527         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
528         return 0;
529     }
530
531     /* do_sigver_init() checked that |digest_custom| is non-NULL */
532     if (pctx->flag_call_digest_custom
533         && !ctx->pctx->pmeth->digest_custom(ctx->pctx, ctx))
534         return 0;
535     pctx->flag_call_digest_custom = 0;
536
537     if (pctx->pmeth->verifyctx != NULL)
538         vctx = 1;
539     else
540         vctx = 0;
541     if (ctx->flags & EVP_MD_CTX_FLAG_FINALISE) {
542         if (vctx)
543             r = pctx->pmeth->verifyctx(pctx, sig, siglen, ctx);
544         else
545             r = EVP_DigestFinal_ex(ctx, md, &mdlen);
546     } else {
547         EVP_MD_CTX *tmp_ctx = EVP_MD_CTX_new();
548         if (tmp_ctx == NULL)
549             return -1;
550         if (!EVP_MD_CTX_copy_ex(tmp_ctx, ctx)) {
551             EVP_MD_CTX_free(tmp_ctx);
552             return -1;
553         }
554         if (vctx)
555             r = tmp_ctx->pctx->pmeth->verifyctx(tmp_ctx->pctx,
556                                                 sig, siglen, tmp_ctx);
557         else
558             r = EVP_DigestFinal_ex(tmp_ctx, md, &mdlen);
559         EVP_MD_CTX_free(tmp_ctx);
560     }
561     if (vctx || !r)
562         return r;
563     return EVP_PKEY_verify(pctx, sig, siglen, md, mdlen);
564 }
565
566 int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret,
567                      size_t siglen, const unsigned char *tbs, size_t tbslen)
568 {
569     EVP_PKEY_CTX *pctx = ctx->pctx;
570
571     if (pctx != NULL
572             && pctx->operation == EVP_PKEY_OP_VERIFYCTX
573             && pctx->op.sig.sigprovctx != NULL
574             && pctx->op.sig.signature != NULL) {
575         if (pctx->op.sig.signature->digest_verify != NULL)
576             return pctx->op.sig.signature->digest_verify(pctx->op.sig.sigprovctx,
577                                                          sigret, siglen,
578                                                          tbs, tbslen);
579     } else {
580         /* legacy */
581         if (ctx->pctx->pmeth != NULL && ctx->pctx->pmeth->digestverify != NULL)
582             return ctx->pctx->pmeth->digestverify(ctx, sigret, siglen, tbs, tbslen);
583     }
584
585     if (EVP_DigestVerifyUpdate(ctx, tbs, tbslen) <= 0)
586         return -1;
587     return EVP_DigestVerifyFinal(ctx, sigret, siglen);
588 }
589 #endif /* FIPS_MODULE */