OpenSSL: clear any leftover errors from the stack after SSL_accept succeeds
[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
JH
30
31#ifndef SUPPORT_TLS
32# error Need SUPPORT_TLS for DKIM
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
415if ((der.len = b64decode(s1, &der.data)) < 0)
416 return US"Bad PEM-DER b64 decode";
417
418/* untangle asn.1 */
419
420/* sequence; just move past the header */
421if ((rc = as_tag(&der, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
422 != ASN1_SUCCESS) goto asn_err;
423
424/* integer version; move past the header, check is zero */
425if ((rc = as_tag(&der, 0, ASN1_TAG_INTEGER, &alen)) != ASN1_SUCCESS)
426 goto asn_err;
427if (alen != 1 || *der.data != 0)
428 return US"Bad version number";
429der.data++; der.len--;
430
431if ( (s1 = as_mpi(&der, &sign_ctx->n))
432 || (s1 = as_mpi(&der, &sign_ctx->e))
433 || (s1 = as_mpi(&der, &sign_ctx->d))
434 || (s1 = as_mpi(&der, &sign_ctx->p))
435 || (s1 = as_mpi(&der, &sign_ctx->q))
436 || (s1 = as_mpi(&der, &sign_ctx->dp))
437 || (s1 = as_mpi(&der, &sign_ctx->dq))
438 || (s1 = as_mpi(&der, &sign_ctx->qp))
439 )
440 return s1;
441
349d0869 442#ifdef extreme_debug
6e4aaa85 443DEBUG(D_acl) debug_printf_indent("rsa_signing_init:\n");
2592e6c0
JH
444 {
445 uschar * s;
446 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->n);
6e4aaa85 447 debug_printf_indent(" N : %s\n", s);
2592e6c0 448 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->e);
6e4aaa85 449 debug_printf_indent(" E : %s\n", s);
2592e6c0 450 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->d);
6e4aaa85 451 debug_printf_indent(" D : %s\n", s);
2592e6c0 452 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->p);
6e4aaa85 453 debug_printf_indent(" P : %s\n", s);
2592e6c0 454 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->q);
6e4aaa85 455 debug_printf_indent(" Q : %s\n", s);
2592e6c0 456 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dp);
6e4aaa85 457 debug_printf_indent(" DP: %s\n", s);
2592e6c0 458 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->dq);
6e4aaa85 459 debug_printf_indent(" DQ: %s\n", s);
2592e6c0 460 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, sign_ctx->qp);
6e4aaa85 461 debug_printf_indent(" QP: %s\n", s);
2592e6c0 462 }
349d0869 463#endif
286b9d5f
JH
464
465sign_ctx->keytype = KEYTYPE_RSA;
2592e6c0
JH
466return NULL;
467
468asn_err: return US asn1_strerror(rc);
469}
470
471
472
473/* allocate mem for signature (when signing) */
286b9d5f 474/* sign already-hashed data.
2592e6c0
JH
475
476Return: NULL for success, or an error string */
477
478const uschar *
d73e45df 479exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 480{
349d0869 481char * sexp_hash;
2592e6c0
JH
482gcry_sexp_t s_hash = NULL, s_key = NULL, s_sig = NULL;
483gcry_mpi_t m_sig;
484uschar * errstr;
485gcry_error_t gerr;
486
9b2583c4
JH
487/*XXX will need extension for hash types (though, possibly, should
488be re-specced to not rehash but take an already-hashed value? Actually
d73e45df 489current impl looks WRONG - it _is_ given a hash so should not be
9b2583c4
JH
490re-hashing. Has this been tested?
491
492Will need extension for non-RSA sugning algos. */
493
d73e45df
JH
494switch (hash)
495 {
349d0869
JH
496 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
497 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
d73e45df
JH
498 default: return US"nonhandled hash type";
499 }
500
2592e6c0
JH
501#define SIGSPACE 128
502sig->data = store_get(SIGSPACE);
503
504if (gcry_mpi_cmp (sign_ctx->p, sign_ctx->q) > 0)
505 {
506 gcry_mpi_swap (sign_ctx->p, sign_ctx->q);
507 gcry_mpi_invm (sign_ctx->qp, sign_ctx->p, sign_ctx->q);
508 }
509
510if ( (gerr = gcry_sexp_build (&s_key, NULL,
511 "(private-key (rsa (n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
512 sign_ctx->n, sign_ctx->e,
513 sign_ctx->d, sign_ctx->p,
514 sign_ctx->q, sign_ctx->qp))
349d0869 515 || (gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
2592e6c0
JH
516 (int) data->len, CS data->data))
517 || (gerr = gcry_pk_sign (&s_sig, s_hash, s_key))
518 )
519 return US gcry_strerror(gerr);
520
521/* gcry_sexp_dump(s_sig); */
522
523if ( !(s_sig = gcry_sexp_find_token(s_sig, "s", 0))
524 )
525 return US"no sig result";
526
527m_sig = gcry_sexp_nth_mpi(s_sig, 1, GCRYMPI_FMT_USG);
528
349d0869 529#ifdef extreme_debug
2592e6c0
JH
530DEBUG(D_acl)
531 {
532 uschar * s;
533 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, m_sig);
6e4aaa85 534 debug_printf_indent(" SG: %s\n", s);
2592e6c0 535 }
349d0869 536#endif
2592e6c0
JH
537
538gerr = gcry_mpi_print(GCRYMPI_FMT_USG, sig->data, SIGSPACE, &sig->len, m_sig);
539if (gerr)
540 {
6e4aaa85 541 debug_printf_indent("signature conversion from MPI to buffer failed\n");
2592e6c0
JH
542 return US gcry_strerror(gerr);
543 }
544#undef SIGSPACE
545
546return NULL;
547}
548
549
286b9d5f 550/* import public key (from blob in memory)
2592e6c0
JH
551Return: NULL for success, or an error string */
552
553const uschar *
286b9d5f 554exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
2592e6c0
JH
555{
556/*
557in code sequence per b81207d2bfa92 rsa_parse_public_key() and asn1_get_mpi()
558*/
559uschar tag_class;
560int taglen;
561long alen;
562int rc;
563uschar * errstr;
564gcry_error_t gerr;
565uschar * stage = US"S1";
566
286b9d5f
JH
567if (fmt != KEYFMT_DER) return US"pubkey format not handled";
568
2592e6c0
JH
569/*
570sequence
571 sequence
572 OBJECT:rsaEncryption
573 NULL
574 BIT STRING:RSAPublicKey
575 sequence
576 INTEGER:Public modulus
577 INTEGER:Public exponent
578
579openssl rsa -in aux-fixed/dkim/dkim.private -pubout -outform DER | od -t x1 | head;
580openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump;
581openssl rsa -in aux-fixed/dkim/dkim.private -pubout | openssl asn1parse -dump -offset 22;
582*/
583
584/* sequence; just move past the header */
286b9d5f 585if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
2592e6c0
JH
586 != ASN1_SUCCESS) goto asn_err;
587
588/* sequence; skip the entire thing */
589DEBUG(D_acl) stage = US"S2";
286b9d5f 590if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, &alen))
2592e6c0 591 != ASN1_SUCCESS) goto asn_err;
286b9d5f 592pubkey->data += alen; pubkey->len -= alen;
2592e6c0
JH
593
594
595/* bitstring: limit range to size of bitstring;
596move over header + content wrapper */
597DEBUG(D_acl) stage = US"BS";
286b9d5f 598if ((rc = as_tag(pubkey, 0, ASN1_TAG_BIT_STRING, &alen)) != ASN1_SUCCESS)
2592e6c0 599 goto asn_err;
286b9d5f
JH
600pubkey->len = alen;
601pubkey->data++; pubkey->len--;
2592e6c0
JH
602
603/* sequence; just move past the header */
604DEBUG(D_acl) stage = US"S3";
286b9d5f 605if ((rc = as_tag(pubkey, ASN1_CLASS_STRUCTURED, ASN1_TAG_SEQUENCE, NULL))
2592e6c0
JH
606 != ASN1_SUCCESS) goto asn_err;
607
608/* read two integers */
609DEBUG(D_acl) stage = US"MPI";
286b9d5f
JH
610if ( (errstr = as_mpi(pubkey, &verify_ctx->n))
611 || (errstr = as_mpi(pubkey, &verify_ctx->e))
2592e6c0
JH
612 )
613 return errstr;
614
349d0869 615#ifdef extreme_debug
6e4aaa85 616DEBUG(D_acl) debug_printf_indent("rsa_verify_init:\n");
2592e6c0
JH
617 {
618 uschar * s;
619 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->n);
6e4aaa85 620 debug_printf_indent(" N : %s\n", s);
2592e6c0 621 gcry_mpi_aprint (GCRYMPI_FMT_HEX, &s, NULL, verify_ctx->e);
6e4aaa85 622 debug_printf_indent(" E : %s\n", s);
2592e6c0
JH
623 }
624
349d0869 625#endif
2592e6c0
JH
626return NULL;
627
628asn_err:
629DEBUG(D_acl) return string_sprintf("%s: %s", stage, asn1_strerror(rc));
630 return US asn1_strerror(rc);
631}
632
633
286b9d5f
JH
634/* verify signature (of hash)
635XXX though we appear to be doing a hash, too!
636(given pubkey & alleged sig)
2592e6c0
JH
637Return: NULL for success, or an error string */
638
639const uschar *
d73e45df 640exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data_hash, blob * sig)
2592e6c0
JH
641{
642/*
643cf. libgnutls 2.8.5 _wrap_gcry_pk_verify()
644*/
349d0869 645char * sexp_hash;
2592e6c0
JH
646gcry_mpi_t m_sig;
647gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
648gcry_error_t gerr;
649uschar * stage;
650
349d0869 651/*XXX needs extension for SHA512 */
d73e45df
JH
652switch (hash)
653 {
349d0869
JH
654 case HASH_SHA1: sexp_hash = "(data(flags pkcs1)(hash sha1 %b))"; break;
655 case HASH_SHA2_256: sexp_hash = "(data(flags pkcs1)(hash sha256 %b))"; break;
656 default: return US"nonhandled hash type";
d73e45df
JH
657 }
658
2592e6c0
JH
659if ( (stage = US"pkey sexp build",
660 gerr = gcry_sexp_build (&s_pkey, NULL, "(public-key(rsa(n%m)(e%m)))",
661 verify_ctx->n, verify_ctx->e))
662 || (stage = US"data sexp build",
349d0869 663 gerr = gcry_sexp_build (&s_hash, NULL, sexp_hash,
2592e6c0
JH
664 (int) data_hash->len, CS data_hash->data))
665 || (stage = US"sig mpi scan",
666 gerr = gcry_mpi_scan(&m_sig, GCRYMPI_FMT_USG, sig->data, sig->len, NULL))
667 || (stage = US"sig sexp build",
668 gerr = gcry_sexp_build (&s_sig, NULL, "(sig-val(rsa(s%m)))", m_sig))
669 || (stage = US"verify",
670 gerr = gcry_pk_verify (s_sig, s_hash, s_pkey))
671 )
672 {
6e4aaa85 673 DEBUG(D_acl) debug_printf_indent("verify: error in stage '%s'\n", stage);
2592e6c0
JH
674 return US gcry_strerror(gerr);
675 }
676
677if (s_sig) gcry_sexp_release (s_sig);
678if (s_hash) gcry_sexp_release (s_hash);
679if (s_pkey) gcry_sexp_release (s_pkey);
680gcry_mpi_release (m_sig);
681gcry_mpi_release (verify_ctx->n);
682gcry_mpi_release (verify_ctx->e);
683
684return NULL;
685}
686
687
688
689
d73e45df 690#elif defined(SIGN_OPENSSL)
2592e6c0
JH
691/******************************************************************************/
692
693void
9b2583c4 694exim_dkim_init(void)
2592e6c0 695{
9e70917d 696ERR_load_crypto_strings();
2592e6c0
JH
697}
698
699
617d3932 700/* accumulate data (was gnutls-only but now needed for OpenSSL non-EC too
286b9d5f 701because now using hash-and-sign interface) */
acec9514
JH
702gstring *
703exim_dkim_data_append(gstring * g, uschar * s)
2592e6c0 704{
286b9d5f 705return string_cat(g, s);
2592e6c0
JH
706}
707
708
709/* import private key from PEM string in memory.
710Return: NULL for success, or an error string */
711
712const uschar *
617d3932 713exim_dkim_signing_init(const uschar * privkey_pem, es_ctx * sign_ctx)
2592e6c0 714{
d73e45df 715BIO * bp = BIO_new_mem_buf(privkey_pem, -1);
2592e6c0 716
d73e45df 717if (!(sign_ctx->key = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL)))
c59b09dc
JH
718 return string_sprintf("privkey PEM-block import: %s",
719 ERR_error_string(ERR_get_error(), NULL));
286b9d5f
JH
720
721sign_ctx->keytype =
722#ifdef SIGN_HAVE_ED25519
cb78c1a8 723 EVP_PKEY_type(EVP_PKEY_id(sign_ctx->key)) == EVP_PKEY_ED25519
286b9d5f
JH
724 ? KEYTYPE_ED25519 : KEYTYPE_RSA;
725#else
726 KEYTYPE_RSA;
727#endif
2592e6c0
JH
728return NULL;
729}
730
731
732
733/* allocate mem for signature (when signing) */
cb78c1a8 734/* hash & sign data. Incremental not supported.
2592e6c0 735
9e70917d 736Return: NULL for success with the signaature in the sig blob, or an error string */
2592e6c0
JH
737
738const uschar *
d73e45df 739exim_dkim_sign(es_ctx * sign_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 740{
d73e45df 741const EVP_MD * md;
286b9d5f 742EVP_MD_CTX * ctx;
d73e45df 743size_t siglen;
9b2583c4 744
d73e45df
JH
745switch (hash)
746 {
cb78c1a8 747 case HASH_NULL: md = NULL; break; /* Ed25519 signing */
d73e45df
JH
748 case HASH_SHA1: md = EVP_sha1(); break;
749 case HASH_SHA2_256: md = EVP_sha256(); break;
750 case HASH_SHA2_512: md = EVP_sha512(); break;
751 default: return US"nonhandled hash type";
752 }
2592e6c0 753
cb78c1a8
JH
754#ifdef SIGN_HAVE_ED25519
755if ( (ctx = EVP_MD_CTX_new())
756 && EVP_DigestSignInit(ctx, NULL, md, NULL, sign_ctx->key) > 0
757 && EVP_DigestSign(ctx, NULL, &siglen, NULL, 0) > 0
758 && (sig->data = store_get(siglen))
f9ba5e22 759
cb78c1a8 760 /* Obtain the signature (slen could change here!) */
39e02651 761 && EVP_DigestSign(ctx, sig->data, &siglen, data->data, data->len) > 0
cb78c1a8
JH
762 )
763 {
764 EVP_MD_CTX_destroy(ctx);
765 sig->len = siglen;
766 return NULL;
767 }
768#else
769/*XXX renamed to EVP_MD_CTX_new() in 1.1.0 */
770if ( (ctx = EVP_MD_CTX_create())
771 && EVP_DigestSignInit(ctx, NULL, md, NULL, sign_ctx->key) > 0
286b9d5f 772 && EVP_DigestSignUpdate(ctx, data->data, data->len) > 0
286b9d5f 773 && EVP_DigestSignFinal(ctx, NULL, &siglen) > 0
286b9d5f 774 && (sig->data = store_get(siglen))
cb78c1a8
JH
775
776 /* Obtain the signature (slen could change here!) */
286b9d5f 777 && EVP_DigestSignFinal(ctx, sig->data, &siglen) > 0
d73e45df 778 )
2592e6c0 779 {
286b9d5f
JH
780 EVP_MD_CTX_destroy(ctx);
781 sig->len = siglen;
782 return NULL;
2592e6c0 783 }
cb78c1a8 784#endif
2592e6c0 785
286b9d5f 786if (ctx) EVP_MD_CTX_destroy(ctx);
7845dbb3 787return US ERR_error_string(ERR_get_error(), NULL);
2592e6c0
JH
788}
789
790
791
286b9d5f 792/* import public key (from blob in memory)
9b2583c4 793Return: NULL for success, or an error string */
2592e6c0
JH
794
795const uschar *
286b9d5f 796exim_dkim_verify_init(blob * pubkey, keyformat fmt, ev_ctx * verify_ctx)
2592e6c0 797{
286b9d5f
JH
798const uschar * s = pubkey->data;
799uschar * ret = NULL;
2592e6c0 800
286b9d5f
JH
801switch(fmt)
802 {
803 case KEYFMT_DER:
286b9d5f
JH
804 /*XXX hmm, we never free this */
805 if (!(verify_ctx->key = d2i_PUBKEY(NULL, &s, pubkey->len)))
806 ret = US ERR_error_string(ERR_get_error(), NULL);
807 break;
808#ifdef SIGN_HAVE_ED25519
809 case KEYFMT_ED25519_BARE:
cb78c1a8
JH
810 if (!(verify_ctx->key = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, NULL,
811 s, pubkey->len)))
286b9d5f 812 ret = US ERR_error_string(ERR_get_error(), NULL);
286b9d5f
JH
813 break;
814#endif
815 default:
816 ret = US"pubkey format not handled";
817 break;
818 }
9b2583c4 819
286b9d5f 820return ret;
2592e6c0
JH
821}
822
823
824
825
cb78c1a8 826/* verify signature (of hash, except Ed25519 where of-data)
286b9d5f 827(given pubkey & alleged sig)
2592e6c0
JH
828Return: NULL for success, or an error string */
829
830const uschar *
286b9d5f 831exim_dkim_verify(ev_ctx * verify_ctx, hashmethod hash, blob * data, blob * sig)
2592e6c0 832{
d73e45df 833const EVP_MD * md;
25fa0868 834const uschar * where;
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
cb78c1a8 850 if ( (ctx = EVP_MD_CTX_new())
286b9d5f 851 && EVP_DigestVerifyInit(ctx, NULL, md, NULL, verify_ctx->key) > 0
cb78c1a8 852 && EVP_DigestVerify(ctx, sig->data, sig->len, data->data, data->len) > 0
286b9d5f 853 )
cb78c1a8 854 { EVP_MD_CTX_free(ctx); return NULL; }
286b9d5f
JH
855
856 if (ctx) EVP_MD_CTX_free(ctx);
286b9d5f 857 }
cb78c1a8
JH
858else
859#endif
286b9d5f
JH
860 {
861 EVP_PKEY_CTX * ctx;
862
25fa0868
JH
863 if ((where = US"EVP_PKEY_CTX_new",
864 (ctx = EVP_PKEY_CTX_new(verify_ctx->key, NULL))))
865 {
866 if ( (where = US"EVP_PKEY_verify_init",
867 EVP_PKEY_verify_init(ctx) > 0)
868 && (where = US"EVP_PKEY_CTX_set_rsa_padding",
869 EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) > 0)
870 && (where = US"EVP_PKEY_CTX_set_signature_md",
871 EVP_PKEY_CTX_set_signature_md(ctx, md) > 0)
872 && (where = US"EVP_PKEY_verify",
873 EVP_PKEY_verify(ctx, sig->data, sig->len,
874 data->data, data->len) == 1)
875 )
876 { EVP_PKEY_CTX_free(ctx); return NULL; }
877
878 EVP_PKEY_CTX_free(ctx);
879 }
286b9d5f 880 }
25fa0868 881return string_sprintf("%s: %s", where, ERR_error_string(ERR_get_error(), NULL));
2592e6c0
JH
882}
883
884
d73e45df 885
2592e6c0
JH
886#endif
887/******************************************************************************/
888
889#endif /*DISABLE_DKIM*/
260958d6 890#endif /*MACRO_PREDEF*/
2592e6c0 891/* End of File */