2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 1995 - 2018 Exim maintainers
6 * signing/verification interface
10 #include "crypt_ver.h"
15 # include "../macro_predef.h"
20 # ifdef SIGN_HAVE_ED25519
21 builtin_macro_create(US"_CRYPTO_SIGN_ED25519");
23 # ifdef EXIM_HAVE_SHA3
24 builtin_macro_create(US"_CRYPTO_HASH_SHA3");
29 #ifndef DISABLE_DKIM /* rest of file */
32 # error Must no DISABLE_TLS, for DKIM
36 /******************************************************************************/
38 # define EXIM_GNUTLS_LIBRARY_LOG_LEVEL 3
41 /* Logging function which can be registered with
42 * gnutls_global_set_log_function()
43 * gnutls_global_set_log_level() 0..9
45 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
47 exim_gnutls_logger_cb(int level, const char *message)
49 size_t len = strlen(message);
52 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
55 DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
56 message[len-1] == '\n' ? "" : "\n");
65 #if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
68 gnutls_global_set_log_function(exim_gnutls_logger_cb);
69 /* arbitrarily chosen level; bump upto 9 for more */
70 gnutls_global_set_log_level(EXIM_GNUTLS_LIBRARY_LOG_LEVEL);
76 /* accumulate data (gnutls-only). String to be appended must be nul-terminated. */
78 exim_dkim_data_append(gstring * g, uschar * s)
80 return string_cat(g, s);
85 /* import private key from PEM string in memory.
86 Return: NULL for success, or an error string */
89 exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
91 gnutls_datum_t k = { .data = (void *)privkey_pem, .size = Ustrlen(privkey_pem) };
92 gnutls_x509_privkey_t x509_key;
96 if ( (where = US"internal init", rc = gnutls_x509_privkey_init(&x509_key))
97 || (rc = gnutls_privkey_init(&sign_ctx->key))
98 || (where = US"privkey PEM-block import",
99 rc = gnutls_x509_privkey_import(x509_key, &k, GNUTLS_X509_FMT_PEM))
100 || (where = US"internal privkey transfer",
101 rc = gnutls_privkey_import_x509(sign_ctx->key, x509_key, 0))
103 return string_sprintf("%s: %s", where, gnutls_strerror(rc));
105 switch (rc = gnutls_privkey_get_pk_algorithm(sign_ctx->key, NULL))
107 case GNUTLS_PK_RSA: sign_ctx->keytype = KEYTYPE_RSA; break;
108 #ifdef SIGN_HAVE_ED25519
109 case GNUTLS_PK_EDDSA_ED25519: sign_ctx->keytype = KEYTYPE_ED25519; break;
111 default: return rc < 0
112 ? CUS gnutls_strerror(rc)
113 : string_sprintf("Unhandled key type: %d '%s'", rc, gnutls_pk_get_name(rc));
121 /* allocate mem for signature (when signing) */
122 /* hash & sign data. No way to do incremental.
124 Return: NULL for success, or an error string */
127 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
129 gnutls_datum_t k_data = { .data = data->data, .size = data->len };
130 gnutls_digest_algorithm_t dig;
131 gnutls_datum_t k_sig;
136 case HASH_SHA1: dig = GNUTLS_DIG_SHA1; break;
137 case HASH_SHA2_256: dig = GNUTLS_DIG_SHA256; break;
138 case HASH_SHA2_512: dig = GNUTLS_DIG_SHA512; break;
139 default: return US"nonhandled hash type";
142 if ((rc = gnutls_privkey_sign_data(sign_ctx->key, dig, 0, &k_data, &k_sig)))
143 return CUS gnutls_strerror(rc);
145 /* Don't care about deinit for the key; shortlived process */
147 sig->data = k_sig.data;
148 sig->len = k_sig.size;
154 /* import public key (from blob in memory)
155 Return: NULL for success, or an error string */
158 exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
162 const uschar * ret = NULL;
164 gnutls_pubkey_init(&verify_ctx->key);
165 k.data = pubkey->data;
166 k.size = pubkey->len;
171 if ((rc = gnutls_pubkey_import(verify_ctx->key, &k, GNUTLS_X509_FMT_DER)))
172 ret = US gnutls_strerror(rc);
174 #ifdef SIGN_HAVE_ED25519
175 case KEYFMT_ED25519_BARE:
176 if ((rc = gnutls_pubkey_import_ecc_raw(verify_ctx->key,
177 GNUTLS_ECC_CURVE_ED25519, &k, NULL)))
178 ret = US gnutls_strerror(rc);
182 ret = US"pubkey format not handled";
189 /* verify signature (of hash if RSA sig, of data if EC sig. No way to do incremental)
190 (given pubkey & alleged sig)
191 Return: NULL for success, or an error string */
194 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
196 gnutls_datum_t k = { .data = data_hash->data, .size = data_hash->len };
197 gnutls_datum_t s = { .data = sig->data, .size = sig->len };
199 const uschar * ret = NULL;
201 #ifdef SIGN_HAVE_ED25519
202 if (verify_ctx->keytype == KEYTYPE_ED25519)
204 if ((rc = gnutls_pubkey_verify_data2(verify_ctx->key,
205 GNUTLS_SIGN_EDDSA_ED25519, 0, &k, &s)) < 0)
206 ret = US gnutls_strerror(rc);
211 gnutls_sign_algorithm_t algo;
214 case HASH_SHA1: algo = GNUTLS_SIGN_RSA_SHA1; break;
215 case HASH_SHA2_256: algo = GNUTLS_SIGN_RSA_SHA256; break;
216 case HASH_SHA2_512: algo = GNUTLS_SIGN_RSA_SHA512; break;
217 default: return US"nonhandled hash type";
220 if ((rc = gnutls_pubkey_verify_hash2(verify_ctx->key, algo, 0, &k, &s)) < 0)
221 ret = US gnutls_strerror(rc);
224 gnutls_pubkey_deinit(verify_ctx->key);
231 #elif defined(SIGN_GCRYPT)
232 /******************************************************************************/
233 /* This variant is used under pre-3.0.0 GnuTLS. Only rsa-sha1 and rsa-sha256 */
236 /* Internal service routine:
237 Read and move past an asn.1 header, checking class & tag,
238 optionally returning the data-length */
241 as_tag(blob * der, uschar req_cls, long req_tag, long * alen)
248 debug_printf_indent("as_tag: %02x %02x %02x %02x\n",
249 der->data[0], der->data[1], der->data[2], der->data[3]);
251 if ((rc = asn1_get_tag_der(der->data++, der->len--, &tag_class, &taglen, &tag))
255 if (tag_class != req_cls || tag != req_tag) return ASN1_ELEMENT_NOT_FOUND;
257 if ((len = asn1_get_length_der(der->data, der->len, &taglen)) < 0)
258 return ASN1_DER_ERROR;
259 if (alen) *alen = len;
261 /* debug_printf_indent("as_tag: tlen %d dlen %d\n", taglen, (int)len); */
268 /* Internal service routine:
269 Read and move over an asn.1 integer, setting an MPI to the value
273 as_mpi(blob * der, gcry_mpi_t * mpi)
279 debug_printf_indent("%s\n", __FUNCTION__);
281 /* integer; move past the header */
282 if ((rc = as_tag(der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
283 return US asn1_strerror(rc);
286 if ((gerr = gcry_mpi_scan(mpi, GCRYMPI_FMT_STD, der->data, alen, NULL)))
287 return US gcry_strerror(gerr);
289 /* move over the data */
290 der->data += alen; der->len -= alen;
299 /* Version check should be the very first call because it
300 makes sure that important subsystems are initialized. */
301 if (!gcry_check_version (GCRYPT_VERSION))
303 fputs ("libgcrypt version mismatch\n", stderr);
307 /* We don't want to see any warnings, e.g. because we have not yet
308 parsed program options which might be used to suppress such
310 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
312 /* ... If required, other initialization goes here. Note that the
313 process might still be running with increased privileges and that
314 the secure memory has not been initialized. */
316 /* Allocate a pool of 16k secure memory. This make the secure memory
317 available and also drops privileges where needed. */
318 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
320 /* It is now okay to let Libgcrypt complain when there was/is
321 a problem with the secure memory. */
322 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
324 /* ... If required, other initialization goes here. */
326 /* Tell Libgcrypt that initialization has completed. */
327 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
335 /* Accumulate data (gnutls-only).
336 String to be appended must be nul-terminated. */
339 exim_dkim_data_append(gstring * g, uschar * s)
346 /* import private key from PEM string in memory.
347 Only handles RSA keys.
348 Return: NULL for success, or an error string */
351 exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
358 /*XXX will need extension to _spot_ as well as handle a
359 non-RSA key? I think...
360 So... this is not a PrivateKeyInfo - which would have a field
361 identifying the keytype - PrivateKeyAlgorithmIdentifier -
362 but a plain RSAPrivateKey (wrapped in PEM-headers. Can we
363 use those as a type tag? What forms are there? "BEGIN EC PRIVATE KEY" (cf. ec(1ssl))
365 How does OpenSSL PEM_read_bio_PrivateKey() deal with it?
366 gnutls_x509_privkey_import() ?
370 * RSAPrivateKey ::= SEQUENCE
372 * modulus INTEGER, -- n
373 * publicExponent INTEGER, -- e
374 * privateExponent INTEGER, -- d
375 * prime1 INTEGER, -- p
376 * prime2 INTEGER, -- q
377 * exponent1 INTEGER, -- d mod (p-1)
378 * exponent2 INTEGER, -- d mod (q-1)
379 * coefficient INTEGER, -- (inverse of q) mod p
380 * otherPrimeInfos OtherPrimeInfos OPTIONAL
382 * ECPrivateKey ::= SEQUENCE {
383 * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
384 * privateKey OCTET STRING,
385 * parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
386 * publicKey [1] BIT STRING OPTIONAL
388 * Hmm, only 1 useful item, and not even an integer? Wonder how we might use it...
390 - actually, gnutls_x509_privkey_import() appears to require a curve name parameter
391 value for that is an OID? a local-only integer (it's an enum in GnuTLS)?
395 ssh-keygen -t ecdsa -f foo.privkey
396 ssh-keygen -t ecdsa -b384 -f foo.privkey
397 ssh-keygen -t ecdsa -b521 -f foo.privkey
398 ssh-keygen -t ed25519 -f foo.privkey
400 < foo openssl pkcs8 -in /dev/stdin -inform PEM -nocrypt -topk8 -outform DER | od -x
402 openssl asn1parse -in foo -inform PEM -dump
403 openssl asn1parse -in foo -inform PEM -dump -stroffset 24 (??)
404 (not good for ed25519)
408 if ( !(s1 = Ustrstr(CS privkey_pem, "-----BEGIN RSA PRIVATE KEY-----"))
409 || !(s2 = Ustrstr(CS (s1+=31), "-----END RSA PRIVATE KEY-----" ))
411 return US"Bad PEM wrapper";
415 if ((rc = b64decode(s1, &der.data) < 0))
416 return US"Bad PEM-DER b64 decode";
421 /* sequence; just move past the header */
422 if ((rc = as_tag(&der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
423 != ASN1_SUCCESS) goto asn_err;
425 /* integer version; move past the header, check is zero */
426 if ((rc = as_tag(&der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
428 if (alen != 1 || *der.data != 0)
429 return US"Bad version number";
430 der.data++; der.len--;
432 if ( (s1 = as_mpi(&der, &sign_ctx->n))
433 || (s1 = as_mpi(&der, &sign_ctx->e))
434 || (s1 = as_mpi(&der, &sign_ctx->d))
435 || (s1 = as_mpi(&der, &sign_ctx->p))
436 || (s1 = as_mpi(&der, &sign_ctx->q))
437 || (s1 = as_mpi(&der, &sign_ctx->dp))
438 || (s1 = as_mpi(&der, &sign_ctx->dq))
439 || (s1 = as_mpi(&der, &sign_ctx->qp))
444 DEBUG(D_acl) debug_printf_indent("rsa_signing_init:\n");
447 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->n);
448 debug_printf_indent(" N : %s\n", s);
449 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->e);
450 debug_printf_indent(" E : %s\n", s);
451 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->d);
452 debug_printf_indent(" D : %s\n", s);
453 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->p);
454 debug_printf_indent(" P : %s\n", s);
455 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->q);
456 debug_printf_indent(" Q : %s\n", s);
457 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dp);
458 debug_printf_indent(" DP: %s\n", s);
459 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dq);
460 debug_printf_indent(" DQ: %s\n", s);
461 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->qp);
462 debug_printf_indent(" QP: %s\n", s);
466 sign_ctx->keytype = KEYTYPE_RSA;
469 asn_err: return US asn1_strerror(rc);
474 /* allocate mem for signature (when signing) */
475 /* sign already-hashed data.
477 Return: NULL for success, or an error string */
480 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
483 gcry_sexp_t s_hash = NULL, s_key = NULL, s_sig = NULL;
488 /*XXX will need extension for hash types (though, possibly, should
489 be re-specced to not rehash but take an already-hashed value? Actually
490 current impl looks WRONG - it _is_ given a hash so should not be
491 re-hashing. Has this been tested?
493 Will need extension for non-RSA sugning algos. */
497 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
498 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
499 default: return US"nonhandled hash type";
503 sig->data = store_get(SIGSPACE, FALSE);
505 if (gcry_mpi_cmp (sign_ctx->p, sign_ctx->q) > 0)
507 gcry_mpi_swap (sign_ctx->p, sign_ctx->q);
508 gcry_mpi_invm (sign_ctx->qp, sign_ctx->p, sign_ctx->q);
511 if ( (gerr = gcry_sexp_build (&s_key, NULL,
512 "(private-key (rsa (n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
513 sign_ctx->n, sign_ctx->e,
514 sign_ctx->d, sign_ctx->p,
515 sign_ctx->q, sign_ctx->qp))
516 || (gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
517 (int) data->len, CS data->data))
518 || (gerr = gcry_pk_sign (&s_sig, s_hash, s_key))
520 return US gcry_strerror(gerr);
522 /* gcry_sexp_dump(s_sig); */
524 if ( !(s_sig = gcry_sexp_find_token(s_sig, "s", 0))
526 return US"no sig result";
528 m_sig = gcry_sexp_nth_mpi(s_sig, 1, GCRYMPI_FMT_USG);
534 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, m_sig);
535 debug_printf_indent(" SG: %s\n", s);
539 gerr = gcry_mpi_print(GCRYMPI_FMT_USG, sig->data, SIGSPACE, &sig->len, m_sig);
542 debug_printf_indent("signature conversion from MPI to buffer failed\n");
543 return US gcry_strerror(gerr);
551 /* import public key (from blob in memory)
552 Return: NULL for success, or an error string */
555 exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
558 in code sequence per b81207d2bfa92 rsa_parse_public_key() and asn1_get_mpi()
566 uschar * stage = US"S1";
568 if (fmt != KEYFMT_DER) return US"pubkey format not handled";
575 BIT STRING:RSAPublicKey
577 INTEGER:Public modulus
578 INTEGER:Public exponent
580 openssl rsa -in aux-fixed/dkim/dkim.private -pubout -outform DER | od -t x1 | head;
581 openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump;
582 openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump -offset 22;
585 /* sequence; just move past the header */
586 if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
587 != ASN1_SUCCESS) goto asn_err;
589 /* sequence; skip the entire thing */
590 DEBUG(D_acl) stage = US"S2";
591 if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, &alen))
592 != ASN1_SUCCESS) goto asn_err;
593 pubkey->data += alen; pubkey->len -= alen;
596 /* bitstring: limit range to size of bitstring;
597 move over header + content wrapper */
598 DEBUG(D_acl) stage = US"BS";
599 if ((rc = as_tag(pubkey, 0, ASN1_TAG_BIT_STRING, &alen)) != ASN1_SUCCESS)
602 pubkey->data++; pubkey->len--;
604 /* sequence; just move past the header */
605 DEBUG(D_acl) stage = US"S3";
606 if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
607 != ASN1_SUCCESS) goto asn_err;
609 /* read two integers */
610 DEBUG(D_acl) stage = US"MPI";
611 if ( (errstr = as_mpi(pubkey, &verify_ctx->n))
612 || (errstr = as_mpi(pubkey, &verify_ctx->e))
617 DEBUG(D_acl) debug_printf_indent("rsa_verify_init:\n");
620 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->n);
621 debug_printf_indent(" N : %s\n", s);
622 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->e);
623 debug_printf_indent(" E : %s\n", s);
630 DEBUG(D_acl) return string_sprintf("%s: %s", stage, asn1_strerror(rc));
631 return US asn1_strerror(rc);
635 /* verify signature (of hash)
636 XXX though we appear to be doing a hash, too!
637 (given pubkey & alleged sig)
638 Return: NULL for success, or an error string */
641 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
644 cf. libgnutls 2.8.5 _wrap_gcry_pk_verify()
648 gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
652 /*XXX needs extension for SHA512 */
655 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
656 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
657 default: return US"nonhandled hash type";
660 if ( (stage = US"pkey sexp build",
661 gerr = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%m)(e%m)))",
662 verify_ctx->n, verify_ctx->e))
663 || (stage = US"data sexp build",
664 gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
665 (int) data_hash->len, CS data_hash->data))
666 || (stage = US"sig mpi scan",
667 gerr = gcry_mpi_scan(&m_sig, GCRYMPI_FMT_USG, sig->data, sig->len, NULL))
668 || (stage = US"sig sexp build",
669 gerr = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%m)))", m_sig))
670 || (stage = US"verify",
671 gerr = gcry_pk_verify (s_sig, s_hash, s_pkey))
674 DEBUG(D_acl) debug_printf_indent("verify: error in stage '%s'\n", stage);
675 return US gcry_strerror(gerr);
678 if (s_sig) gcry_sexp_release (s_sig);
679 if (s_hash) gcry_sexp_release (s_hash);
680 if (s_pkey) gcry_sexp_release (s_pkey);
681 gcry_mpi_release (m_sig);
682 gcry_mpi_release (verify_ctx->n);
683 gcry_mpi_release (verify_ctx->e);
691 #elif defined(SIGN_OPENSSL)
692 /******************************************************************************/
697 ERR_load_crypto_strings();
701 /* accumulate data (was gnutls-only but now needed for OpenSSL non-EC too
702 because now using hash-and-sign interface) */
704 exim_dkim_data_append(gstring * g, uschar * s)
706 return string_cat(g, s);
710 /* import private key from PEM string in memory.
711 Return: NULL for success, or an error string */
714 exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
716 BIO * bp = BIO_new_mem_buf((void *)privkey_pem, -1);
718 if (!(sign_ctx->key = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL)))
719 return string_sprintf("privkey PEM-block import: %s",
720 ERR_error_string(ERR_get_error(), NULL));
723 #ifdef SIGN_HAVE_ED25519
724 EVP_PKEY_type(EVP_PKEY_id(sign_ctx->key)) == EVP_PKEY_ED25519
725 ? KEYTYPE_ED25519 : KEYTYPE_RSA;
734 /* allocate mem for signature (when signing) */
735 /* hash & sign data. Incremental not supported.
737 Return: NULL for success with the signaature in the sig blob, or an error string */
740 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
748 case HASH_NULL: md = NULL; break; /* Ed25519 signing */
749 case HASH_SHA1: md = EVP_sha1(); break;
750 case HASH_SHA2_256: md = EVP_sha256(); break;
751 case HASH_SHA2_512: md = EVP_sha512(); break;
752 default: return US"nonhandled hash type";
755 #ifdef SIGN_HAVE_ED25519
756 if ( (ctx = EVP_MD_CTX_new())
757 && EVP_DigestSignInit(ctx, NULL, md, NULL, sign_ctx->key) > 0
758 && EVP_DigestSign(ctx, NULL, &siglen, NULL, 0) > 0
759 && (sig->data = store_get(siglen, FALSE))
761 /* Obtain the signature (slen could change here!) */
762 && EVP_DigestSign(ctx, sig->data, &siglen, data->data, data->len) > 0
765 EVP_MD_CTX_destroy(ctx);
770 /*XXX renamed to EVP_MD_CTX_new() in 1.1.0 */
771 if ( (ctx = EVP_MD_CTX_create())
772 && EVP_DigestSignInit(ctx, NULL, md, NULL, sign_ctx->key) > 0
773 && EVP_DigestSignUpdate(ctx, data->data, data->len) > 0
774 && EVP_DigestSignFinal(ctx, NULL, &siglen) > 0
775 && (sig->data = store_get(siglen, FALSE))
777 /* Obtain the signature (slen could change here!) */
778 && EVP_DigestSignFinal(ctx, sig->data, &siglen) > 0
781 EVP_MD_CTX_destroy(ctx);
787 if (ctx) EVP_MD_CTX_destroy(ctx);
788 return US ERR_error_string(ERR_get_error(), NULL);
793 /* import public key (from blob in memory)
794 Return: NULL for success, or an error string */
797 exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
799 const uschar * s = pubkey->data;
805 /*XXX hmm, we never free this */
806 if (!(verify_ctx->key = d2i_PUBKEY(NULL, &s, pubkey->len)))
807 ret = US ERR_error_string(ERR_get_error(), NULL);
809 #ifdef SIGN_HAVE_ED25519
810 case KEYFMT_ED25519_BARE:
811 if (!(verify_ctx->key = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, NULL,
813 ret = US ERR_error_string(ERR_get_error(), NULL);
817 ret = US"pubkey format not handled";
827 /* verify signature (of hash, except Ed25519 where of-data)
828 (given pubkey & alleged sig)
829 Return: NULL for success, or an error string */
832 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data, blob * sig)
838 case HASH_NULL: md = NULL; break;
839 case HASH_SHA1: md = EVP_sha1(); break;
840 case HASH_SHA2_256: md = EVP_sha256(); break;
841 case HASH_SHA2_512: md = EVP_sha512(); break;
842 default: return US"nonhandled hash type";
845 #ifdef SIGN_HAVE_ED25519
850 if ((ctx = EVP_MD_CTX_new()))
852 if ( EVP_DigestVerifyInit(ctx, NULL, md, NULL, verify_ctx->key) > 0
853 && EVP_DigestVerify(ctx, sig->data, sig->len, data->data, data->len) > 0
855 { EVP_MD_CTX_free(ctx); return NULL; }
856 EVP_MD_CTX_free(ctx);
864 if ((ctx = EVP_PKEY_CTX_new(verify_ctx->key, NULL)))
866 if ( EVP_PKEY_verify_init(ctx) > 0
867 && EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) > 0
868 && EVP_PKEY_CTX_set_signature_md(ctx, md) > 0
869 && EVP_PKEY_verify(ctx, sig->data, sig->len,
870 data->data, data->len) == 1
872 { EVP_PKEY_CTX_free(ctx); return NULL; }
873 EVP_PKEY_CTX_free(ctx);
876 if (Ustrcmp(ERR_reason_error_string(ERR_peek_error()), "wrong signature length") == 0)
877 debug_printf("sig len (from msg hdr): %d, expected (from dns pubkey) %d\n",
878 (int) sig->len, EVP_PKEY_size(verify_ctx->key));
882 return US ERR_error_string(ERR_get_error(), NULL);
888 /******************************************************************************/
890 #endif /*DISABLE_DKIM*/
891 #endif /*MACRO_PREDEF*/