2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2016 Exim maintainers
6 * signing/verification interface
11 #ifndef DISABLE_DKIM /* entire file */
14 # error Need SUPPORT_TLS for DKIM
17 #include "crypt_ver.h"
21 /******************************************************************************/
30 /* accumulate data (gnutls-only). String to be appended must be nul-terminated. */
32 exim_dkim_data_append(gstring * g, uschar * s)
34 return string_cat(g, s);
39 /* import private key from PEM string in memory.
40 Return: NULL for success, or an error string */
43 exim_dkim_signing_init(uschar * privkey_pem, es_ctx * sign_ctx)
49 k.size = strlen(privkey_pem);
51 if ( (rc = gnutls_x509_privkey_init(&sign_ctx->key)) != GNUTLS_E_SUCCESS
52 || (rc = gnutls_x509_privkey_import(sign_ctx->key, &k,
53 GNUTLS_X509_FMT_PEM)) != GNUTLS_E_SUCCESS
55 return gnutls_strerror(rc);
62 /* allocate mem for signature (when signing) */
63 /* sign data (gnutls_only)
67 Return: NULL for success, or an error string */
70 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
72 gnutls_digest_algorithm_t dig;
76 const uschar * ret = NULL;
80 case HASH_SHA1: dig = GNUTLS_DIG_SHA1; break;
81 case HASH_SHA2_256: dig = GNUTLS_DIG_SHA256; break;
82 case HASH_SHA2_512: dig = GNUTLS_DIG_SHA512; break;
83 default: return US"nonhandled hash type";
86 /* Allocate mem for signature */
89 (void) gnutls_x509_privkey_sign_data(sign_ctx->key, dig,
90 0, &k, NULL, &sigsize);
92 sig->data = store_get(sigsize);
96 if ((rc = gnutls_x509_privkey_sign_data(sign_ctx->key, dig,
97 0, &k, sig->data, &sigsize)) != GNUTLS_E_SUCCESS
99 ret = gnutls_strerror(rc);
101 gnutls_x509_privkey_deinit(sign_ctx->key);
107 /* import public key (from DER in memory)
108 Return: NULL for success, or an error string */
111 exim_dkim_verify_init(blob * pubkey_der, ev_ctx * verify_ctx)
115 const uschar * ret = NULL;
117 gnutls_pubkey_init(&verify_ctx->key);
119 k.data = pubkey_der->data;
120 k.size = pubkey_der->len;
122 if ((rc = gnutls_pubkey_import(verify_ctx->key, &k, GNUTLS_X509_FMT_DER))
124 ret = gnutls_strerror(rc);
129 /* verify signature (of hash) (given pubkey & alleged sig)
130 Return: NULL for success, or an error string */
133 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
135 gnutls_sign_algorithm_t algo;
138 const uschar * ret = NULL;
140 /*XXX needs extension for non-rsa */
143 case HASH_SHA1: algo = GNUTLS_SIGN_RSA_SHA1; break;
144 case HASH_SHA2_256: algo = GNUTLS_SIGN_RSA_SHA256; break;
145 case HASH_SHA2_512: algo = GNUTLS_SIGN_RSA_SHA512; break;
146 default: return US"nonhandled hash type";
149 k.data = data_hash->data;
150 k.size = data_hash->len;
153 if ((rc = gnutls_pubkey_verify_hash2(verify_ctx->key, algo, 0, &k, &s)) < 0)
154 ret = gnutls_strerror(rc);
156 gnutls_pubkey_deinit(verify_ctx->key);
163 #elif defined(SIGN_GCRYPT)
164 /******************************************************************************/
165 /* This variant is used under pre-3.0.0 GnuTLS. Only rsa-sha1 and rsa-sha256 */
168 /* Internal service routine:
169 Read and move past an asn.1 header, checking class & tag,
170 optionally returning the data-length */
173 as_tag(blob * der, uschar req_cls, long req_tag, long * alen)
180 /* debug_printf_indent("as_tag: %02x %02x %02x %02x\n",
181 der->data[0], der->data[1], der->data[2], der->data[3]); */
183 if ((rc = asn1_get_tag_der(der->data++, der->len--, &tag_class, &taglen, &tag))
187 if (tag_class != req_cls || tag != req_tag) return ASN1_ELEMENT_NOT_FOUND;
189 if ((len = asn1_get_length_der(der->data, der->len, &taglen)) < 0)
190 return ASN1_DER_ERROR;
191 if (alen) *alen = len;
193 /* debug_printf_indent("as_tag: tlen %d dlen %d\n", taglen, (int)len); */
200 /* Internal service routine:
201 Read and move over an asn.1 integer, setting an MPI to the value
205 as_mpi(blob * der, gcry_mpi_t * mpi)
211 /* integer; move past the header */
212 if ((rc = as_tag(der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
213 return US asn1_strerror(rc);
216 if ((gerr = gcry_mpi_scan(mpi, GCRYMPI_FMT_STD, der->data, alen, NULL)))
217 return US gcry_strerror(gerr);
219 /* move over the data */
220 der->data += alen; der->len -= alen;
229 /* Version check should be the very first call because it
230 makes sure that important subsystems are initialized. */
231 if (!gcry_check_version (GCRYPT_VERSION))
233 fputs ("libgcrypt version mismatch\n", stderr);
237 /* We don't want to see any warnings, e.g. because we have not yet
238 parsed program options which might be used to suppress such
240 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
242 /* ... If required, other initialization goes here. Note that the
243 process might still be running with increased privileges and that
244 the secure memory has not been initialized. */
246 /* Allocate a pool of 16k secure memory. This make the secure memory
247 available and also drops privileges where needed. */
248 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
250 /* It is now okay to let Libgcrypt complain when there was/is
251 a problem with the secure memory. */
252 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
254 /* ... If required, other initialization goes here. */
256 /* Tell Libgcrypt that initialization has completed. */
257 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
265 /* Accumulate data (gnutls-only).
266 String to be appended must be nul-terminated. */
269 exim_dkim_data_append(gstring * g, uschar * s)
276 /* import private key from PEM string in memory.
277 Return: NULL for success, or an error string */
280 exim_dkim_signing_init(uschar * privkey_pem, es_ctx * sign_ctx)
287 /*XXX will need extension to _spot_ as well as handle a
288 non-RSA key? I think... */
291 * RSAPrivateKey ::= SEQUENCE
293 * modulus INTEGER, -- n
294 * publicExponent INTEGER, -- e
295 * privateExponent INTEGER, -- d
296 * prime1 INTEGER, -- p
297 * prime2 INTEGER, -- q
298 * exponent1 INTEGER, -- d mod (p-1)
299 * exponent2 INTEGER, -- d mod (q-1)
300 * coefficient INTEGER, -- (inverse of q) mod p
301 * otherPrimeInfos OtherPrimeInfos OPTIONAL
304 if ( !(s1 = Ustrstr(CS privkey_pem, "-----BEGIN RSA PRIVATE KEY-----"))
305 || !(s2 = Ustrstr(CS (s1+=31), "-----END RSA PRIVATE KEY-----" ))
307 return US"Bad PEM wrapper";
311 if ((der.len = b64decode(s1, &der.data)) < 0)
312 return US"Bad PEM-DER b64 decode";
316 /* sequence; just move past the header */
317 if ((rc = as_tag(&der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
318 != ASN1_SUCCESS) goto asn_err;
320 /* integer version; move past the header, check is zero */
321 if ((rc = as_tag(&der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
323 if (alen != 1 || *der.data != 0)
324 return US"Bad version number";
325 der.data++; der.len--;
327 if ( (s1 = as_mpi(&der, &sign_ctx->n))
328 || (s1 = as_mpi(&der, &sign_ctx->e))
329 || (s1 = as_mpi(&der, &sign_ctx->d))
330 || (s1 = as_mpi(&der, &sign_ctx->p))
331 || (s1 = as_mpi(&der, &sign_ctx->q))
332 || (s1 = as_mpi(&der, &sign_ctx->dp))
333 || (s1 = as_mpi(&der, &sign_ctx->dq))
334 || (s1 = as_mpi(&der, &sign_ctx->qp))
339 DEBUG(D_acl) debug_printf_indent("rsa_signing_init:\n");
342 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->n);
343 debug_printf_indent(" N : %s\n", s);
344 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->e);
345 debug_printf_indent(" E : %s\n", s);
346 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->d);
347 debug_printf_indent(" D : %s\n", s);
348 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->p);
349 debug_printf_indent(" P : %s\n", s);
350 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->q);
351 debug_printf_indent(" Q : %s\n", s);
352 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dp);
353 debug_printf_indent(" DP: %s\n", s);
354 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dq);
355 debug_printf_indent(" DQ: %s\n", s);
356 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->qp);
357 debug_printf_indent(" QP: %s\n", s);
362 asn_err: return US asn1_strerror(rc);
367 /* allocate mem for signature (when signing) */
368 /* sign data (gnutls_only)
372 Return: NULL for success, or an error string */
375 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
378 gcry_sexp_t s_hash = NULL, s_key = NULL, s_sig = NULL;
383 /*XXX will need extension for hash types (though, possibly, should
384 be re-specced to not rehash but take an already-hashed value? Actually
385 current impl looks WRONG - it _is_ given a hash so should not be
386 re-hashing. Has this been tested?
388 Will need extension for non-RSA sugning algos. */
392 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
393 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
394 default: return US"nonhandled hash type";
398 sig->data = store_get(SIGSPACE);
400 if (gcry_mpi_cmp (sign_ctx->p, sign_ctx->q) > 0)
402 gcry_mpi_swap (sign_ctx->p, sign_ctx->q);
403 gcry_mpi_invm (sign_ctx->qp, sign_ctx->p, sign_ctx->q);
406 if ( (gerr = gcry_sexp_build (&s_key, NULL,
407 "(private-key (rsa (n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
408 sign_ctx->n, sign_ctx->e,
409 sign_ctx->d, sign_ctx->p,
410 sign_ctx->q, sign_ctx->qp))
411 || (gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
412 (int) data->len, CS data->data))
413 || (gerr = gcry_pk_sign (&s_sig, s_hash, s_key))
415 return US gcry_strerror(gerr);
417 /* gcry_sexp_dump(s_sig); */
419 if ( !(s_sig = gcry_sexp_find_token(s_sig, "s", 0))
421 return US"no sig result";
423 m_sig = gcry_sexp_nth_mpi(s_sig, 1, GCRYMPI_FMT_USG);
429 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, m_sig);
430 debug_printf_indent(" SG: %s\n", s);
434 gerr = gcry_mpi_print(GCRYMPI_FMT_USG, sig->data, SIGSPACE, &sig->len, m_sig);
437 debug_printf_indent("signature conversion from MPI to buffer failed\n");
438 return US gcry_strerror(gerr);
446 /* import public key (from DER in memory)
447 Return: NULL for success, or an error string */
450 exim_dkim_verify_init(blob * pubkey_der, ev_ctx * verify_ctx)
453 in code sequence per b81207d2bfa92 rsa_parse_public_key() and asn1_get_mpi()
461 uschar * stage = US"S1";
468 BIT STRING:RSAPublicKey
470 INTEGER:Public modulus
471 INTEGER:Public exponent
473 openssl rsa -in aux-fixed/dkim/dkim.private -pubout -outform DER | od -t x1 | head;
474 openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump;
475 openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump -offset 22;
478 /* sequence; just move past the header */
479 if ((rc = as_tag(pubkey_der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
480 != ASN1_SUCCESS) goto asn_err;
482 /* sequence; skip the entire thing */
483 DEBUG(D_acl) stage = US"S2";
484 if ((rc = as_tag(pubkey_der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, &alen))
485 != ASN1_SUCCESS) goto asn_err;
486 pubkey_der->data += alen; pubkey_der->len -= alen;
489 /* bitstring: limit range to size of bitstring;
490 move over header + content wrapper */
491 DEBUG(D_acl) stage = US"BS";
492 if ((rc = as_tag(pubkey_der, 0, ASN1_TAG_BIT_STRING, &alen)) != ASN1_SUCCESS)
494 pubkey_der->len = alen;
495 pubkey_der->data++; pubkey_der->len--;
497 /* sequence; just move past the header */
498 DEBUG(D_acl) stage = US"S3";
499 if ((rc = as_tag(pubkey_der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
500 != ASN1_SUCCESS) goto asn_err;
502 /* read two integers */
503 DEBUG(D_acl) stage = US"MPI";
504 if ( (errstr = as_mpi(pubkey_der, &verify_ctx->n))
505 || (errstr = as_mpi(pubkey_der, &verify_ctx->e))
510 DEBUG(D_acl) debug_printf_indent("rsa_verify_init:\n");
513 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->n);
514 debug_printf_indent(" N : %s\n", s);
515 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->e);
516 debug_printf_indent(" E : %s\n", s);
523 DEBUG(D_acl) return string_sprintf("%s: %s", stage, asn1_strerror(rc));
524 return US asn1_strerror(rc);
528 /* verify signature (of hash) (given pubkey & alleged sig)
529 Return: NULL for success, or an error string */
532 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
535 cf. libgnutls 2.8.5 _wrap_gcry_pk_verify()
539 gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
543 /*XXX needs extension for SHA512 */
546 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
547 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
548 default: return US"nonhandled hash type";
551 if ( (stage = US"pkey sexp build",
552 gerr = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%m)(e%m)))",
553 verify_ctx->n, verify_ctx->e))
554 || (stage = US"data sexp build",
555 gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
556 (int) data_hash->len, CS data_hash->data))
557 || (stage = US"sig mpi scan",
558 gerr = gcry_mpi_scan(&m_sig, GCRYMPI_FMT_USG, sig->data, sig->len, NULL))
559 || (stage = US"sig sexp build",
560 gerr = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%m)))", m_sig))
561 || (stage = US"verify",
562 gerr = gcry_pk_verify (s_sig, s_hash, s_pkey))
565 DEBUG(D_acl) debug_printf_indent("verify: error in stage '%s'\n", stage);
566 return US gcry_strerror(gerr);
569 if (s_sig) gcry_sexp_release (s_sig);
570 if (s_hash) gcry_sexp_release (s_hash);
571 if (s_pkey) gcry_sexp_release (s_pkey);
572 gcry_mpi_release (m_sig);
573 gcry_mpi_release (verify_ctx->n);
574 gcry_mpi_release (verify_ctx->e);
582 #elif defined(SIGN_OPENSSL)
583 /******************************************************************************/
588 ERR_load_crypto_strings();
592 /* accumulate data (gnutls-only) */
594 exim_dkim_data_append(gstring * g, uschar * s)
600 /* import private key from PEM string in memory.
601 Return: NULL for success, or an error string */
604 exim_dkim_signing_init(uschar * privkey_pem, es_ctx * sign_ctx)
606 BIO * bp = BIO_new_mem_buf(privkey_pem, -1);
608 if (!(sign_ctx->key = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL)))
609 return US ERR_error_string(ERR_get_error(), NULL);
615 /* allocate mem for signature (when signing) */
616 /* sign data (gnutls_only)
620 Return: NULL for success with the signaature in the sig blob, or an error string */
623 exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
631 case HASH_SHA1: md = EVP_sha1(); break;
632 case HASH_SHA2_256: md = EVP_sha256(); break;
633 case HASH_SHA2_512: md = EVP_sha512(); break;
634 default: return US"nonhandled hash type";
637 if ( (ctx = EVP_PKEY_CTX_new(sign_ctx->key, NULL))
638 && EVP_PKEY_sign_init(ctx) > 0
639 && EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) > 0
640 && EVP_PKEY_CTX_set_signature_md(ctx, md) > 0
641 && EVP_PKEY_sign(ctx, NULL, &siglen, data->data, data->len) > 0
644 /* Allocate mem for signature */
645 sig->data = store_get(siglen);
647 if (EVP_PKEY_sign(ctx, sig->data, &siglen, data->data, data->len) > 0)
649 EVP_PKEY_CTX_free(ctx);
655 if (ctx) EVP_PKEY_CTX_free(ctx);
656 return US ERR_error_string(ERR_get_error(), NULL);
661 /* import public key (from DER in memory)
662 Return: NULL for success, or an error string */
665 exim_dkim_verify_init(blob * pubkey_der, ev_ctx * verify_ctx)
667 const uschar * s = pubkey_der->data;
669 /*XXX hmm, we never free this */
671 if ((verify_ctx->key = d2i_PUBKEY(NULL, &s, pubkey_der->len)))
673 return US ERR_error_string(ERR_get_error(), NULL);
679 /* verify signature (of hash) (given pubkey & alleged sig)
680 Return: NULL for success, or an error string */
683 exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
690 case HASH_SHA1: md = EVP_sha1(); break;
691 case HASH_SHA2_256: md = EVP_sha256(); break;
692 case HASH_SHA2_512: md = EVP_sha512(); break;
693 default: return US"nonhandled hash type";
696 if ( (ctx = EVP_PKEY_CTX_new(verify_ctx->key, NULL))
697 && EVP_PKEY_verify_init(ctx) > 0
698 && EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) > 0
699 && EVP_PKEY_CTX_set_signature_md(ctx, md) > 0
700 && EVP_PKEY_verify(ctx, sig->data, sig->len,
701 data_hash->data, data_hash->len) == 1
703 { EVP_PKEY_CTX_free(ctx); return NULL; }
705 if (ctx) EVP_PKEY_CTX_free(ctx);
706 return US ERR_error_string(ERR_get_error(), NULL);
712 /******************************************************************************/
714 #endif /*DISABLE_DKIM*/