Logging: bump limit on initial-connect synch-error log line
[exim.git] / src / src / pdkim / signing.c
CommitLineData
2592e6c0
JH
1/*
2 * PDKIM - a RFC4871 (DKIM) implementation
3 *
f9ba5e22 4 * Copyright (C) 1995 - 2018 Exim maintainers
2592e6c0 5 *
d73e45df 6 * signing/verification interface
2592e6c0
JH
7 */
8
9#include "../exim.h"
260958d6
JH
10#include "crypt_ver.h"
11#include "signing.h"
12
13
14#ifdef MACRO_PREDEF
15# include "../macro_predef.h"
16
17void
18features_crypto(void)
19{
20# ifdef SIGN_HAVE_ED25519
21 builtin_macro_create(US"_CRYPTO_SIGN_ED25519");
22# endif
23# ifdef EXIM_HAVE_SHA3
24 builtin_macro_create(US"_CRYPTO_HASH_SHA3");
25# endif
26}
27#else
2592e6c0 28
260958d6 29#ifndef DISABLE_DKIM /* rest of file */
2592e6c0 30
01603eec
JH
31#ifdef DISABLE_TLS
32# error Must no DISABLE_TLS, for DKIM
2592e6c0
JH
33#endif
34
2592e6c0
JH
35
36/******************************************************************************/
d73e45df 37#ifdef SIGN_GNUTLS
286b9d5f
JH
38# define EXIM_GNUTLS_LIBRARY_LOG_LEVEL 3
39
40
41/* Logging function which can be registered with
42 * gnutls_global_set_log_function()
43 * gnutls_global_set_log_level() 0..9
44 */
45#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
46static void
47exim_gnutls_logger_cb(int level, const char *message)
48{
49size_t len = strlen(message);
50if (len < 1)
51 {
52 DEBUG(D_tls) debug_printf("GnuTLS<%d> empty debug message\n", level);
53 return;
54 }
55DEBUG(D_tls) debug_printf("GnuTLS<%d>: %s%s", level, message,
56 message[len-1] == '\n' ? "" : "\n");
57}
58#endif
59
60
2592e6c0
JH
61
62void
9b2583c4 63exim_dkim_init(void)
2592e6c0 64{
286b9d5f
JH
65#if EXIM_GNUTLS_LIBRARY_LOG_LEVEL >= 0
66DEBUG(D_tls)
67 {
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);
71 }
72#endif
2592e6c0
JH
73}
74
75
76/* accumulate data (gnutls-only). String to be appended must be nul-terminated. */
acec9514
JH
77gstring *
78exim_dkim_data_append(gstring * g, uschar * s)
2592e6c0 79{
acec9514 80return string_cat(g, s);
2592e6c0
JH
81}
82
83
84
85/* import private key from PEM string in memory.
86Return: NULL for success, or an error string */
87
88const uschar *
617d3932 89exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
2592e6c0 90{
cb78c1a8 91gnutls_datum_t k = { .data = (void *)privkey_pem, .size = Ustrlen(privkey_pem) };
286b9d5f 92gnutls_x509_privkey_t x509_key;
c59b09dc 93const uschar * where;
2592e6c0
JH
94int rc;
95
c59b09dc 96if ( (where = US"internal init", rc = gnutls_x509_privkey_init(&x509_key))
286b9d5f 97 || (rc = gnutls_privkey_init(&sign_ctx->key))
c59b09dc
JH
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))
2592e6c0 102 )
c59b09dc 103 return string_sprintf("%s: %s", where, gnutls_strerror(rc));
286b9d5f
JH
104
105switch (rc = gnutls_privkey_get_pk_algorithm(sign_ctx->key, NULL))
106 {
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;
110#endif
111 default: return rc < 0
112 ? CUS gnutls_strerror(rc)
113 : string_sprintf("Unhandled key type: %d '%s'", rc, gnutls_pk_get_name(rc));
114 }
2592e6c0
JH
115
116return NULL;
117}
118
119
120
121/* allocate mem for signature (when signing) */
286b9d5f 122/* hash & sign data. No way to do incremental.
2592e6c0
JH
123
124Return: NULL for success, or an error string */
125
126const uschar *
d73e45df 127exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 128{
286b9d5f 129gnutls_datum_t k_data = { .data = data->data, .size = data->len };
d73e45df 130gnutls_digest_algorithm_t dig;
286b9d5f 131gnutls_datum_t k_sig;
2592e6c0 132int rc;
2592e6c0 133
d73e45df
JH
134switch (hash)
135 {
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";
140 }
141
286b9d5f
JH
142if ((rc = gnutls_privkey_sign_data(sign_ctx->key, dig, 0, &k_data, &k_sig)))
143 return CUS gnutls_strerror(rc);
2592e6c0 144
286b9d5f 145/* Don't care about deinit for the key; shortlived process */
2592e6c0 146
286b9d5f
JH
147sig->data = k_sig.data;
148sig->len = k_sig.size;
149return NULL;
2592e6c0
JH
150}
151
152
153
286b9d5f 154/* import public key (from blob in memory)
2592e6c0
JH
155Return: NULL for success, or an error string */
156
157const uschar *
286b9d5f 158exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
2592e6c0
JH
159{
160gnutls_datum_t k;
161int rc;
162const uschar * ret = NULL;
163
d73e45df 164gnutls_pubkey_init(&verify_ctx->key);
286b9d5f
JH
165k.data = pubkey->data;
166k.size = pubkey->len;
2592e6c0 167
286b9d5f
JH
168switch(fmt)
169 {
170 case KEYFMT_DER:
171 if ((rc = gnutls_pubkey_import(verify_ctx->key, &k, GNUTLS_X509_FMT_DER)))
48224640 172 ret = US gnutls_strerror(rc);
286b9d5f
JH
173 break;
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)))
48224640 178 ret = US gnutls_strerror(rc);
286b9d5f
JH
179 break;
180#endif
181 default:
182 ret = US"pubkey format not handled";
183 break;
184 }
2592e6c0
JH
185return ret;
186}
187
188
286b9d5f
JH
189/* verify signature (of hash if RSA sig, of data if EC sig. No way to do incremental)
190(given pubkey & alleged sig)
2592e6c0
JH
191Return: NULL for success, or an error string */
192
193const uschar *
d73e45df 194exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
2592e6c0 195{
286b9d5f
JH
196gnutls_datum_t k = { .data = data_hash->data, .size = data_hash->len };
197gnutls_datum_t s = { .data = sig->data, .size = sig->len };
2592e6c0
JH
198int rc;
199const uschar * ret = NULL;
200
286b9d5f
JH
201#ifdef SIGN_HAVE_ED25519
202if (verify_ctx->keytype == KEYTYPE_ED25519)
d73e45df 203 {
286b9d5f
JH
204 if ((rc = gnutls_pubkey_verify_data2(verify_ctx->key,
205 GNUTLS_SIGN_EDDSA_ED25519, 0, &k, &s)) < 0)
48224640 206 ret = US gnutls_strerror(rc);
d73e45df 207 }
286b9d5f
JH
208else
209#endif
210 {
211 gnutls_sign_algorithm_t algo;
212 switch (hash)
213 {
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";
218 }
d73e45df 219
286b9d5f 220 if ((rc = gnutls_pubkey_verify_hash2(verify_ctx->key, algo, 0, &k, &s)) < 0)
48224640 221 ret = US gnutls_strerror(rc);
286b9d5f 222 }
2592e6c0 223
d73e45df 224gnutls_pubkey_deinit(verify_ctx->key);
2592e6c0
JH
225return ret;
226}
227
228
229
230
d73e45df 231#elif defined(SIGN_GCRYPT)
2592e6c0 232/******************************************************************************/
d73e45df 233/* This variant is used under pre-3.0.0 GnuTLS. Only rsa-sha1 and rsa-sha256 */
2592e6c0
JH
234
235
236/* Internal service routine:
237Read and move past an asn.1 header, checking class & tag,
238optionally returning the data-length */
239
240static int
241as_tag(blob * der, uschar req_cls, long req_tag, long * alen)
242{
243int rc;
244uschar tag_class;
245int taglen;
246long tag, len;
247
286b9d5f
JH
248debug_printf_indent("as_tag: %02x %02x %02x %02x\n",
249 der->data[0], der->data[1], der->data[2], der->data[3]);
2592e6c0
JH
250
251if ((rc = asn1_get_tag_der(der->data++, der->len--, &tag_class, &taglen, &tag))
252 != ASN1_SUCCESS)
253 return rc;
254
255if (tag_class != req_cls || tag != req_tag) return ASN1_ELEMENT_NOT_FOUND;
256
257if ((len = asn1_get_length_der(der->data, der->len, &taglen)) < 0)
258 return ASN1_DER_ERROR;
259if (alen) *alen = len;
260
6e4aaa85 261/* debug_printf_indent("as_tag: tlen %d dlen %d\n", taglen, (int)len); */
2592e6c0
JH
262
263der->data += taglen;
264der->len -= taglen;
265return rc;
266}
267
268/* Internal service routine:
269Read and move over an asn.1 integer, setting an MPI to the value
270*/
271
272static uschar *
273as_mpi(blob * der, gcry_mpi_t * mpi)
274{
275long alen;
276int rc;
277gcry_error_t gerr;
278
286b9d5f
JH
279debug_printf_indent("%s\n", __FUNCTION__);
280
2592e6c0
JH
281/* integer; move past the header */
282if ((rc = as_tag(der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
283 return US asn1_strerror(rc);
284
285/* read to an MPI */
286if ((gerr = gcry_mpi_scan(mpi, GCRYMPI_FMT_STD, der->data, alen, NULL)))
287 return US gcry_strerror(gerr);
288
289/* move over the data */
290der->data += alen; der->len -= alen;
291return NULL;
292}
293
294
295
296void
9b2583c4 297exim_dkim_init(void)
2592e6c0
JH
298{
299/* Version check should be the very first call because it
300makes sure that important subsystems are initialized. */
301if (!gcry_check_version (GCRYPT_VERSION))
302 {
303 fputs ("libgcrypt version mismatch\n", stderr);
304 exit (2);
305 }
306
307/* We don't want to see any warnings, e.g. because we have not yet
308parsed program options which might be used to suppress such
309warnings. */
310gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
311
312/* ... If required, other initialization goes here. Note that the
313process might still be running with increased privileges and that
314the secure memory has not been initialized. */
315
316/* Allocate a pool of 16k secure memory. This make the secure memory
317available and also drops privileges where needed. */
318gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
319
320/* It is now okay to let Libgcrypt complain when there was/is
321a problem with the secure memory. */
322gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
323
324/* ... If required, other initialization goes here. */
325
326/* Tell Libgcrypt that initialization has completed. */
327gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
328
329return;
330}
331
332
333
334
335/* Accumulate data (gnutls-only).
336String to be appended must be nul-terminated. */
337
acec9514
JH
338gstring *
339exim_dkim_data_append(gstring * g, uschar * s)
2592e6c0 340{
acec9514 341return g; /*dummy*/
2592e6c0
JH
342}
343
344
345
346/* import private key from PEM string in memory.
286b9d5f 347Only handles RSA keys.
2592e6c0
JH
348Return: NULL for success, or an error string */
349
350const uschar *
617d3932 351exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
2592e6c0
JH
352{
353uschar * s1, * s2;
354blob der;
355long alen;
356int rc;
357
9b2583c4 358/*XXX will need extension to _spot_ as well as handle a
286b9d5f
JH
359non-RSA key? I think...
360So... this is not a PrivateKeyInfo - which would have a field
361identifying the keytype - PrivateKeyAlgorithmIdentifier -
362but a plain RSAPrivateKey (wrapped in PEM-headers. Can we
363use those as a type tag? What forms are there? "BEGIN EC PRIVATE KEY" (cf. ec(1ssl))
364
365How does OpenSSL PEM_read_bio_PrivateKey() deal with it?
366gnutls_x509_privkey_import() ?
367*/
9b2583c4 368
2592e6c0
JH
369/*
370 * RSAPrivateKey ::= SEQUENCE
371 * version Version,
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
286b9d5f
JH
381
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
387 * }
388 * Hmm, only 1 useful item, and not even an integer? Wonder how we might use it...
389
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)?
392
393
394Useful cmds:
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
399
400 < foo openssl pkcs8 -in /dev/stdin -inform PEM -nocrypt -topk8 -outform DER | od -x
401
402 openssl asn1parse -in foo -inform PEM -dump
403 openssl asn1parse -in foo -inform PEM -dump -stroffset 24 (??)
404(not good for ed25519)
405
2592e6c0 406 */
f9ba5e22 407
2592e6c0
JH
408if ( !(s1 = Ustrstr(CS privkey_pem, "-----BEGIN RSA PRIVATE KEY-----"))
409 || !(s2 = Ustrstr(CS (s1+=31), "-----END RSA PRIVATE KEY-----" ))
410 )
411 return US"Bad PEM wrapper";
412
413*s2 = '\0';
414
428cdca7 415if ((rc = b64decode(s1, &der.data) < 0))
2592e6c0 416 return US"Bad PEM-DER b64 decode";
428cdca7 417der.len = rc;
2592e6c0
JH
418
419/* untangle asn.1 */
420
421/* sequence; just move past the header */
422if ((rc = as_tag(&der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
423 != ASN1_SUCCESS) goto asn_err;
424
425/* integer version; move past the header, check is zero */
426if ((rc = as_tag(&der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
427 goto asn_err;
428if (alen != 1 || *der.data != 0)
429 return US"Bad version number";
430der.data++; der.len--;
431
432if ( (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))
440 )
441 return s1;
442
349d0869 443#ifdef extreme_debug
6e4aaa85 444DEBUG(D_acl) debug_printf_indent("rsa_signing_init:\n");
2592e6c0
JH
445 {
446 uschar * s;
447 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->n);
6e4aaa85 448 debug_printf_indent(" N : %s\n", s);
2592e6c0 449 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->e);
6e4aaa85 450 debug_printf_indent(" E : %s\n", s);
2592e6c0 451 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->d);
6e4aaa85 452 debug_printf_indent(" D : %s\n", s);
2592e6c0 453 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->p);
6e4aaa85 454 debug_printf_indent(" P : %s\n", s);
2592e6c0 455 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->q);
6e4aaa85 456 debug_printf_indent(" Q : %s\n", s);
2592e6c0 457 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dp);
6e4aaa85 458 debug_printf_indent(" DP: %s\n", s);
2592e6c0 459 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dq);
6e4aaa85 460 debug_printf_indent(" DQ: %s\n", s);
2592e6c0 461 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->qp);
6e4aaa85 462 debug_printf_indent(" QP: %s\n", s);
2592e6c0 463 }
349d0869 464#endif
286b9d5f
JH
465
466sign_ctx->keytype = KEYTYPE_RSA;
2592e6c0
JH
467return NULL;
468
469asn_err: return US asn1_strerror(rc);
470}
471
472
473
474/* allocate mem for signature (when signing) */
286b9d5f 475/* sign already-hashed data.
2592e6c0
JH
476
477Return: NULL for success, or an error string */
478
479const uschar *
d73e45df 480exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 481{
349d0869 482char * sexp_hash;
2592e6c0
JH
483gcry_sexp_t s_hash = NULL, s_key = NULL, s_sig = NULL;
484gcry_mpi_t m_sig;
485uschar * errstr;
486gcry_error_t gerr;
487
9b2583c4
JH
488/*XXX will need extension for hash types (though, possibly, should
489be re-specced to not rehash but take an already-hashed value? Actually
d73e45df 490current impl looks WRONG - it _is_ given a hash so should not be
9b2583c4
JH
491re-hashing. Has this been tested?
492
493Will need extension for non-RSA sugning algos. */
494
d73e45df
JH
495switch (hash)
496 {
349d0869
JH
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;
d73e45df
JH
499 default: return US"nonhandled hash type";
500 }
501
2592e6c0 502#define SIGSPACE 128
f3ebb786 503sig->data = store_get(SIGSPACE, FALSE);
2592e6c0
JH
504
505if (gcry_mpi_cmp (sign_ctx->p, sign_ctx->q) > 0)
506 {
507 gcry_mpi_swap (sign_ctx->p, sign_ctx->q);
508 gcry_mpi_invm (sign_ctx->qp, sign_ctx->p, sign_ctx->q);
509 }
510
511if ( (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))
349d0869 516 || (gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
2592e6c0
JH
517 (int) data->len, CS data->data))
518 || (gerr = gcry_pk_sign (&s_sig, s_hash, s_key))
519 )
520 return US gcry_strerror(gerr);
521
522/* gcry_sexp_dump(s_sig); */
523
524if ( !(s_sig = gcry_sexp_find_token(s_sig, "s", 0))
525 )
526 return US"no sig result";
527
528m_sig = gcry_sexp_nth_mpi(s_sig, 1, GCRYMPI_FMT_USG);
529
349d0869 530#ifdef extreme_debug
2592e6c0
JH
531DEBUG(D_acl)
532 {
533 uschar * s;
534 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, m_sig);
6e4aaa85 535 debug_printf_indent(" SG: %s\n", s);
2592e6c0 536 }
349d0869 537#endif
2592e6c0
JH
538
539gerr = gcry_mpi_print(GCRYMPI_FMT_USG, sig->data, SIGSPACE, &sig->len, m_sig);
540if (gerr)
541 {
6e4aaa85 542 debug_printf_indent("signature conversion from MPI to buffer failed\n");
2592e6c0
JH
543 return US gcry_strerror(gerr);
544 }
545#undef SIGSPACE
546
547return NULL;
548}
549
550
286b9d5f 551/* import public key (from blob in memory)
2592e6c0
JH
552Return: NULL for success, or an error string */
553
554const uschar *
286b9d5f 555exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
2592e6c0
JH
556{
557/*
558in code sequence per b81207d2bfa92 rsa_parse_public_key() and asn1_get_mpi()
559*/
560uschar tag_class;
561int taglen;
562long alen;
563int rc;
564uschar * errstr;
565gcry_error_t gerr;
566uschar * stage = US"S1";
567
286b9d5f
JH
568if (fmt != KEYFMT_DER) return US"pubkey format not handled";
569
2592e6c0
JH
570/*
571sequence
572 sequence
573 OBJECT:rsaEncryption
574 NULL
575 BIT STRING:RSAPublicKey
576 sequence
577 INTEGER:Public modulus
578 INTEGER:Public exponent
579
580openssl rsa -in aux-fixed/dkim/dkim.private -pubout -outform DER | od -t x1 | head;
581openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump;
582openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump -offset 22;
583*/
584
585/* sequence; just move past the header */
286b9d5f 586if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
2592e6c0
JH
587 != ASN1_SUCCESS) goto asn_err;
588
589/* sequence; skip the entire thing */
590DEBUG(D_acl) stage = US"S2";
286b9d5f 591if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, &alen))
2592e6c0 592 != ASN1_SUCCESS) goto asn_err;
286b9d5f 593pubkey->data += alen; pubkey->len -= alen;
2592e6c0
JH
594
595
596/* bitstring: limit range to size of bitstring;
597move over header + content wrapper */
598DEBUG(D_acl) stage = US"BS";
286b9d5f 599if ((rc = as_tag(pubkey, 0, ASN1_TAG_BIT_STRING, &alen)) != ASN1_SUCCESS)
2592e6c0 600 goto asn_err;
286b9d5f
JH
601pubkey->len = alen;
602pubkey->data++; pubkey->len--;
2592e6c0
JH
603
604/* sequence; just move past the header */
605DEBUG(D_acl) stage = US"S3";
286b9d5f 606if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
2592e6c0
JH
607 != ASN1_SUCCESS) goto asn_err;
608
609/* read two integers */
610DEBUG(D_acl) stage = US"MPI";
286b9d5f
JH
611if ( (errstr = as_mpi(pubkey, &verify_ctx->n))
612 || (errstr = as_mpi(pubkey, &verify_ctx->e))
2592e6c0
JH
613 )
614 return errstr;
615
349d0869 616#ifdef extreme_debug
6e4aaa85 617DEBUG(D_acl) debug_printf_indent("rsa_verify_init:\n");
2592e6c0
JH
618 {
619 uschar * s;
620 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->n);
6e4aaa85 621 debug_printf_indent(" N : %s\n", s);
2592e6c0 622 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->e);
6e4aaa85 623 debug_printf_indent(" E : %s\n", s);
2592e6c0
JH
624 }
625
349d0869 626#endif
2592e6c0
JH
627return NULL;
628
629asn_err:
630DEBUG(D_acl) return string_sprintf("%s: %s", stage, asn1_strerror(rc));
631 return US asn1_strerror(rc);
632}
633
634
286b9d5f
JH
635/* verify signature (of hash)
636XXX though we appear to be doing a hash, too!
637(given pubkey & alleged sig)
2592e6c0
JH
638Return: NULL for success, or an error string */
639
640const uschar *
d73e45df 641exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
2592e6c0
JH
642{
643/*
644cf. libgnutls 2.8.5 _wrap_gcry_pk_verify()
645*/
349d0869 646char * sexp_hash;
2592e6c0
JH
647gcry_mpi_t m_sig;
648gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
649gcry_error_t gerr;
650uschar * stage;
651
349d0869 652/*XXX needs extension for SHA512 */
d73e45df
JH
653switch (hash)
654 {
349d0869
JH
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";
d73e45df
JH
658 }
659
2592e6c0
JH
660if ( (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",
349d0869 664 gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
2592e6c0
JH
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))
672 )
673 {
6e4aaa85 674 DEBUG(D_acl) debug_printf_indent("verify: error in stage '%s'\n", stage);
2592e6c0
JH
675 return US gcry_strerror(gerr);
676 }
677
678if (s_sig) gcry_sexp_release (s_sig);
679if (s_hash) gcry_sexp_release (s_hash);
680if (s_pkey) gcry_sexp_release (s_pkey);
681gcry_mpi_release (m_sig);
682gcry_mpi_release (verify_ctx->n);
683gcry_mpi_release (verify_ctx->e);
684
685return NULL;
686}
687
688
689
690
d73e45df 691#elif defined(SIGN_OPENSSL)
2592e6c0
JH
692/******************************************************************************/
693
694void
9b2583c4 695exim_dkim_init(void)
2592e6c0 696{
9e70917d 697ERR_load_crypto_strings();
2592e6c0
JH
698}
699
700
617d3932 701/* accumulate data (was gnutls-only but now needed for OpenSSL non-EC too
286b9d5f 702because now using hash-and-sign interface) */
acec9514
JH
703gstring *
704exim_dkim_data_append(gstring * g, uschar * s)
2592e6c0 705{
286b9d5f 706return string_cat(g, s);
2592e6c0
JH
707}
708
709
710/* import private key from PEM string in memory.
711Return: NULL for success, or an error string */
712
713const uschar *
617d3932 714exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
2592e6c0 715{
d70fc283 716BIO * bp = BIO_new_mem_buf((void *)privkey_pem, -1);
2592e6c0 717
d73e45df 718if (!(sign_ctx->key = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL)))
c59b09dc
JH
719 return string_sprintf("privkey PEM-block import: %s",
720 ERR_error_string(ERR_get_error(), NULL));
286b9d5f
JH
721
722sign_ctx->keytype =
723#ifdef SIGN_HAVE_ED25519
cb78c1a8 724 EVP_PKEY_type(EVP_PKEY_id(sign_ctx->key)) == EVP_PKEY_ED25519
286b9d5f
JH
725 ? KEYTYPE_ED25519 : KEYTYPE_RSA;
726#else
727 KEYTYPE_RSA;
728#endif
2592e6c0
JH
729return NULL;
730}
731
732
733
734/* allocate mem for signature (when signing) */
cb78c1a8 735/* hash & sign data. Incremental not supported.
2592e6c0 736
9e70917d 737Return: NULL for success with the signaature in the sig blob, or an error string */
2592e6c0
JH
738
739const uschar *
d73e45df 740exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 741{
d73e45df 742const EVP_MD * md;
286b9d5f 743EVP_MD_CTX * ctx;
d73e45df 744size_t siglen;
9b2583c4 745
d73e45df
JH
746switch (hash)
747 {
cb78c1a8 748 case HASH_NULL: md = NULL; break; /* Ed25519 signing */
d73e45df
JH
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";
753 }
2592e6c0 754
cb78c1a8
JH
755#ifdef SIGN_HAVE_ED25519
756if ( (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
f3ebb786 759 && (sig->data = store_get(siglen, FALSE))
f9ba5e22 760
cb78c1a8 761 /* Obtain the signature (slen could change here!) */
39e02651 762 && EVP_DigestSign(ctx, sig->data, &siglen, data->data, data->len) > 0
cb78c1a8
JH
763 )
764 {
765 EVP_MD_CTX_destroy(ctx);
766 sig->len = siglen;
767 return NULL;
768 }
769#else
770/*XXX renamed to EVP_MD_CTX_new() in 1.1.0 */
771if ( (ctx = EVP_MD_CTX_create())
772 && EVP_DigestSignInit(ctx, NULL, md, NULL, sign_ctx->key) > 0
286b9d5f 773 && EVP_DigestSignUpdate(ctx, data->data, data->len) > 0
286b9d5f 774 && EVP_DigestSignFinal(ctx, NULL, &siglen) > 0
f3ebb786 775 && (sig->data = store_get(siglen, FALSE))
cb78c1a8
JH
776
777 /* Obtain the signature (slen could change here!) */
286b9d5f 778 && EVP_DigestSignFinal(ctx, sig->data, &siglen) > 0
d73e45df 779 )
2592e6c0 780 {
286b9d5f
JH
781 EVP_MD_CTX_destroy(ctx);
782 sig->len = siglen;
783 return NULL;
2592e6c0 784 }
cb78c1a8 785#endif
2592e6c0 786
286b9d5f 787if (ctx) EVP_MD_CTX_destroy(ctx);
7845dbb3 788return US ERR_error_string(ERR_get_error(), NULL);
2592e6c0
JH
789}
790
791
792
286b9d5f 793/* import public key (from blob in memory)
9b2583c4 794Return: NULL for success, or an error string */
2592e6c0
JH
795
796const uschar *
286b9d5f 797exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
2592e6c0 798{
286b9d5f
JH
799const uschar * s = pubkey->data;
800uschar * ret = NULL;
2592e6c0 801
286b9d5f
JH
802switch(fmt)
803 {
804 case KEYFMT_DER:
286b9d5f
JH
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);
808 break;
809#ifdef SIGN_HAVE_ED25519
810 case KEYFMT_ED25519_BARE:
cb78c1a8
JH
811 if (!(verify_ctx->key = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, NULL,
812 s, pubkey->len)))
286b9d5f 813 ret = US ERR_error_string(ERR_get_error(), NULL);
286b9d5f
JH
814 break;
815#endif
816 default:
817 ret = US"pubkey format not handled";
818 break;
819 }
9b2583c4 820
286b9d5f 821return ret;
2592e6c0
JH
822}
823
824
825
826
cb78c1a8 827/* verify signature (of hash, except Ed25519 where of-data)
286b9d5f 828(given pubkey & alleged sig)
2592e6c0
JH
829Return: NULL for success, or an error string */
830
831const uschar *
286b9d5f 832exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 833{
d73e45df 834const EVP_MD * md;
286b9d5f 835
d73e45df 836switch (hash)
2592e6c0 837 {
cb78c1a8 838 case HASH_NULL: md = NULL; break;
d73e45df
JH
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";
2592e6c0 843 }
d73e45df 844
cb78c1a8
JH
845#ifdef SIGN_HAVE_ED25519
846if (!md)
286b9d5f
JH
847 {
848 EVP_MD_CTX * ctx;
d73e45df 849
c8b2f374
JH
850 if ((ctx = EVP_MD_CTX_new()))
851 {
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
854 )
855 { EVP_MD_CTX_free(ctx); return NULL; }
856 EVP_MD_CTX_free(ctx);
857 }
286b9d5f 858 }
cb78c1a8
JH
859else
860#endif
286b9d5f
JH
861 {
862 EVP_PKEY_CTX * ctx;
863
c8b2f374 864 if ((ctx = EVP_PKEY_CTX_new(verify_ctx->key, NULL)))
25fa0868 865 {
c8b2f374
JH
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
25fa0868
JH
871 )
872 { EVP_PKEY_CTX_free(ctx); return NULL; }
25fa0868 873 EVP_PKEY_CTX_free(ctx);
c8b2f374
JH
874
875 DEBUG(D_tls)
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));
25fa0868 879 }
286b9d5f 880 }
c8b2f374
JH
881
882return US ERR_error_string(ERR_get_error(), NULL);
2592e6c0
JH
883}
884
885
d73e45df 886
2592e6c0
JH
887#endif
888/******************************************************************************/
889
890#endif /*DISABLE_DKIM*/
260958d6 891#endif /*MACRO_PREDEF*/
2592e6c0 892/* End of File */