2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (C) 2009 - 2016 Tom Kistner <tom@duncanthrax.net>
5 * Copyright (C) 2016 - 2020 Jeremy Harris <jgh@exim.org>
7 * http://duncanthrax.net/pdkim/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #ifndef DISABLE_DKIM /* entire file */
30 # error Must not DISABLE_TLS, for DKIM
33 #include "crypt_ver.h"
36 # include <openssl/rsa.h>
37 # include <openssl/ssl.h>
38 # include <openssl/err.h>
39 #elif defined(SIGN_GNUTLS)
40 # include <gnutls/gnutls.h>
41 # include <gnutls/x509.h>
47 #define PDKIM_SIGNATURE_VERSION "1"
48 #define PDKIM_PUB_RECORD_VERSION US "DKIM1"
50 #define PDKIM_MAX_HEADER_LEN 65536
51 #define PDKIM_MAX_HEADERS 512
52 #define PDKIM_MAX_BODY_LINE_LEN 16384
53 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
55 /* -------------------------------------------------------------------------- */
56 struct pdkim_stringlist {
62 /* -------------------------------------------------------------------------- */
63 /* A bunch of list constants */
64 const uschar * pdkim_querymethods[] = {
68 const uschar * pdkim_canons[] = {
74 const pdkim_hashtype pdkim_hashes[] = {
75 { US"sha1", HASH_SHA1 },
76 { US"sha256", HASH_SHA2_256 },
77 { US"sha512", HASH_SHA2_512 }
80 const uschar * pdkim_keytypes[] = {
81 [KEYTYPE_RSA] = US"rsa",
82 #ifdef SIGN_HAVE_ED25519
83 [KEYTYPE_ED25519] = US"ed25519", /* Works for 3.6.0 GnuTLS, OpenSSL 1.1.1 */
86 #ifdef notyet_EC_dkim_extensions /* https://tools.ietf.org/html/draft-srose-dkim-ecc-00 */
93 typedef struct pdkim_combined_canon_entry {
97 } pdkim_combined_canon_entry;
99 pdkim_combined_canon_entry pdkim_combined_canons[] = {
100 { US"simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
101 { US"simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
102 { US"relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
103 { US"relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
104 { US"simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
105 { US"relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
110 static blob lineending = {.data = US"\r\n", .len = 2};
112 /* -------------------------------------------------------------------------- */
114 dkim_sig_to_a_tag(const pdkim_signature * sig)
116 if ( sig->keytype < 0 || sig->keytype > nelem(pdkim_keytypes)
117 || sig->hashtype < 0 || sig->hashtype > nelem(pdkim_hashes))
119 return string_sprintf("%s-%s",
120 pdkim_keytypes[sig->keytype], pdkim_hashes[sig->hashtype].dkim_hashname);
125 pdkim_keyname_to_keytype(const uschar * s)
127 for (int i = 0; i < nelem(pdkim_keytypes); i++)
128 if (Ustrcmp(s, pdkim_keytypes[i]) == 0) return i;
133 pdkim_hashname_to_hashtype(const uschar * s, unsigned len)
135 if (!len) len = Ustrlen(s);
136 for (int i = 0; i < nelem(pdkim_hashes); i++)
137 if (Ustrncmp(s, pdkim_hashes[i].dkim_hashname, len) == 0)
143 pdkim_cstring_to_canons(const uschar * s, unsigned len,
144 int * canon_head, int * canon_body)
146 if (!len) len = Ustrlen(s);
147 for (int i = 0; pdkim_combined_canons[i].str; i++)
148 if ( Ustrncmp(s, pdkim_combined_canons[i].str, len) == 0
149 && len == Ustrlen(pdkim_combined_canons[i].str))
151 *canon_head = pdkim_combined_canons[i].canon_headers;
152 *canon_body = pdkim_combined_canons[i].canon_body;
160 pdkim_verify_status_str(int status)
164 case PDKIM_VERIFY_NONE: return "PDKIM_VERIFY_NONE";
165 case PDKIM_VERIFY_INVALID: return "PDKIM_VERIFY_INVALID";
166 case PDKIM_VERIFY_FAIL: return "PDKIM_VERIFY_FAIL";
167 case PDKIM_VERIFY_PASS: return "PDKIM_VERIFY_PASS";
168 default: return "PDKIM_VERIFY_UNKNOWN";
173 pdkim_verify_ext_status_str(int ext_status)
177 case PDKIM_VERIFY_FAIL_BODY: return "PDKIM_VERIFY_FAIL_BODY";
178 case PDKIM_VERIFY_FAIL_MESSAGE: return "PDKIM_VERIFY_FAIL_MESSAGE";
179 case PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH: return "PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH";
180 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
181 case PDKIM_VERIFY_INVALID_BUFFER_SIZE: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
182 case PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD: return "PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD";
183 case PDKIM_VERIFY_INVALID_PUBKEY_IMPORT: return "PDKIM_VERIFY_INVALID_PUBKEY_IMPORT";
184 case PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE: return "PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE";
185 case PDKIM_VERIFY_INVALID_SIGNATURE_ERROR: return "PDKIM_VERIFY_INVALID_SIGNATURE_ERROR";
186 case PDKIM_VERIFY_INVALID_DKIM_VERSION: return "PDKIM_VERIFY_INVALID_DKIM_VERSION";
187 default: return "PDKIM_VERIFY_UNKNOWN";
192 pdkim_errstr(int status)
196 case PDKIM_OK: return US"OK";
197 case PDKIM_FAIL: return US"FAIL";
198 case PDKIM_ERR_RSA_PRIVKEY: return US"PRIVKEY";
199 case PDKIM_ERR_RSA_SIGNING: return US"SIGNING";
200 case PDKIM_ERR_LONG_LINE: return US"LONG_LINE";
201 case PDKIM_ERR_BUFFER_TOO_SMALL: return US"BUFFER_TOO_SMALL";
202 case PDKIM_ERR_EXCESS_SIGS: return US"EXCESS_SIGS";
203 case PDKIM_SIGN_PRIVKEY_WRAP: return US"PRIVKEY_WRAP";
204 case PDKIM_SIGN_PRIVKEY_B64D: return US"PRIVKEY_B64D";
205 default: return US"(unknown)";
210 /* -------------------------------------------------------------------------- */
211 /* Print debugging functions */
213 pdkim_quoteprint(const uschar *data, int len)
215 for (int i = 0; i < len; i++)
217 const int c = data[i];
220 case ' ' : debug_printf("{SP}"); break;
221 case '\t': debug_printf("{TB}"); break;
222 case '\r': debug_printf("{CR}"); break;
223 case '\n': debug_printf("{LF}"); break;
224 case '{' : debug_printf("{BO}"); break;
225 case '}' : debug_printf("{BC}"); break;
227 if ( (c < 32) || (c > 127) )
228 debug_printf("{%02x}", c);
230 debug_printf("%c", c);
238 pdkim_hexprint(const uschar *data, int len)
240 if (data) for (int i = 0 ; i < len; i++) debug_printf("%02x", data[i]);
241 else debug_printf("<NULL>");
247 static pdkim_stringlist *
248 pdkim_prepend_stringlist(pdkim_stringlist * base, const uschar * str)
250 pdkim_stringlist * new_entry = store_get(sizeof(pdkim_stringlist), FALSE);
252 memset(new_entry, 0, sizeof(pdkim_stringlist));
253 new_entry->value = string_copy(str);
254 if (base) new_entry->next = base;
260 /* Trim whitespace fore & aft */
263 pdkim_strtrim(gstring * str)
268 while (*p == '\t' || *p == ' ') /* dump the leading whitespace */
269 { str->size--; str->ptr--; str->s++; }
272 && ((q = str->s + str->ptr - 1), (*q == '\t' || *q == ' '))
274 str->ptr--; /* dump trailing whitespace */
276 (void) string_from_gstring(str);
281 /* -------------------------------------------------------------------------- */
284 pdkim_free_ctx(pdkim_ctx *ctx)
289 /* -------------------------------------------------------------------------- */
290 /* Matches the name of the passed raw "header" against
291 the passed colon-separated "tick", and invalidates
292 the entry in tick. Entries can be prefixed for multi- or over-signing,
293 in which case do not invalidate.
295 Returns OK for a match, or fail-code
299 header_name_match(const uschar * header, uschar * tick)
301 const uschar * ticklist = tick;
304 uschar * hname, * p, * ele;
305 uschar * hcolon = Ustrchr(header, ':'); /* Get header name */
308 return PDKIM_FAIL; /* This isn't a header */
310 /* if we had strncmpic() we wouldn't need this copy */
311 hname = string_copyn(header, hcolon-header);
313 while (p = US ticklist, ele = string_nextinlist(&ticklist, &sep, NULL, 0))
317 case '=': case '+': multisign = TRUE; ele++; break;
318 default: multisign = FALSE; break;
321 if (strcmpic(ele, hname) == 0)
324 *p = '_'; /* Invalidate this header name instance in tick-off list */
332 /* -------------------------------------------------------------------------- */
333 /* Performs "relaxed" canonicalization of a header. */
336 pdkim_relax_header_n(const uschar * header, int len, BOOL append_crlf)
338 BOOL past_field_name = FALSE;
339 BOOL seen_wsp = FALSE;
340 uschar * relaxed = store_get(len+3, TRUE); /* tainted */
341 uschar * q = relaxed;
343 for (const uschar * p = header; p - header < len; p++)
347 if (c == '\r' || c == '\n') /* Ignore CR & LF */
349 if (c == '\t' || c == ' ')
353 c = ' '; /* Turns WSP into SP */
357 if (!past_field_name && c == ':')
359 if (seen_wsp) q--; /* This removes WSP immediately before the colon */
360 seen_wsp = TRUE; /* This removes WSP immediately after the colon */
361 past_field_name = TRUE;
366 /* Lowercase header name */
367 if (!past_field_name) c = tolower(c);
371 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
373 if (append_crlf) { *q++ = '\r'; *q++ = '\n'; }
380 pdkim_relax_header(const uschar * header, BOOL append_crlf)
382 return pdkim_relax_header_n(header, Ustrlen(header), append_crlf);
386 /* -------------------------------------------------------------------------- */
387 #define PDKIM_QP_ERROR_DECODE -1
389 static const uschar *
390 pdkim_decode_qp_char(const uschar *qp_p, int *c)
392 const uschar *initial_pos = qp_p;
394 /* Advance one char */
397 /* Check for two hex digits and decode them */
398 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
400 /* Do hex conversion */
401 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
402 *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
406 /* Illegal char here */
407 *c = PDKIM_QP_ERROR_DECODE;
412 /* -------------------------------------------------------------------------- */
415 pdkim_decode_qp(const uschar * str)
419 const uschar * p = str;
420 uschar * n = store_get(Ustrlen(str)+1, TRUE);
428 p = pdkim_decode_qp_char(p, &nchar);
444 /* -------------------------------------------------------------------------- */
447 pdkim_decode_base64(const uschar * str, blob * b)
449 int dlen = b64decode(str, &b->data);
450 if (dlen < 0) b->data = NULL;
455 pdkim_encode_base64(blob * b)
457 return b64encode(CUS b->data, b->len);
461 /* -------------------------------------------------------------------------- */
462 #define PDKIM_HDR_LIMBO 0
463 #define PDKIM_HDR_TAG 1
464 #define PDKIM_HDR_VALUE 2
466 static pdkim_signature *
467 pdkim_parse_sig_header(pdkim_ctx * ctx, uschar * raw_hdr)
469 pdkim_signature * sig;
471 gstring * cur_tag = NULL;
472 gstring * cur_val = NULL;
473 BOOL past_hname = FALSE;
474 BOOL in_b_val = FALSE;
475 int where = PDKIM_HDR_LIMBO;
477 sig = store_get(sizeof(pdkim_signature), FALSE);
478 memset(sig, 0, sizeof(pdkim_signature));
479 sig->bodylength = -1;
481 /* Set so invalid/missing data error display is accurate */
486 q = sig->rawsig_no_b_val = store_get(Ustrlen(raw_hdr)+1, TRUE); /* tainted */
488 for (uschar * p = raw_hdr; ; p++)
493 if (c == '\r' || c == '\n')
496 /* Fast-forward through header name */
499 if (c == ':') past_hname = TRUE;
503 if (where == PDKIM_HDR_LIMBO)
505 /* In limbo, just wait for a tag-char to appear */
506 if (!(c >= 'a' && c <= 'z'))
509 where = PDKIM_HDR_TAG;
512 if (where == PDKIM_HDR_TAG)
514 if (c >= 'a' && c <= 'z')
515 cur_tag = string_catn(cur_tag, p, 1);
519 if (Ustrcmp(string_from_gstring(cur_tag), "b") == 0)
524 where = PDKIM_HDR_VALUE;
529 if (where == PDKIM_HDR_VALUE)
531 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
534 if (c == ';' || c == '\0')
536 /* We must have both tag and value, and tags must be one char except
537 for the possibility of "bh". */
539 if ( cur_tag && cur_val
540 && (cur_tag->ptr == 1 || *cur_tag->s == 'b')
543 (void) string_from_gstring(cur_val);
544 pdkim_strtrim(cur_val);
546 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->s, cur_val->s);
550 case 'b': /* sig-data or body-hash */
551 switch (cur_tag->s[1])
553 case '\0': pdkim_decode_base64(cur_val->s, &sig->sighash); break;
554 case 'h': if (cur_tag->ptr == 2)
555 pdkim_decode_base64(cur_val->s, &sig->bodyhash);
560 case 'v': /* version */
561 /* We only support version 1, and that is currently the
562 only version there is. */
564 Ustrcmp(cur_val->s, PDKIM_SIGNATURE_VERSION) == 0 ? 1 : -1;
566 case 'a': /* algorithm */
568 const uschar * list = cur_val->s;
572 if ((elem = string_nextinlist(&list, &sep, NULL, 0)))
573 sig->keytype = pdkim_keyname_to_keytype(elem);
574 if ((elem = string_nextinlist(&list, &sep, NULL, 0)))
575 for (int i = 0; i < nelem(pdkim_hashes); i++)
576 if (Ustrcmp(elem, pdkim_hashes[i].dkim_hashname) == 0)
577 { sig->hashtype = i; break; }
580 case 'c': /* canonicalization */
581 pdkim_cstring_to_canons(cur_val->s, 0,
582 &sig->canon_headers, &sig->canon_body);
584 case 'q': /* Query method (for pubkey)*/
585 for (int i = 0; pdkim_querymethods[i]; i++)
586 if (Ustrcmp(cur_val->s, pdkim_querymethods[i]) == 0)
588 sig->querymethod = i; /* we never actually use this */
592 case 's': /* Selector */
593 sig->selector = string_copyn(cur_val->s, cur_val->ptr); break;
595 sig->domain = string_copyn(cur_val->s, cur_val->ptr); break;
597 sig->identity = pdkim_decode_qp(cur_val->s); break;
598 case 't': /* Timestamp */
599 sig->created = strtoul(CS cur_val->s, NULL, 10); break;
600 case 'x': /* Expiration */
601 sig->expires = strtoul(CS cur_val->s, NULL, 10); break;
602 case 'l': /* Body length count */
603 sig->bodylength = strtol(CS cur_val->s, NULL, 10); break;
604 case 'h': /* signed header fields */
605 sig->headernames = string_copyn(cur_val->s, cur_val->ptr); break;
606 case 'z': /* Copied headfields */
607 sig->copiedheaders = pdkim_decode_qp(cur_val->s); break;
608 /*XXX draft-ietf-dcrup-dkim-crypto-05 would need 'p' tag support
609 for rsafp signatures. But later discussion is dropping those. */
611 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
615 cur_tag = cur_val = NULL;
617 where = PDKIM_HDR_LIMBO;
620 cur_val = string_catn(cur_val, p, 1);
631 if (sig->keytype < 0 || sig->hashtype < 0) /* Cannot verify this signature */
635 /* Chomp raw header. The final newline must not be added to the signature. */
636 while (--q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
642 "DKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
643 pdkim_quoteprint(US sig->rawsig_no_b_val, Ustrlen(sig->rawsig_no_b_val));
645 "DKIM >> Sig size: %4u bits\n", (unsigned) sig->sighash.len*8);
647 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
650 if (!pdkim_set_sig_bodyhash(ctx, sig))
657 /* -------------------------------------------------------------------------- */
660 pdkim_parse_pubkey_record(const uschar *raw_record)
666 pub = store_get(sizeof(pdkim_pubkey), TRUE); /* tainted */
667 memset(pub, 0, sizeof(pdkim_pubkey));
669 while ((ele = string_nextinlist(&raw_record, &sep, NULL, 0)))
673 if ((val = Ustrchr(ele, '=')))
675 int taglen = val++ - ele;
677 DEBUG(D_acl) debug_printf(" %.*s=%s\n", taglen, ele, val);
680 case 'v': pub->version = val; break;
681 case 'h': pub->hashes = val; break;
682 case 'k': pub->keytype = val; break;
683 case 'g': pub->granularity = val; break;
684 case 'n': pub->notes = pdkim_decode_qp(val); break;
685 case 'p': pdkim_decode_base64(val, &pub->key); break;
686 case 's': pub->srvtype = val; break;
687 case 't': if (Ustrchr(val, 'y')) pub->testing = 1;
688 if (Ustrchr(val, 's')) pub->no_subdomaining = 1;
690 default: DEBUG(D_acl) debug_printf(" Unknown tag encountered\n"); break;
695 /* Set fallback defaults */
697 pub->version = string_copy(PDKIM_PUB_RECORD_VERSION);
698 else if (Ustrcmp(pub->version, PDKIM_PUB_RECORD_VERSION) != 0)
700 DEBUG(D_acl) debug_printf(" Bad v= field\n");
704 if (!pub->granularity) pub->granularity = US"*";
705 if (!pub->keytype ) pub->keytype = US"rsa";
706 if (!pub->srvtype ) pub->srvtype = US"*";
712 DEBUG(D_acl) debug_printf(" Missing p= field\n");
717 /* -------------------------------------------------------------------------- */
719 /* Update one bodyhash with some additional data.
720 If we have to relax the data for this sig, return our copy of it. */
723 pdkim_update_ctx_bodyhash(pdkim_bodyhash * b, blob * orig_data, blob * relaxed_data)
725 blob * canon_data = orig_data;
726 /* Defaults to simple canon (no further treatment necessary) */
728 if (b->canon_method == PDKIM_CANON_RELAXED)
730 /* Relax the line if not done already */
733 BOOL seen_wsp = FALSE;
736 /* We want to be able to free this else we allocate
737 for the entire message which could be many MB. Since
738 we don't know what allocations the SHA routines might
739 do, not safe to use store_get()/store_reset(). */
741 relaxed_data = store_malloc(sizeof(blob) + orig_data->len+1);
742 relaxed_data->data = US (relaxed_data+1);
744 for (const uschar * p = orig_data->data, * r = p + orig_data->len; p < r; p++)
749 if (q > 0 && relaxed_data->data[q-1] == ' ')
752 else if (c == '\t' || c == ' ')
754 c = ' '; /* Turns WSP into SP */
761 relaxed_data->data[q++] = c;
763 relaxed_data->data[q] = '\0';
764 relaxed_data->len = q;
766 canon_data = relaxed_data;
769 /* Make sure we don't exceed the to-be-signed body length */
770 if ( b->bodylength >= 0
771 && b->signed_body_bytes + (unsigned long)canon_data->len > b->bodylength
773 canon_data->len = b->bodylength - b->signed_body_bytes;
775 if (canon_data->len > 0)
777 exim_sha_update(&b->body_hash_ctx, CUS canon_data->data, canon_data->len);
778 b->signed_body_bytes += canon_data->len;
779 DEBUG(D_acl) pdkim_quoteprint(canon_data->data, canon_data->len);
786 /* -------------------------------------------------------------------------- */
789 pdkim_finish_bodyhash(pdkim_ctx * ctx)
791 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next) /* Finish hashes */
793 DEBUG(D_acl) debug_printf("DKIM: finish bodyhash %d/%d/%ld len %ld\n",
794 b->hashtype, b->canon_method, b->bodylength, b->signed_body_bytes);
795 exim_sha_finish(&b->body_hash_ctx, &b->bh);
798 /* Traverse all signatures */
799 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next)
801 pdkim_bodyhash * b = sig->calc_body_hash;
805 debug_printf("DKIM [%s] Body bytes (%s) hashed: %lu\n"
806 "DKIM [%s] Body %s computed: ",
807 sig->domain, pdkim_canons[b->canon_method], b->signed_body_bytes,
808 sig->domain, pdkim_hashes[b->hashtype].dkim_hashname);
809 pdkim_hexprint(CUS b->bh.data, b->bh.len);
812 /* SIGNING -------------------------------------------------------------- */
813 if (ctx->flags & PDKIM_MODE_SIGN)
815 /* If bodylength limit is set, and we have received less bytes
816 than the requested amount, effectively remove the limit tag. */
817 if (b->signed_body_bytes < sig->bodylength)
818 sig->bodylength = -1;
822 /* VERIFICATION --------------------------------------------------------- */
823 /* Be careful that the header sig included a bodyash */
825 if ( sig->bodyhash.data
826 && memcmp(b->bh.data, sig->bodyhash.data, b->bh.len) == 0)
828 DEBUG(D_acl) debug_printf("DKIM [%s] Body hash compared OK\n", sig->domain);
834 debug_printf("DKIM [%s] Body hash signature from headers: ", sig->domain);
835 pdkim_hexprint(sig->bodyhash.data, sig->bodyhash.len);
836 debug_printf("DKIM [%s] Body hash did NOT verify\n", sig->domain);
838 sig->verify_status = PDKIM_VERIFY_FAIL;
839 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
847 pdkim_body_complete(pdkim_ctx * ctx)
849 /* In simple body mode, if any empty lines were buffered,
850 replace with one. rfc 4871 3.4.3 */
851 /*XXX checking the signed-body-bytes is a gross hack; I think
852 it indicates that all linebreaks should be buffered, including
853 the one terminating a text line */
855 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
856 if ( b->canon_method == PDKIM_CANON_SIMPLE
857 && b->signed_body_bytes == 0
858 && b->num_buffered_blanklines > 0
860 (void) pdkim_update_ctx_bodyhash(b, &lineending, NULL);
862 ctx->flags |= PDKIM_SEEN_EOD;
863 ctx->linebuf_offset = 0;
868 /* -------------------------------------------------------------------------- */
869 /* Call from pdkim_feed below for processing complete body lines */
870 /* NOTE: the line is not NUL-terminated; but we have a count */
873 pdkim_bodyline_complete(pdkim_ctx * ctx)
875 blob line = {.data = ctx->linebuf, .len = ctx->linebuf_offset};
879 /* Ignore extra data if we've seen the end-of-data marker */
880 if (ctx->flags & PDKIM_SEEN_EOD) goto all_skip;
882 /* We've always got one extra byte to stuff a zero ... */
883 ctx->linebuf[line.len] = '\0';
885 /* Terminate on EOD marker */
886 if (ctx->flags & PDKIM_DOT_TERM)
888 if (memcmp(line.data, ".\r\n", 3) == 0)
889 { pdkim_body_complete(ctx); return; }
892 if (memcmp(line.data, "..", 2) == 0)
893 { line.data++; line.len--; }
896 /* Empty lines need to be buffered until we find a non-empty line */
897 if (memcmp(line.data, "\r\n", 2) == 0)
899 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
900 b->num_buffered_blanklines++;
904 /* Process line for each bodyhash separately */
905 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
907 if (b->canon_method == PDKIM_CANON_RELAXED)
909 /* Lines with just spaces need to be buffered too */
910 uschar * cp = line.data;
915 if (c == '\r' && cp[1] == '\n') break;
916 if (c != ' ' && c != '\t') goto hash_process;
920 b->num_buffered_blanklines++;
925 /* At this point, we have a non-empty line, so release the buffered ones. */
927 while (b->num_buffered_blanklines)
929 rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
930 b->num_buffered_blanklines--;
933 rline = pdkim_update_ctx_bodyhash(b, &line, rline);
937 if (rnl) store_free(rnl);
938 if (rline) store_free(rline);
942 ctx->linebuf_offset = 0;
947 /* -------------------------------------------------------------------------- */
948 /* Callback from pdkim_feed below for processing complete headers */
949 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
952 pdkim_header_complete(pdkim_ctx * ctx)
954 if ( (ctx->cur_header->ptr > 1) &&
955 (ctx->cur_header->s[ctx->cur_header->ptr-1] == '\r') )
956 --ctx->cur_header->ptr;
957 (void) string_from_gstring(ctx->cur_header);
959 #ifdef EXPERIMENTAL_ARC
960 /* Feed the header line to ARC processing */
961 (void) arc_header_feed(ctx->cur_header, !(ctx->flags & PDKIM_MODE_SIGN));
964 if (++ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
966 /* SIGNING -------------------------------------------------------------- */
967 if (ctx->flags & PDKIM_MODE_SIGN)
968 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next) /* Traverse all signatures */
970 /* Add header to the signed headers list (in reverse order) */
971 sig->headers = pdkim_prepend_stringlist(sig->headers, ctx->cur_header->s);
973 /* VERIFICATION ----------------------------------------------------------- */
974 /* DKIM-Signature: headers are added to the verification list */
980 debug_printf("DKIM >> raw hdr: ");
981 pdkim_quoteprint(CUS ctx->cur_header->s, ctx->cur_header->ptr);
984 if (strncasecmp(CCS ctx->cur_header->s,
985 DKIM_SIGNATURE_HEADERNAME,
986 Ustrlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
988 pdkim_signature * sig, * last_sig;
989 /* Create and chain new signature block. We could error-check for all
990 required tags here, but prefer to create the internal sig and expicitly
991 fail verification of it later. */
993 DEBUG(D_acl) debug_printf(
994 "DKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
996 sig = pdkim_parse_sig_header(ctx, ctx->cur_header->s);
998 if (!(last_sig = ctx->sig))
1002 while (last_sig->next) last_sig = last_sig->next;
1003 last_sig->next = sig;
1006 if (--dkim_collect_input == 0)
1008 ctx->headers = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->s);
1009 ctx->cur_header->s[ctx->cur_header->ptr = 0] = '\0';
1010 return PDKIM_ERR_EXCESS_SIGS;
1014 /* all headers are stored for signature verification */
1015 ctx->headers = pdkim_prepend_stringlist(ctx->headers, ctx->cur_header->s);
1019 ctx->cur_header->s[ctx->cur_header->ptr = 0] = '\0'; /* leave buffer for reuse */
1025 /* -------------------------------------------------------------------------- */
1026 #define HEADER_BUFFER_FRAG_SIZE 256
1029 pdkim_feed(pdkim_ctx * ctx, uschar * data, int len)
1031 /* Alternate EOD signal, used in non-dotstuffing mode */
1033 pdkim_body_complete(ctx);
1035 else for (int p = 0; p < len; p++)
1040 if (ctx->flags & PDKIM_PAST_HDRS)
1042 if (c == '\n' && !(ctx->flags & PDKIM_SEEN_CR)) /* emulate the CR */
1044 ctx->linebuf[ctx->linebuf_offset++] = '\r';
1045 if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1046 return PDKIM_ERR_LONG_LINE;
1049 /* Processing body byte */
1050 ctx->linebuf[ctx->linebuf_offset++] = c;
1052 ctx->flags |= PDKIM_SEEN_CR;
1055 ctx->flags &= ~PDKIM_SEEN_CR;
1056 pdkim_bodyline_complete(ctx);
1059 if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1060 return PDKIM_ERR_LONG_LINE;
1064 /* Processing header byte */
1066 ctx->flags |= PDKIM_SEEN_CR;
1069 if (!(ctx->flags & PDKIM_SEEN_CR)) /* emulate the CR */
1070 ctx->cur_header = string_catn(ctx->cur_header, CUS "\r", 1);
1072 if (ctx->flags & PDKIM_SEEN_LF) /* Seen last header line */
1074 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1077 ctx->flags = (ctx->flags & ~(PDKIM_SEEN_LF|PDKIM_SEEN_CR)) | PDKIM_PAST_HDRS;
1078 DEBUG(D_acl) debug_printf(
1079 "DKIM >> Body data for hash, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1083 ctx->flags = (ctx->flags & ~PDKIM_SEEN_CR) | PDKIM_SEEN_LF;
1085 else if (ctx->flags & PDKIM_SEEN_LF)
1087 if (!(c == '\t' || c == ' ')) /* End of header */
1088 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1090 ctx->flags &= ~PDKIM_SEEN_LF;
1093 if (!ctx->cur_header || ctx->cur_header->ptr < PDKIM_MAX_HEADER_LEN)
1094 ctx->cur_header = string_catn(ctx->cur_header, CUS &data[p], 1);
1102 /* Extend a growing header with a continuation-linebreak */
1104 pdkim_hdr_cont(gstring * str, int * col)
1107 return string_catn(str, US"\r\n\t", 3);
1113 * RFC 5322 specifies that header line length SHOULD be no more than 78
1116 * Returns gstring (not nul-terminated) appending to one supplied
1118 * col: this int holds and receives column number (octets since last '\n')
1119 * str: partial string to append to
1120 * pad: padding, split line or space after before or after eg: ";".
1121 * Only the initial charater is used.
1122 * intro: - must join to payload eg "h=", usually the tag name
1123 * payload: eg base64 data - long data can be split arbitrarily.
1125 * this code doesn't fold the header in some of the places that RFC4871
1126 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1127 * pairs and inside long values. it also always spaces or breaks after the
1130 * No guarantees are made for output given out-of range input. like tag
1131 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1135 pdkim_headcat(int * col, gstring * str,
1136 const uschar * pad, const uschar * intro, const uschar * payload)
1138 int len, chomp, padded = 0;
1140 /* If we can fit at least the pad at the end of current line, do it now.
1141 Otherwise, wrap if there is a pad. */
1146 str = string_catn(str, pad, 1);
1152 str = pdkim_hdr_cont(str, col);
1154 /* Special case: if the whole addition does not fit at the end of the current
1155 line, but could fit on a new line, wrap to give it its full, dedicated line. */
1157 len = (pad ? 2 : padded)
1158 + (intro ? Ustrlen(intro) : 0)
1159 + (payload ? Ustrlen(payload) : 0);
1160 if (len <= 77 && *col+len > 78)
1162 str = pdkim_hdr_cont(str, col);
1166 /* Either we already dealt with the pad or we know there is room */
1170 str = string_catn(str, pad, 1);
1171 str = string_catn(str, US" ", 1);
1174 else if (padded && *col < 78)
1176 str = string_catn(str, US" ", 1);
1180 /* Call recursively with intro as payload: it gets the same, special treatment
1181 (that is, not split if < 78). */
1184 str = pdkim_headcat(col, str, NULL, NULL, intro);
1187 for (len = Ustrlen(payload); len; len -= chomp)
1190 str = pdkim_hdr_cont(str, col);
1191 chomp = *col+len > 78 ? 78 - *col : len;
1192 str = string_catn(str, payload, chomp);
1201 /* -------------------------------------------------------------------------- */
1203 /* Signing: create signature header
1206 pdkim_create_header(pdkim_signature * sig, BOOL final)
1212 gstring * canon_all;
1214 canon_all = string_cat (NULL, pdkim_canons[sig->canon_headers]);
1215 canon_all = string_catn(canon_all, US"/", 1);
1216 canon_all = string_cat (canon_all, pdkim_canons[sig->canon_body]);
1217 (void) string_from_gstring(canon_all);
1219 hdr = string_cat(NULL, US"DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1222 /* Required and static bits */
1223 hdr = pdkim_headcat(&col, hdr, US";", US"a=", dkim_sig_to_a_tag(sig));
1224 hdr = pdkim_headcat(&col, hdr, US";", US"q=", pdkim_querymethods[sig->querymethod]);
1225 hdr = pdkim_headcat(&col, hdr, US";", US"c=", canon_all->s);
1226 hdr = pdkim_headcat(&col, hdr, US";", US"d=", sig->domain);
1227 hdr = pdkim_headcat(&col, hdr, US";", US"s=", sig->selector);
1229 /* list of header names can be split between items. */
1231 uschar * n = string_copy(sig->headernames);
1232 uschar * i = US"h=";
1237 uschar * c = Ustrchr(n, ':');
1242 hdr = pdkim_headcat(&col, hdr, NULL, NULL, US":");
1244 hdr = pdkim_headcat(&col, hdr, s, i, n);
1255 base64_bh = pdkim_encode_base64(&sig->calc_body_hash->bh);
1256 hdr = pdkim_headcat(&col, hdr, US";", US"bh=", base64_bh);
1260 hdr = pdkim_headcat(&col, hdr, US";", US"i=", sig->identity);
1262 if (sig->created > 0)
1266 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->created);
1267 hdr = pdkim_headcat(&col, hdr, US";", US"t=", minibuf);
1270 if (sig->expires > 0)
1274 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->expires);
1275 hdr = pdkim_headcat(&col, hdr, US";", US"x=", minibuf);
1278 if (sig->bodylength >= 0)
1282 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->bodylength);
1283 hdr = pdkim_headcat(&col, hdr, US";", US"l=", minibuf);
1286 /* Preliminary or final version? */
1289 base64_b = pdkim_encode_base64(&sig->sighash);
1290 hdr = pdkim_headcat(&col, hdr, US";", US"b=", base64_b);
1292 /* add trailing semicolon: I'm not sure if this is actually needed */
1293 hdr = pdkim_headcat(&col, hdr, NULL, US";", US"");
1297 /* To satisfy the rule "all surrounding whitespace [...] deleted"
1298 ( RFC 6376 section 3.7 ) we ensure there is no whitespace here. Otherwise
1299 the headcat routine could insert a linebreak which the relaxer would reduce
1300 to a single space preceding the terminating semicolon, resulting in an
1301 incorrect header-hash. */
1302 hdr = pdkim_headcat(&col, hdr, US";", US"b=;", US"");
1305 return string_from_gstring(hdr);
1309 /* -------------------------------------------------------------------------- */
1311 /* According to draft-ietf-dcrup-dkim-crypto-07 "keys are 256 bits" (referring
1312 to DNS, hence the pubkey). Check for more than 32 bytes; if so assume the
1313 alternate possible representation (still) being discussed: a
1314 SubjectPublickeyInfo wrapped key - and drop all but the trailing 32-bytes (it
1315 should be a DER, with exactly 12 leading bytes - but we could accept a BER also,
1316 which could be any size). We still rely on the crypto library for checking for
1319 When the RFC is published this should be re-addressed. */
1322 check_bare_ed25519_pubkey(pdkim_pubkey * p)
1324 int excess = p->key.len - 32;
1328 debug_printf("DKIM: unexpected pubkey len %lu\n", (unsigned long) p->key.len);
1329 p->key.data += excess; p->key.len = 32;
1334 static pdkim_pubkey *
1335 pdkim_key_from_dns(pdkim_ctx * ctx, pdkim_signature * sig, ev_ctx * vctx,
1336 const uschar ** errstr)
1338 uschar * dns_txt_name, * dns_txt_reply;
1341 /* Fetch public key for signing domain, from DNS */
1343 dns_txt_name = string_sprintf("%s._domainkey.%s.", sig->selector, sig->domain);
1345 if ( !(dns_txt_reply = ctx->dns_txt_callback(dns_txt_name))
1346 || dns_txt_reply[0] == '\0'
1349 sig->verify_status = PDKIM_VERIFY_INVALID;
1350 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1357 "DKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
1361 pdkim_quoteprint(CUS dns_txt_reply, Ustrlen(dns_txt_reply));
1364 if ( !(p = pdkim_parse_pubkey_record(CUS dns_txt_reply))
1365 || (Ustrcmp(p->srvtype, "*") != 0 && Ustrcmp(p->srvtype, "email") != 0)
1368 sig->verify_status = PDKIM_VERIFY_INVALID;
1369 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD;
1374 debug_printf(" Invalid public key service type '%s'\n", p->srvtype);
1376 debug_printf(" Error while parsing public key record\n");
1378 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1383 DEBUG(D_acl) debug_printf(
1384 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1386 /* Import public key */
1388 /* Normally we use the signature a= tag to tell us the pubkey format.
1389 When signing under debug we do a test-import of the pubkey, and at that
1390 time we do not have a signature so we must interpret the pubkey k= tag
1391 instead. Assume writing on the sig is ok in that case. */
1393 if (sig->keytype < 0)
1394 if ((sig->keytype = pdkim_keyname_to_keytype(p->keytype)) < 0)
1396 DEBUG(D_acl) debug_printf("verify_init: unhandled keytype %s\n", p->keytype);
1397 sig->verify_status = PDKIM_VERIFY_INVALID;
1398 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
1402 if (sig->keytype == KEYTYPE_ED25519)
1403 check_bare_ed25519_pubkey(p);
1405 if ((*errstr = exim_dkim_verify_init(&p->key,
1406 sig->keytype == KEYTYPE_ED25519 ? KEYFMT_ED25519_BARE : KEYFMT_DER,
1407 vctx, &sig->keybits)))
1409 DEBUG(D_acl) debug_printf("verify_init: %s\n", *errstr);
1410 sig->verify_status = PDKIM_VERIFY_INVALID;
1411 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
1415 vctx->keytype = sig->keytype;
1420 /* -------------------------------------------------------------------------- */
1421 /* Sort and filter the sigs developed from the message */
1423 static pdkim_signature *
1424 sort_sig_methods(pdkim_signature * siglist)
1426 pdkim_signature * yield, ** ss;
1427 const uschar * prefs;
1431 if (!siglist) return NULL;
1433 /* first select in order of hashtypes */
1434 DEBUG(D_acl) debug_printf("DKIM: dkim_verify_hashes '%s'\n", dkim_verify_hashes);
1435 for (prefs = dkim_verify_hashes, sep = 0, yield = NULL, ss = &yield;
1436 ele = string_nextinlist(&prefs, &sep, NULL, 0); )
1438 int i = pdkim_hashname_to_hashtype(CUS ele, 0);
1439 for (pdkim_signature * s = siglist, * next, ** prev = &siglist; s;
1443 if (s->hashtype == i)
1444 { *prev = next; s->next = NULL; *ss = s; ss = &s->next; }
1450 /* then in order of keytypes */
1452 DEBUG(D_acl) debug_printf("DKIM: dkim_verify_keytypes '%s'\n", dkim_verify_keytypes);
1453 for (prefs = dkim_verify_keytypes, sep = 0, yield = NULL, ss = &yield;
1454 ele = string_nextinlist(&prefs, &sep, NULL, 0); )
1456 int i = pdkim_keyname_to_keytype(CUS ele);
1457 for (pdkim_signature * s = siglist, * next, ** prev = &siglist; s;
1461 if (s->keytype == i)
1462 { *prev = next; s->next = NULL; *ss = s; ss = &s->next; }
1468 DEBUG(D_acl) for (pdkim_signature * s = yield; s; s = s->next)
1469 debug_printf(" retain d=%s s=%s a=%s\n",
1470 s->domain, s->selector, dkim_sig_to_a_tag(s));
1475 /* -------------------------------------------------------------------------- */
1478 pdkim_feed_finish(pdkim_ctx * ctx, pdkim_signature ** return_signatures,
1479 const uschar ** err)
1481 BOOL verify_pass = FALSE;
1483 /* Check if we must still flush a (partial) header. If that is the
1484 case, the message has no body, and we must compute a body hash
1485 out of '<CR><LF>' */
1486 if (ctx->cur_header && ctx->cur_header->ptr > 0)
1491 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1494 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
1495 rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
1496 if (rnl) store_free(rnl);
1499 DEBUG(D_acl) debug_printf(
1500 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1502 /* Build (and/or evaluate) body hash. Do this even if no DKIM sigs, in case we
1503 have a hash to do for ARC. */
1505 pdkim_finish_bodyhash(ctx);
1507 /* Sort and filter the recived signatures */
1509 if (!(ctx->flags & PDKIM_MODE_SIGN))
1510 ctx->sig = sort_sig_methods(ctx->sig);
1514 DEBUG(D_acl) debug_printf("DKIM: no signatures\n");
1515 *return_signatures = NULL;
1519 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next)
1522 uschar * sig_hdr = US"";
1524 gstring * hdata = NULL;
1527 if ( !(ctx->flags & PDKIM_MODE_SIGN)
1528 && sig->verify_status == PDKIM_VERIFY_FAIL)
1531 debug_printf("DKIM: [%s] abandoning this signature\n", sig->domain);
1535 /*XXX The hash of the headers is needed for GCrypt (for which we can do RSA
1536 signing only, as it happens) and for either GnuTLS and OpenSSL when we are
1537 signing with EC (specifically, Ed25519). The former is because the GCrypt
1538 signing operation is pure (does not do its own hash) so we must hash. The
1539 latter is because we (stupidly, but this is what the IETF draft is saying)
1540 must hash with the declared hash method, then pass the result to the library
1541 hash-and-sign routine (because that's all the libraries are providing. And
1542 we're stuck with whatever that hidden hash method is, too). We may as well
1543 do this hash incrementally.
1544 We don't need the hash we're calculating here for the GnuTLS and OpenSSL
1545 cases of RSA signing, since those library routines can do hash-and-sign.
1547 Some time in the future we could easily avoid doing the hash here for those
1548 cases (which will be common for a long while. We could also change from
1549 the current copy-all-the-headers-into-one-block, then call the hash-and-sign
1550 implementation - to a proper incremental one. Unfortunately, GnuTLS just
1551 cannot do incremental - either signing or verification. Unsure about GCrypt.
1554 /*XXX The header hash is also used (so far) by the verify operation */
1556 if (!exim_sha_init(&hhash_ctx, pdkim_hashes[sig->hashtype].exim_hashmethod))
1558 log_write(0, LOG_MAIN|LOG_PANIC,
1559 "DKIM: hash setup error, possibly nonhandled hashtype");
1563 if (ctx->flags & PDKIM_MODE_SIGN)
1564 DEBUG(D_acl) debug_printf(
1565 "DKIM >> Headers to be signed: >>>>>>>>>>>>\n"
1569 DEBUG(D_acl) debug_printf(
1570 "DKIM >> Header data for hash, canonicalized (%-7s), in sequence >>\n",
1571 pdkim_canons[sig->canon_headers]);
1574 /* SIGNING ---------------------------------------------------------------- */
1575 /* When signing, walk through our header list and add them to the hash. As we
1576 go, construct a list of the header's names to use for the h= parameter.
1577 Then append to that list any remaining header names for which there was no
1580 if (ctx->flags & PDKIM_MODE_SIGN)
1587 /* Import private key, including the keytype which we need for building
1588 the signature header */
1590 if ((*err = exim_dkim_signing_init(CUS sig->privkey, &sctx)))
1592 log_write(0, LOG_MAIN|LOG_PANIC, "signing_init: %s", *err);
1593 return PDKIM_ERR_RSA_PRIVKEY;
1595 sig->keytype = sctx.keytype;
1597 sig->headernames = NULL; /* Collected signed header names */
1598 for (pdkim_stringlist * p = sig->headers; p; p = p->next)
1600 uschar * rh = p->value;
1602 if (header_name_match(rh, sig->sign_headers) == PDKIM_OK)
1604 /* Collect header names (Note: colon presence is guaranteed here) */
1605 g = string_append_listele_n(g, ':', rh, Ustrchr(rh, ':') - rh);
1607 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1608 rh = pdkim_relax_header(rh, TRUE); /* cook header for relaxed canon */
1610 /* Feed header to the hash algorithm */
1611 exim_sha_update(&hhash_ctx, CUS rh, Ustrlen(rh));
1613 /* Remember headers block for signing (when the library cannot do incremental) */
1614 /*XXX we could avoid doing this for all but the GnuTLS/RSA case */
1615 hdata = exim_dkim_data_append(hdata, rh);
1617 DEBUG(D_acl) pdkim_quoteprint(rh, Ustrlen(rh));
1621 /* Any headers we wanted to sign but were not present must also be listed.
1622 Ignore elements that have been ticked-off or are marked as never-oversign. */
1624 l = sig->sign_headers;
1625 while((s = string_nextinlist(&l, &sep, NULL, 0)))
1627 if (*s == '+') /* skip oversigning marker */
1629 if (*s != '_' && *s != '=')
1630 g = string_append_listele(g, ':', s);
1632 sig->headernames = string_from_gstring(g);
1634 /* Create signature header with b= omitted */
1635 sig_hdr = pdkim_create_header(sig, FALSE);
1638 /* VERIFICATION ----------------------------------------------------------- */
1639 /* When verifying, walk through the header name list in the h= parameter and
1640 add the headers to the hash in that order. */
1643 uschar * p = sig->headernames;
1649 for (pdkim_stringlist * hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1655 if ((q = Ustrchr(p, ':')))
1658 /*XXX walk the list of headers in same order as received. */
1659 for (pdkim_stringlist * hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1661 && strncasecmp(CCS hdrs->value, CCS p, Ustrlen(p)) == 0
1662 && (hdrs->value)[Ustrlen(p)] == ':'
1665 /* cook header for relaxed canon, or just copy it for simple */
1667 uschar * rh = sig->canon_headers == PDKIM_CANON_RELAXED
1668 ? pdkim_relax_header(hdrs->value, TRUE)
1669 : string_copy(CUS hdrs->value);
1671 /* Feed header to the hash algorithm */
1672 exim_sha_update(&hhash_ctx, CUS rh, Ustrlen(rh));
1674 DEBUG(D_acl) pdkim_quoteprint(rh, Ustrlen(rh));
1683 sig_hdr = string_copy(sig->rawsig_no_b_val);
1687 DEBUG(D_acl) debug_printf(
1688 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1693 "DKIM >> Signed DKIM-Signature header, pre-canonicalized >>>>>>>>>>>>>\n");
1694 pdkim_quoteprint(CUS sig_hdr, Ustrlen(sig_hdr));
1696 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1699 /* Relax header if necessary */
1700 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1701 sig_hdr = pdkim_relax_header(sig_hdr, FALSE);
1705 debug_printf("DKIM >> Signed DKIM-Signature header, canonicalized (%-7s) >>>>>>>\n",
1706 pdkim_canons[sig->canon_headers]);
1707 pdkim_quoteprint(CUS sig_hdr, Ustrlen(sig_hdr));
1709 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1712 /* Finalize header hash */
1713 exim_sha_update(&hhash_ctx, CUS sig_hdr, Ustrlen(sig_hdr));
1714 exim_sha_finish(&hhash_ctx, &hhash);
1718 debug_printf("DKIM [%s] Header %s computed: ",
1719 sig->domain, pdkim_hashes[sig->hashtype].dkim_hashname);
1720 pdkim_hexprint(hhash.data, hhash.len);
1723 /* Remember headers block for signing (when the signing library cannot do
1725 if (ctx->flags & PDKIM_MODE_SIGN)
1726 hdata = exim_dkim_data_append(hdata, US sig_hdr);
1728 /* SIGNING ---------------------------------------------------------------- */
1729 if (ctx->flags & PDKIM_MODE_SIGN)
1731 hashmethod hm = sig->keytype == KEYTYPE_ED25519
1732 #if defined(SIGN_OPENSSL)
1737 : pdkim_hashes[sig->hashtype].exim_hashmethod;
1739 #ifdef SIGN_HAVE_ED25519
1740 /* For GCrypt, and for EC, we pass the hash-of-headers to the signing
1741 routine. For anything else we just pass the headers. */
1743 if (sig->keytype != KEYTYPE_ED25519)
1746 hhash.data = hdata->s;
1747 hhash.len = hdata->ptr;
1750 if ((*err = exim_dkim_sign(&sctx, hm, &hhash, &sig->sighash)))
1752 log_write(0, LOG_MAIN|LOG_PANIC, "signing: %s", *err);
1753 return PDKIM_ERR_RSA_SIGNING;
1758 debug_printf( "DKIM [%s] b computed: ", sig->domain);
1759 pdkim_hexprint(sig->sighash.data, sig->sighash.len);
1762 sig->signature_header = pdkim_create_header(sig, TRUE);
1765 /* VERIFICATION ----------------------------------------------------------- */
1771 /* Make sure we have all required signature tags */
1772 if (!( sig->domain && *sig->domain
1773 && sig->selector && *sig->selector
1774 && sig->headernames && *sig->headernames
1775 && sig->bodyhash.data
1776 && sig->sighash.data
1777 && sig->keytype >= 0
1778 && sig->hashtype >= 0
1782 sig->verify_status = PDKIM_VERIFY_INVALID;
1783 sig->verify_ext_status = PDKIM_VERIFY_INVALID_SIGNATURE_ERROR;
1785 DEBUG(D_acl) debug_printf(
1786 " Error in DKIM-Signature header: tags missing or invalid (%s)\n"
1787 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n",
1788 !(sig->domain && *sig->domain) ? "d="
1789 : !(sig->selector && *sig->selector) ? "s="
1790 : !(sig->headernames && *sig->headernames) ? "h="
1791 : !sig->bodyhash.data ? "bh="
1792 : !sig->sighash.data ? "b="
1793 : sig->keytype < 0 || sig->hashtype < 0 ? "a="
1799 /* Make sure sig uses supported DKIM version (only v1) */
1800 if (sig->version != 1)
1802 sig->verify_status = PDKIM_VERIFY_INVALID;
1803 sig->verify_ext_status = PDKIM_VERIFY_INVALID_DKIM_VERSION;
1805 DEBUG(D_acl) debug_printf(
1806 " Error in DKIM-Signature header: unsupported DKIM version\n"
1807 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1813 debug_printf( "DKIM [%s] b from mail: ", sig->domain);
1814 pdkim_hexprint(sig->sighash.data, sig->sighash.len);
1817 if (!(sig->pubkey = pdkim_key_from_dns(ctx, sig, &vctx, err)))
1819 log_write(0, LOG_MAIN, "DKIM: %s%s %s%s [failed key import]",
1820 sig->domain ? "d=" : "", sig->domain ? sig->domain : US"",
1821 sig->selector ? "s=" : "", sig->selector ? sig->selector : US"");
1825 /* If the pubkey limits to a list of specific hashes, ignore sigs that
1826 do not have the hash part of the sig algorithm matching */
1828 if (sig->pubkey->hashes)
1830 const uschar * list = sig->pubkey->hashes, * ele;
1832 while ((ele = string_nextinlist(&list, &sep, NULL, 0)))
1833 if (Ustrcmp(ele, pdkim_hashes[sig->hashtype].dkim_hashname) == 0) break;
1836 DEBUG(D_acl) debug_printf("pubkey h=%s vs. sig a=%s_%s\n",
1837 sig->pubkey->hashes,
1838 pdkim_keytypes[sig->keytype],
1839 pdkim_hashes[sig->hashtype].dkim_hashname);
1840 sig->verify_status = PDKIM_VERIFY_FAIL;
1841 sig->verify_ext_status = PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH;
1846 hm = sig->keytype == KEYTYPE_ED25519
1847 #if defined(SIGN_OPENSSL)
1852 : pdkim_hashes[sig->hashtype].exim_hashmethod;
1854 /* Check the signature */
1856 if ((*err = exim_dkim_verify(&vctx, hm, &hhash, &sig->sighash)))
1858 DEBUG(D_acl) debug_printf("headers verify: %s\n", *err);
1859 sig->verify_status = PDKIM_VERIFY_FAIL;
1860 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1863 if (*dkim_verify_min_keysizes)
1866 uschar * ss = expand_getkeyed(US pdkim_keytypes[sig->keytype],
1867 dkim_verify_min_keysizes);
1868 if (ss && (minbits = atoi(CS ss)) > sig->keybits)
1870 DEBUG(D_acl) debug_printf("Key too short: Actual: %s %u Minima '%s'\n",
1871 pdkim_keytypes[sig->keytype], sig->keybits, dkim_verify_min_keysizes);
1872 sig->verify_status = PDKIM_VERIFY_FAIL;
1873 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE;
1878 /* We have a winner! (if bodyhash was correct earlier) */
1879 if (sig->verify_status == PDKIM_VERIFY_NONE)
1881 sig->verify_status = PDKIM_VERIFY_PASS;
1883 if (dkim_verify_minimal) break;
1890 debug_printf("DKIM [%s] %s signature status: %s",
1891 sig->domain, dkim_sig_to_a_tag(sig),
1892 pdkim_verify_status_str(sig->verify_status));
1893 if (sig->verify_ext_status > 0)
1894 debug_printf(" (%s)\n",
1895 pdkim_verify_ext_status_str(sig->verify_ext_status));
1902 /* If requested, set return pointer to signature(s) */
1903 if (return_signatures)
1904 *return_signatures = ctx->sig;
1906 return ctx->flags & PDKIM_MODE_SIGN || verify_pass
1907 ? PDKIM_OK : PDKIM_FAIL;
1911 /* -------------------------------------------------------------------------- */
1913 DLLEXPORT pdkim_ctx *
1914 pdkim_init_verify(uschar * (*dns_txt_callback)(const uschar *), BOOL dot_stuffing)
1918 ctx = store_get(sizeof(pdkim_ctx), FALSE);
1919 memset(ctx, 0, sizeof(pdkim_ctx));
1921 if (dot_stuffing) ctx->flags = PDKIM_DOT_TERM;
1922 /* The line-buffer is for message data, hence tainted */
1923 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN, TRUE);
1924 ctx->dns_txt_callback = dns_txt_callback;
1930 /* -------------------------------------------------------------------------- */
1932 DLLEXPORT pdkim_signature *
1933 pdkim_init_sign(pdkim_ctx * ctx,
1934 uschar * domain, uschar * selector, uschar * privkey,
1935 uschar * hashname, const uschar ** errstr)
1938 pdkim_signature * sig;
1940 if (!domain || !selector || !privkey)
1943 /* Allocate & init one signature struct */
1945 sig = store_get(sizeof(pdkim_signature), FALSE);
1946 memset(sig, 0, sizeof(pdkim_signature));
1948 sig->bodylength = -1;
1950 sig->domain = string_copy(US domain);
1951 sig->selector = string_copy(US selector);
1952 sig->privkey = string_copy(US privkey);
1955 for (hashtype = 0; hashtype < nelem(pdkim_hashes); hashtype++)
1956 if (Ustrcmp(hashname, pdkim_hashes[hashtype].dkim_hashname) == 0)
1957 { sig->hashtype = hashtype; break; }
1958 if (hashtype >= nelem(pdkim_hashes))
1960 log_write(0, LOG_MAIN|LOG_PANIC,
1961 "DKIM: unrecognised hashname '%s'", hashname);
1967 pdkim_signature s = *sig;
1970 debug_printf("DKIM (checking verify key)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1971 if (!pdkim_key_from_dns(ctx, &s, &vctx, errstr))
1972 debug_printf("WARNING: bad dkim key in dns\n");
1973 debug_printf("DKIM (finished checking verify key)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1979 /* -------------------------------------------------------------------------- */
1982 pdkim_set_optional(pdkim_signature * sig,
1983 char * sign_headers,
1988 unsigned long created,
1989 unsigned long expires)
1992 sig->identity = string_copy(US identity);
1994 sig->sign_headers = string_copy(sign_headers
1995 ? US sign_headers : US PDKIM_DEFAULT_SIGN_HEADERS);
1997 sig->canon_headers = canon_headers;
1998 sig->canon_body = canon_body;
1999 sig->bodylength = bodylength;
2000 sig->created = created;
2001 sig->expires = expires;
2008 /* Set up a blob for calculating the bodyhash according to the
2009 given needs. Use an existing one if possible, or create a new one.
2011 Return: hashblob pointer, or NULL on error
2014 pdkim_set_bodyhash(pdkim_ctx * ctx, int hashtype, int canon_method,
2019 if (hashtype == -1 || canon_method == -1) return NULL;
2021 for (b = ctx->bodyhash; b; b = b->next)
2022 if ( hashtype == b->hashtype
2023 && canon_method == b->canon_method
2024 && bodylength == b->bodylength)
2026 DEBUG(D_receive) debug_printf("DKIM: using existing bodyhash %d/%d/%ld\n",
2027 hashtype, canon_method, bodylength);
2031 DEBUG(D_receive) debug_printf("DKIM: new bodyhash %d/%d/%ld\n",
2032 hashtype, canon_method, bodylength);
2033 b = store_get(sizeof(pdkim_bodyhash), FALSE);
2034 b->next = ctx->bodyhash;
2035 b->hashtype = hashtype;
2036 b->canon_method = canon_method;
2037 b->bodylength = bodylength;
2038 if (!exim_sha_init(&b->body_hash_ctx, /*XXX hash method: extend for sha512 */
2039 pdkim_hashes[hashtype].exim_hashmethod))
2042 debug_printf("DKIM: hash init error, possibly nonhandled hashtype\n");
2045 b->signed_body_bytes = 0;
2046 b->num_buffered_blanklines = 0;
2052 /* Set up a blob for calculating the bodyhash according to the
2053 needs of this signature. Use an existing one if possible, or
2056 Return: hashblob pointer, or NULL on error (only used as a boolean).
2059 pdkim_set_sig_bodyhash(pdkim_ctx * ctx, pdkim_signature * sig)
2061 pdkim_bodyhash * b = pdkim_set_bodyhash(ctx,
2062 sig->hashtype, sig->canon_body, sig->bodylength);
2063 sig->calc_body_hash = b;
2068 /* -------------------------------------------------------------------------- */
2072 pdkim_init_context(pdkim_ctx * ctx, BOOL dot_stuffed,
2073 uschar * (*dns_txt_callback)(const uschar *))
2075 memset(ctx, 0, sizeof(pdkim_ctx));
2076 ctx->flags = dot_stuffed ? PDKIM_MODE_SIGN | PDKIM_DOT_TERM : PDKIM_MODE_SIGN;
2077 /* The line buffer is for message data, hence tainted */
2078 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN, TRUE);
2079 DEBUG(D_acl) ctx->dns_txt_callback = dns_txt_callback;
2091 #endif /*DISABLE_DKIM*/