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