2 * PDKIM - a RFC4871 (DKIM) implementation
4 * Copyright (c) The Exim Maintainers 2021 - 2024
5 * Copyright (C) 2016 - 2020 Jeremy Harris <jgh@exim.org>
6 * Copyright (C) 2009 - 2016 Tom Kistner <tom@duncanthrax.net>
7 * SPDX-License-Identifier: GPL-2.0-or-later
9 * http://duncanthrax.net/pdkim/
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 #ifndef DISABLE_DKIM /* entire file */
32 # error Must not DISABLE_TLS, for DKIM
35 #include "crypt_ver.h"
38 # include <openssl/rsa.h>
39 # include <openssl/ssl.h>
40 # include <openssl/err.h>
41 #elif defined(SIGN_GNUTLS)
42 # include <gnutls/gnutls.h>
43 # include <gnutls/x509.h>
49 #define PDKIM_SIGNATURE_VERSION "1"
50 #define PDKIM_PUB_RECORD_VERSION US "DKIM1"
52 #define PDKIM_MAX_HEADER_LEN 65536
53 #define PDKIM_MAX_HEADERS 512
54 #define PDKIM_MAX_BODY_LINE_LEN 16384
55 #define PDKIM_DNS_TXT_MAX_NAMELEN 1024
57 /* -------------------------------------------------------------------------- */
58 struct pdkim_stringlist {
64 /* -------------------------------------------------------------------------- */
65 /* A bunch of list constants */
66 const uschar * pdkim_querymethods[] = {
70 const uschar * pdkim_canons[] = {
76 const pdkim_hashtype pdkim_hashes[] = {
77 { US"sha1", HASH_SHA1 },
78 { US"sha256", HASH_SHA2_256 },
79 { US"sha512", HASH_SHA2_512 }
82 const uschar * pdkim_keytypes[] = {
83 [KEYTYPE_RSA] = US"rsa",
84 #ifdef SIGN_HAVE_ED25519
85 [KEYTYPE_ED25519] = US"ed25519", /* Works for 3.6.0 GnuTLS, OpenSSL 1.1.1 */
88 #ifdef notyet_EC_dkim_extensions /* https://tools.ietf.org/html/draft-srose-dkim-ecc-00 */
95 typedef struct pdkim_combined_canon_entry {
99 } pdkim_combined_canon_entry;
101 pdkim_combined_canon_entry pdkim_combined_canons[] = {
102 { US"simple/simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
103 { US"simple/relaxed", PDKIM_CANON_SIMPLE, PDKIM_CANON_RELAXED },
104 { US"relaxed/simple", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
105 { US"relaxed/relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_RELAXED },
106 { US"simple", PDKIM_CANON_SIMPLE, PDKIM_CANON_SIMPLE },
107 { US"relaxed", PDKIM_CANON_RELAXED, PDKIM_CANON_SIMPLE },
112 static const blob lineending = {.data = US"\r\n", .len = 2};
114 /* -------------------------------------------------------------------------- */
116 dkim_sig_to_a_tag(const pdkim_signature * sig)
118 if ( sig->keytype < 0 || sig->keytype > nelem(pdkim_keytypes)
119 || sig->hashtype < 0 || sig->hashtype > nelem(pdkim_hashes))
121 return string_sprintf("%s-%s",
122 pdkim_keytypes[sig->keytype], pdkim_hashes[sig->hashtype].dkim_hashname);
127 pdkim_keyname_to_keytype(const uschar * s)
129 for (int i = 0; i < nelem(pdkim_keytypes); i++)
130 if (Ustrcmp(s, pdkim_keytypes[i]) == 0) return i;
135 pdkim_hashname_to_hashtype(const uschar * s, unsigned len)
137 if (!len) len = Ustrlen(s);
138 for (int i = 0; i < nelem(pdkim_hashes); i++)
139 if (Ustrncmp(s, pdkim_hashes[i].dkim_hashname, len) == 0)
145 pdkim_cstring_to_canons(const uschar * s, unsigned len,
146 int * canon_head, int * canon_body)
148 if (!len) len = Ustrlen(s);
149 for (int i = 0; pdkim_combined_canons[i].str; i++)
150 if ( Ustrncmp(s, pdkim_combined_canons[i].str, len) == 0
151 && len == Ustrlen(pdkim_combined_canons[i].str))
153 *canon_head = pdkim_combined_canons[i].canon_headers;
154 *canon_body = pdkim_combined_canons[i].canon_body;
162 pdkim_verify_status_str(int status)
166 case PDKIM_VERIFY_NONE: return "PDKIM_VERIFY_NONE";
167 case PDKIM_VERIFY_INVALID: return "PDKIM_VERIFY_INVALID";
168 case PDKIM_VERIFY_FAIL: return "PDKIM_VERIFY_FAIL";
169 case PDKIM_VERIFY_PASS: return "PDKIM_VERIFY_PASS";
170 default: return "PDKIM_VERIFY_UNKNOWN";
175 pdkim_verify_ext_status_str(int ext_status)
179 case PDKIM_VERIFY_FAIL_BODY: return "PDKIM_VERIFY_FAIL_BODY";
180 case PDKIM_VERIFY_FAIL_MESSAGE: return "PDKIM_VERIFY_FAIL_MESSAGE";
181 case PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH: return "PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH";
182 case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: return "PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE";
183 case PDKIM_VERIFY_INVALID_BUFFER_SIZE: return "PDKIM_VERIFY_INVALID_BUFFER_SIZE";
184 case PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD: return "PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD";
185 case PDKIM_VERIFY_INVALID_PUBKEY_IMPORT: return "PDKIM_VERIFY_INVALID_PUBKEY_IMPORT";
186 case PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE: return "PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE";
187 case PDKIM_VERIFY_INVALID_SIGNATURE_ERROR: return "PDKIM_VERIFY_INVALID_SIGNATURE_ERROR";
188 case PDKIM_VERIFY_INVALID_DKIM_VERSION: return "PDKIM_VERIFY_INVALID_DKIM_VERSION";
189 default: return "PDKIM_VERIFY_UNKNOWN";
194 pdkim_errstr(int status)
198 case PDKIM_OK: return US"OK";
199 case PDKIM_FAIL: return US"FAIL";
200 case PDKIM_ERR_RSA_PRIVKEY: return US"PRIVKEY";
201 case PDKIM_ERR_RSA_SIGNING: return US"SIGNING";
202 case PDKIM_ERR_LONG_LINE: return US"LONG_LINE";
203 case PDKIM_ERR_BUFFER_TOO_SMALL: return US"BUFFER_TOO_SMALL";
204 case PDKIM_ERR_EXCESS_SIGS: return US"EXCESS_SIGS";
205 case PDKIM_SIGN_PRIVKEY_WRAP: return US"PRIVKEY_WRAP";
206 case PDKIM_SIGN_PRIVKEY_B64D: return US"PRIVKEY_B64D";
207 default: return US"(unknown)";
212 /* -------------------------------------------------------------------------- */
215 static pdkim_stringlist *
216 pdkim_prepend_stringlist(pdkim_stringlist * base, const uschar * str)
218 pdkim_stringlist * new_entry = store_get(sizeof(pdkim_stringlist), GET_UNTAINTED);
220 memset(new_entry, 0, sizeof(pdkim_stringlist));
221 new_entry->value = string_copy(str);
222 if (base) new_entry->next = base;
228 /* Trim whitespace fore & aft */
231 pdkim_strtrim(gstring * str)
236 while (*p == '\t' || *p == ' ') /* dump the leading whitespace */
237 { str->size--; str->ptr--; str->s++; }
240 && ((q = str->s + str->ptr - 1), (*q == '\t' || *q == ' '))
242 str->ptr--; /* dump trailing whitespace */
244 (void) string_from_gstring(str);
249 /* -------------------------------------------------------------------------- */
252 pdkim_free_ctx(pdkim_ctx *ctx)
257 /* -------------------------------------------------------------------------- */
258 /* Matches the name of the passed raw "header" against
259 the passed colon-separated "tick", and invalidates
260 the entry in tick. Entries can be prefixed for multi- or over-signing,
261 in which case do not invalidate.
263 Returns OK for a match, or fail-code
267 header_name_match(const uschar * header, uschar * tick)
269 const uschar * ticklist = tick;
272 uschar * hname, * p, * ele;
273 uschar * hcolon = Ustrchr(header, ':'); /* Get header name */
276 return PDKIM_FAIL; /* This isn't a header */
278 /* if we had strncmpic() we wouldn't need this copy */
279 hname = string_copyn(header, hcolon-header);
281 while (p = US ticklist, ele = string_nextinlist(&ticklist, &sep, NULL, 0))
285 case '=': case '+': multisign = TRUE; ele++; break;
286 default: multisign = FALSE; break;
289 if (strcmpic(ele, hname) == 0)
292 *p = '_'; /* Invalidate this header name instance in tick-off list */
300 /* -------------------------------------------------------------------------- */
302 /* Performs "relaxed" canonicalization of a header. */
305 pdkim_relax_header_n(const uschar * header, int len, BOOL append_crlf)
307 BOOL past_field_name = FALSE;
308 BOOL seen_wsp = FALSE;
309 uschar * relaxed = store_get(len+3, GET_TAINTED);
310 uschar * q = relaxed;
312 for (const uschar * p = header; p - header < len; p++)
316 if (c == '\r' || c == '\n') /* Ignore CR & LF */
318 if (c == '\t' || c == ' ')
322 c = ' '; /* Turns WSP into SP */
326 if (!past_field_name && c == ':')
328 if (seen_wsp) q--; /* This removes WSP immediately before the colon */
329 seen_wsp = TRUE; /* This removes WSP immediately after the colon */
330 past_field_name = TRUE;
335 /* Lowercase header name */
336 if (!past_field_name) c = tolower(c);
340 if (q > relaxed && q[-1] == ' ') q--; /* Squash eventual trailing SP */
342 if (append_crlf) { *q++ = '\r'; *q++ = '\n'; }
349 pdkim_relax_header(const uschar * header, BOOL append_crlf)
351 return pdkim_relax_header_n(header, Ustrlen(header), append_crlf);
355 /* -------------------------------------------------------------------------- */
356 #define PDKIM_QP_ERROR_DECODE -1
358 static const uschar *
359 pdkim_decode_qp_char(const uschar *qp_p, int *c)
361 const uschar *initial_pos = qp_p;
363 /* Advance one char */
366 /* Check for two hex digits and decode them */
367 if (isxdigit(*qp_p) && isxdigit(qp_p[1]))
369 /* Do hex conversion */
370 *c = (isdigit(*qp_p) ? *qp_p - '0' : toupper(*qp_p) - 'A' + 10) << 4;
371 *c |= isdigit(qp_p[1]) ? qp_p[1] - '0' : toupper(qp_p[1]) - 'A' + 10;
375 /* Illegal char here */
376 *c = PDKIM_QP_ERROR_DECODE;
381 /* -------------------------------------------------------------------------- */
384 pdkim_decode_qp(const uschar * str)
388 const uschar * p = str;
389 uschar * n = store_get(Ustrlen(str)+1, GET_TAINTED);
397 p = pdkim_decode_qp_char(p, &nchar);
413 /* -------------------------------------------------------------------------- */
416 pdkim_decode_base64(const uschar * str, blob * b)
418 int dlen = b64decode(str, &b->data, str);
419 if (dlen < 0) b->data = NULL;
424 pdkim_encode_base64(blob * b)
426 return b64encode(b->data, b->len);
430 /* -------------------------------------------------------------------------- */
431 #define PDKIM_HDR_LIMBO 0
432 #define PDKIM_HDR_TAG 1
433 #define PDKIM_HDR_VALUE 2
435 static pdkim_signature *
436 pdkim_parse_sig_header(pdkim_ctx * ctx, uschar * raw_hdr)
438 pdkim_signature * sig = store_get(sizeof(pdkim_signature), GET_UNTAINTED);
440 gstring * cur_tag = NULL, * cur_val = NULL;
441 BOOL past_hname = FALSE, in_b_val = FALSE;
442 int where = PDKIM_HDR_LIMBO;
444 memset(sig, 0, sizeof(pdkim_signature));
445 sig->bodylength = -1;
447 /* Set so invalid/missing data error display is accurate */
452 q = sig->rawsig_no_b_val = store_get(Ustrlen(raw_hdr)+1, GET_TAINTED);
454 for (uschar * p = raw_hdr; ; p++)
459 if (c == '\r' || c == '\n')
462 /* Fast-forward through header name */
465 if (c == ':') past_hname = TRUE;
469 if (where == PDKIM_HDR_LIMBO)
471 /* In limbo, just wait for a tag-char to appear */
472 if (!(c >= 'a' && c <= 'z'))
475 where = PDKIM_HDR_TAG;
478 if (where == PDKIM_HDR_TAG)
481 if (Ustrcmp(string_from_gstring(cur_tag), "b") == 0)
486 where = PDKIM_HDR_VALUE;
489 else if (!isspace(c))
490 cur_tag = string_catn(cur_tag, p, 1);
492 if (where == PDKIM_HDR_VALUE)
494 if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
497 if (c == ';' || c == '\0')
499 /* We must have both tag and value, and tags must be one char except
500 for the possibility of "bh". */
502 if ( cur_tag && cur_val
503 && (cur_tag->ptr == 1 || *cur_tag->s == 'b')
506 (void) string_from_gstring(cur_val);
507 pdkim_strtrim(cur_val);
509 DEBUG(D_acl) debug_printf(" %s=%s\n", cur_tag->s, cur_val->s);
513 case 'b': /* sig-data or body-hash */
514 switch (cur_tag->s[1])
516 case '\0': pdkim_decode_base64(cur_val->s, &sig->sighash); break;
517 case 'h': if (cur_tag->ptr != 2) goto bad_tag;
518 pdkim_decode_base64(cur_val->s, &sig->bodyhash);
520 default: goto bad_tag;
523 case 'v': /* version */
524 /* We only support version 1, and that is currently the
525 only version there is. */
527 Ustrcmp(cur_val->s, PDKIM_SIGNATURE_VERSION) == 0 ? 1 : -1;
529 case 'a': /* algorithm */
531 const uschar * list = cur_val->s;
535 if ((elem = string_nextinlist(&list, &sep, NULL, 0)))
536 sig->keytype = pdkim_keyname_to_keytype(elem);
537 if ((elem = string_nextinlist(&list, &sep, NULL, 0)))
538 for (int i = 0; i < nelem(pdkim_hashes); i++)
539 if (Ustrcmp(elem, pdkim_hashes[i].dkim_hashname) == 0)
540 { sig->hashtype = i; break; }
544 case 'c': /* canonicalization */
545 pdkim_cstring_to_canons(cur_val->s, 0,
546 &sig->canon_headers, &sig->canon_body);
548 case 'q': /* Query method (for pubkey)*/
549 for (int i = 0; pdkim_querymethods[i]; i++)
550 if (Ustrcmp(cur_val->s, pdkim_querymethods[i]) == 0)
552 sig->querymethod = i; /* we never actually use this */
556 case 's': /* Selector */
557 sig->selector = string_copy_from_gstring(cur_val); break;
559 sig->domain = string_copy_from_gstring(cur_val); break;
561 sig->identity = pdkim_decode_qp(cur_val->s); break;
562 case 't': /* Timestamp */
563 sig->created = strtoul(CS cur_val->s, NULL, 10); break;
564 case 'x': /* Expiration */
565 sig->expires = strtoul(CS cur_val->s, NULL, 10); break;
566 case 'l': /* Body length count */
567 sig->bodylength = strtol(CS cur_val->s, NULL, 10); break;
568 case 'h': /* signed header fields */
569 sig->headernames = string_copy_from_gstring(cur_val); break;
570 case 'z': /* Copied headfields */
571 sig->copiedheaders = pdkim_decode_qp(cur_val->s); break;
572 /*XXX draft-ietf-dcrup-dkim-crypto-05 would need 'p' tag support
573 for rsafp signatures. But later discussion is dropping those. */
579 bad_tag: DEBUG(D_acl) debug_printf(" Unknown tag encountered: %Y\n", cur_tag);
581 cur_tag = cur_val = NULL;
583 where = PDKIM_HDR_LIMBO;
586 cur_val = string_catn(cur_val, p, 1);
597 if (sig->keytype < 0 || sig->hashtype < 0) /* Cannot verify this signature */
601 /* Chomp raw header. The final newline must not be added to the signature. */
602 while (--q > sig->rawsig_no_b_val && (*q == '\r' || *q == '\n'))
608 "DKIM >> Raw signature w/o b= tag value >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
609 debug_printf("%Z\n", US sig->rawsig_no_b_val);
611 "DKIM >> Sig size: %4u bits\n", (unsigned) sig->sighash.len*8);
613 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
616 if (!pdkim_set_sig_bodyhash(ctx, sig))
623 /* -------------------------------------------------------------------------- */
626 pdkim_parse_pubkey_record(const uschar * raw_record)
628 pdkim_pubkey * pub = store_get(sizeof(pdkim_pubkey), GET_TAINTED);
630 memset(pub, 0, sizeof(pdkim_pubkey));
632 for (const uschar * ele = raw_record, * tspec, * end, * val; *ele; ele = end)
634 Uskip_whitespace(&ele);
635 end = Ustrchrnul(ele, ';');
636 tspec = string_copyn(ele, end - ele);
637 if (*end) end++; /* skip the ; */
639 if ((val = Ustrchr(tspec, '=')))
641 int taglen = val++ - tspec;
643 DEBUG(D_acl) debug_printf(" %.*s=%s\n", taglen, tspec, val);
644 while (taglen > 1 && isspace(tspec[taglen-1]))
645 taglen--; /* Ignore whitespace before = */
646 Uskip_whitespace(&val); /* Ignore whitespace after = */
647 if (isspace(val[ Ustrlen(val)-1 ]))
648 { /* Ignore whitespace after value */
649 gstring * g = string_cat(NULL, val);
650 while (isspace(gstring_last_char(g)))
652 val = string_from_gstring(g);
655 if (taglen == 1) switch (tspec[0])
657 case 'v': pub->version = val; break;
658 case 'h': pub->hashes = val; break;
659 case 'k': pub->keytype = val; break;
660 case 'g': pub->granularity = val; break;
661 case 'n': pub->notes = pdkim_decode_qp(val); break;
662 case 'p': pdkim_decode_base64(val, &pub->key); break;
663 case 's': pub->srvtype = val; break;
664 case 't': if (Ustrchr(val, 'y')) pub->testing = 1;
665 if (Ustrchr(val, 's')) pub->no_subdomaining = 1;
667 default: goto bad_tag;
671 DEBUG(D_acl) debug_printf(" Unknown tag encountered\n");
675 /* Set fallback defaults */
677 pub->version = string_copy(PDKIM_PUB_RECORD_VERSION);
678 else if (Ustrcmp(pub->version, PDKIM_PUB_RECORD_VERSION) != 0)
680 DEBUG(D_acl) debug_printf(" Bad v= field\n");
684 if (!pub->granularity) pub->granularity = US"*";
685 if (!pub->keytype ) pub->keytype = US"rsa";
686 if (!pub->srvtype ) pub->srvtype = US"*";
692 DEBUG(D_acl) debug_printf(" Missing p= field\n");
697 /* -------------------------------------------------------------------------- */
699 /* Update one bodyhash with some additional data.
700 If we have to relax the data for this sig, return our copy of it. */
703 pdkim_update_ctx_bodyhash(pdkim_bodyhash * b, const blob * orig_data, blob * relaxed_data)
705 const blob * canon_data = orig_data;
708 /* Defaults to simple canon (no further treatment necessary) */
710 if (b->canon_method == PDKIM_CANON_RELAXED)
712 /* Relax the line if not done already */
715 BOOL seen_wsp = FALSE;
718 /* We want to be able to free this else we allocate
719 for the entire message which could be many MB. Since
720 we don't know what allocations the SHA routines might
721 do, not safe to use store_get()/store_reset(). */
723 relaxed_data = store_malloc(sizeof(blob) + orig_data->len+1);
724 relaxed_data->data = US (relaxed_data+1);
726 for (const uschar * p = orig_data->data, * r = p + orig_data->len; p < r; p++)
731 if (q > 0 && relaxed_data->data[q-1] == ' ')
734 else if (c == '\t' || c == ' ')
736 c = ' '; /* Turns WSP into SP */
743 relaxed_data->data[q++] = c;
745 relaxed_data->data[q] = '\0';
746 relaxed_data->len = q;
748 canon_data = relaxed_data;
751 /* Make sure we don't exceed the to-be-signed body length */
752 left = canon_data->len;
753 if ( b->bodylength >= 0
754 && left > (unsigned long)b->bodylength - b->signed_body_bytes
756 left = (unsigned long)b->bodylength - b->signed_body_bytes;
760 exim_sha_update(&b->body_hash_ctx, CUS canon_data->data, left);
761 b->signed_body_bytes += left;
762 DEBUG(D_acl) debug_printf("%.*Z\n", left, canon_data->data);
769 /* -------------------------------------------------------------------------- */
772 pdkim_finish_bodyhash(pdkim_ctx * ctx)
774 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next) /* Finish hashes */
776 DEBUG(D_acl) debug_printf("DKIM: finish bodyhash %s/%s/%ld len %ld\n",
777 pdkim_hashes[b->hashtype].dkim_hashname, pdkim_canons[b->canon_method],
778 b->bodylength, b->signed_body_bytes);
779 exim_sha_finish(&b->body_hash_ctx, &b->bh);
782 /* Traverse all signatures */
783 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next)
785 pdkim_bodyhash * b = sig->calc_body_hash;
789 debug_printf("DKIM [%s]%s Body bytes (%s) hashed: %lu\n"
790 "DKIM [%s]%s Body %s computed: ",
791 sig->domain, sig->selector, pdkim_canons[b->canon_method], b->signed_body_bytes,
792 sig->domain, sig->selector, pdkim_hashes[b->hashtype].dkim_hashname);
793 debug_printf("%.*H\n", b->bh.len, CUS b->bh.data);
796 /* SIGNING -------------------------------------------------------------- */
797 if (ctx->flags & PDKIM_MODE_SIGN)
799 /* If bodylength limit is set, and we have received less bytes
800 than the requested amount, effectively remove the limit tag. */
801 if (b->signed_body_bytes < sig->bodylength)
802 sig->bodylength = -1;
806 /* VERIFICATION --------------------------------------------------------- */
807 /* Be careful that the header sig included a bodyash */
809 if (sig->bodyhash.data && sig->bodyhash.len == b->bh.len
810 && memcmp(b->bh.data, sig->bodyhash.data, b->bh.len) == 0)
812 DEBUG(D_acl) debug_printf("DKIM [%s] Body hash compared OK\n", sig->domain);
818 debug_printf("DKIM [%s] Body hash signature from headers: ", sig->domain);
819 debug_printf("%.*H\n", sig->bodyhash.len, sig->bodyhash.data);
820 debug_printf("DKIM [%s] Body hash did NOT verify\n", sig->domain);
822 sig->verify_status = PDKIM_VERIFY_FAIL;
823 sig->verify_ext_status = PDKIM_VERIFY_FAIL_BODY;
831 pdkim_body_complete(pdkim_ctx * ctx)
833 /* In simple body mode, if any empty lines were buffered,
834 replace with one. rfc 4871 3.4.3 */
835 /*XXX checking the signed-body-bytes is a gross hack; I think
836 it indicates that all linebreaks should be buffered, including
837 the one terminating a text line */
839 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
840 if ( b->canon_method == PDKIM_CANON_SIMPLE
841 && b->signed_body_bytes == 0
842 && b->num_buffered_blanklines > 0
844 (void) pdkim_update_ctx_bodyhash(b, &lineending, NULL);
846 ctx->flags |= PDKIM_SEEN_EOD;
847 ctx->linebuf_offset = 0;
852 /* -------------------------------------------------------------------------- */
853 /* Call from pdkim_feed below for processing complete body lines */
854 /* NOTE: the line is not NUL-terminated; but we have a count */
857 pdkim_bodyline_complete(pdkim_ctx * ctx)
859 blob line = {.data = ctx->linebuf, .len = ctx->linebuf_offset};
863 /* Ignore extra data if we've seen the end-of-data marker */
864 if (ctx->flags & PDKIM_SEEN_EOD) goto all_skip;
866 /* We've always got one extra byte to stuff a zero ... */
867 ctx->linebuf[line.len] = '\0';
869 /* Terminate on EOD marker */
870 if (ctx->flags & PDKIM_DOT_TERM)
872 if (memcmp(line.data, ".\r\n", 3) == 0)
873 { pdkim_body_complete(ctx); return; }
876 if (memcmp(line.data, "..", 2) == 0)
877 { line.data++; line.len--; }
880 /* Empty lines need to be buffered until we find a non-empty line */
881 if (memcmp(line.data, "\r\n", 2) == 0)
883 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
884 b->num_buffered_blanklines++;
888 /* Process line for each bodyhash separately */
889 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
891 if (b->canon_method == PDKIM_CANON_RELAXED)
893 /* Lines with just spaces need to be buffered too */
894 uschar * cp = line.data;
899 if (c == '\r' && cp[1] == '\n') break;
900 if (c != ' ' && c != '\t') goto hash_process;
904 b->num_buffered_blanklines++;
909 /* At this point, we have a non-empty line, so release the buffered ones. */
911 while (b->num_buffered_blanklines)
913 rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
914 b->num_buffered_blanklines--;
917 rline = pdkim_update_ctx_bodyhash(b, &line, rline);
921 if (rnl) store_free(rnl);
922 if (rline) store_free(rline);
926 ctx->linebuf_offset = 0;
931 /* -------------------------------------------------------------------------- */
932 /* Callback from pdkim_feed below for processing complete headers */
933 #define DKIM_SIGNATURE_HEADERNAME "DKIM-Signature:"
936 pdkim_header_complete(pdkim_ctx * ctx)
938 gstring * g = ctx->cur_header;
940 if (gstring_length(g) > 1)
941 gstring_trim_trailing(g, '\r');
942 (void) string_from_gstring(g);
944 #ifdef EXPERIMENTAL_ARC
945 /* Feed the header line also to ARC processing */
947 const misc_module_info * mi;
948 typedef const uschar * (*fn_t)(gstring *, BOOL);
949 if ((mi = misc_mod_findonly(US"arc")))
950 (((fn_t *) mi->functions)[ARC_HEADER_FEED])
951 (g, !(ctx->flags & PDKIM_MODE_SIGN));
955 if (++ctx->num_headers > PDKIM_MAX_HEADERS) goto BAIL;
957 /* SIGNING -------------------------------------------------------------- */
958 if (ctx->flags & PDKIM_MODE_SIGN)
959 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next) /* Traverse all signatures */
961 /* Add header to the signed headers list (in reverse order) */
962 sig->headers = pdkim_prepend_stringlist(sig->headers, g->s);
964 /* VERIFICATION ----------------------------------------------------------- */
965 /* DKIM-Signature: headers are added to the verification list */
969 DEBUG(D_acl) debug_printf("DKIM >> raw hdr: %.*Z\n",
970 ctx->cur_head->ptr, CUS g->s);
972 if (strncasecmp(CCS g->s,
973 DKIM_SIGNATURE_HEADERNAME,
974 Ustrlen(DKIM_SIGNATURE_HEADERNAME)) == 0)
976 pdkim_signature * sig, * last_sig;
977 /* Create and chain new signature block. We could error-check for all
978 required tags here, but prefer to create the internal sig and expicitly
979 fail verification of it later. */
981 DEBUG(D_acl) debug_printf(
982 "DKIM >> Found sig, trying to parse >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
984 sig = pdkim_parse_sig_header(ctx, g->s);
986 if (!(last_sig = ctx->sig))
990 while (last_sig->next) last_sig = last_sig->next;
991 last_sig->next = sig;
994 if (dkim_collect_input && --dkim_collect_input == 0)
996 ctx->headers = pdkim_prepend_stringlist(ctx->headers, g->s);
997 g->s[g->ptr = 0] = '\0';
998 return PDKIM_ERR_EXCESS_SIGS;
1002 /* all headers are stored for signature verification */
1003 ctx->headers = pdkim_prepend_stringlist(ctx->headers, g->s);
1007 g->s[g->ptr = 0] = '\0'; /* leave buffer for reuse */
1013 /* -------------------------------------------------------------------------- */
1014 #define HEADER_BUFFER_FRAG_SIZE 256
1017 pdkim_feed(pdkim_ctx * ctx, const uschar * data, unsigned len)
1019 /* Alternate EOD signal, used in non-dotstuffing mode */
1021 pdkim_body_complete(ctx);
1023 else for (unsigned p = 0; p < len; p++)
1028 if (ctx->flags & PDKIM_PAST_HDRS)
1030 if (c == '\n' && !(ctx->flags & PDKIM_SEEN_CR)) /* emulate the CR */
1032 ctx->linebuf[ctx->linebuf_offset++] = '\r';
1033 if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1034 return PDKIM_ERR_LONG_LINE;
1037 /* Processing body byte */
1038 ctx->linebuf[ctx->linebuf_offset++] = c;
1040 ctx->flags |= PDKIM_SEEN_CR;
1043 ctx->flags &= ~PDKIM_SEEN_CR;
1044 pdkim_bodyline_complete(ctx);
1047 if (ctx->linebuf_offset == PDKIM_MAX_BODY_LINE_LEN-1)
1048 return PDKIM_ERR_LONG_LINE;
1052 /* Processing header byte */
1054 ctx->flags |= PDKIM_SEEN_CR;
1057 if (!(ctx->flags & PDKIM_SEEN_CR)) /* emulate the CR */
1058 ctx->cur_header = string_catn(ctx->cur_header, CUS "\r", 1);
1060 if (ctx->flags & PDKIM_SEEN_LF) /* Seen last header line */
1062 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1065 ctx->flags = (ctx->flags & ~(PDKIM_SEEN_LF|PDKIM_SEEN_CR)) | PDKIM_PAST_HDRS;
1066 DEBUG(D_acl) debug_printf(
1067 "DKIM >> Body data for hash, canonicalized >>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1071 ctx->flags = (ctx->flags & ~PDKIM_SEEN_CR) | PDKIM_SEEN_LF;
1073 else if (ctx->flags & PDKIM_SEEN_LF)
1075 if (!(c == '\t' || c == ' ')) /* End of header */
1076 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1078 ctx->flags &= ~PDKIM_SEEN_LF;
1081 if (!ctx->cur_header || ctx->cur_header->ptr < PDKIM_MAX_HEADER_LEN)
1082 ctx->cur_header = string_catn(ctx->cur_header, CUS &data[p], 1);
1090 /* Extend a growing header with a continuation-linebreak */
1092 pdkim_hdr_cont(gstring * str, int * col)
1095 return string_catn(str, US"\r\n\t", 3);
1101 * RFC 5322 specifies that header line length SHOULD be no more than 78
1104 * Returns gstring (not nul-terminated) appending to one supplied
1106 * col: this int holds and receives column number (octets since last '\n')
1107 * str: partial string to append to
1108 * pad: padding, split line or space after before or after eg: ";".
1109 * Only the initial charater is used.
1110 * intro: - must join to payload eg "h=", usually the tag name
1111 * payload: eg base64 data - long data can be split arbitrarily.
1113 * this code doesn't fold the header in some of the places that RFC4871
1114 * allows: As per RFC5322(2.2.3) it only folds before or after tag-value
1115 * pairs and inside long values. it also always spaces or breaks after the
1118 * No guarantees are made for output given out-of range input. like tag
1119 * names longer than 78, or bogus col. Input is assumed to be free of line breaks.
1123 pdkim_headcat(int * col, gstring * str,
1124 const uschar * pad, const uschar * intro, const uschar * payload)
1126 int len, chomp, padded = 0;
1128 /* If we can fit at least the pad at the end of current line, do it now.
1129 Otherwise, wrap if there is a pad. */
1134 str = string_catn(str, pad, 1);
1140 str = pdkim_hdr_cont(str, col);
1142 /* Special case: if the whole addition does not fit at the end of the current
1143 line, but could fit on a new line, wrap to give it its full, dedicated line. */
1145 len = (pad ? 2 : padded)
1146 + (intro ? Ustrlen(intro) : 0)
1147 + (payload ? Ustrlen(payload) : 0);
1148 if (len <= 77 && *col+len > 78)
1150 str = pdkim_hdr_cont(str, col);
1154 /* Either we already dealt with the pad or we know there is room */
1158 str = string_catn(str, pad, 1);
1159 str = string_catn(str, US" ", 1);
1162 else if (padded && *col < 78)
1164 str = string_catn(str, US" ", 1);
1168 /* Call recursively with intro as payload: it gets the same, special treatment
1169 (that is, not split if < 78). */
1172 str = pdkim_headcat(col, str, NULL, NULL, intro);
1175 for (len = Ustrlen(payload); len; len -= chomp)
1178 str = pdkim_hdr_cont(str, col);
1179 chomp = *col+len > 78 ? 78 - *col : len;
1180 str = string_catn(str, payload, chomp);
1189 /* -------------------------------------------------------------------------- */
1191 /* Signing: create signature header
1194 pdkim_create_header(pdkim_signature * sig, BOOL final)
1200 gstring * canon_all;
1202 canon_all = string_cat (NULL, pdkim_canons[sig->canon_headers]);
1203 canon_all = string_catn(canon_all, US"/", 1);
1204 canon_all = string_cat (canon_all, pdkim_canons[sig->canon_body]);
1205 (void) string_from_gstring(canon_all);
1207 hdr = string_cat(NULL, US"DKIM-Signature: v="PDKIM_SIGNATURE_VERSION);
1210 /* Required and static bits */
1211 hdr = pdkim_headcat(&col, hdr, US";", US"a=", dkim_sig_to_a_tag(sig));
1212 hdr = pdkim_headcat(&col, hdr, US";", US"q=", pdkim_querymethods[sig->querymethod]);
1213 hdr = pdkim_headcat(&col, hdr, US";", US"c=", canon_all->s);
1214 hdr = pdkim_headcat(&col, hdr, US";", US"d=", sig->domain);
1215 hdr = pdkim_headcat(&col, hdr, US";", US"s=", sig->selector);
1217 /* list of header names can be split between items. */
1219 uschar * n = string_copy(sig->headernames);
1220 uschar * i = US"h=";
1225 uschar * c = Ustrchr(n, ':');
1230 hdr = pdkim_headcat(&col, hdr, NULL, NULL, US":");
1232 hdr = pdkim_headcat(&col, hdr, s, i, n);
1243 base64_bh = pdkim_encode_base64(&sig->calc_body_hash->bh);
1244 hdr = pdkim_headcat(&col, hdr, US";", US"bh=", base64_bh);
1248 hdr = pdkim_headcat(&col, hdr, US";", US"i=", sig->identity);
1250 if (sig->created > 0)
1254 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->created);
1255 hdr = pdkim_headcat(&col, hdr, US";", US"t=", minibuf);
1258 if (sig->expires > 0)
1262 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->expires);
1263 hdr = pdkim_headcat(&col, hdr, US";", US"x=", minibuf);
1266 if (sig->bodylength >= 0)
1270 snprintf(CS minibuf, sizeof(minibuf), "%lu", sig->bodylength);
1271 hdr = pdkim_headcat(&col, hdr, US";", US"l=", minibuf);
1274 /* Preliminary or final version? */
1277 base64_b = pdkim_encode_base64(&sig->sighash);
1278 hdr = pdkim_headcat(&col, hdr, US";", US"b=", base64_b);
1280 /* add trailing semicolon: I'm not sure if this is actually needed */
1281 hdr = pdkim_headcat(&col, hdr, NULL, US";", US"");
1285 /* To satisfy the rule "all surrounding whitespace [...] deleted"
1286 ( RFC 6376 section 3.7 ) we ensure there is no whitespace here. Otherwise
1287 the headcat routine could insert a linebreak which the relaxer would reduce
1288 to a single space preceding the terminating semicolon, resulting in an
1289 incorrect header-hash. */
1290 hdr = pdkim_headcat(&col, hdr, US";", US"b=;", US"");
1293 return string_from_gstring(hdr);
1297 /* -------------------------------------------------------------------------- */
1299 /* According to draft-ietf-dcrup-dkim-crypto-07 "keys are 256 bits" (referring
1300 to DNS, hence the pubkey). Check for more than 32 bytes; if so assume the
1301 alternate possible representation (still) being discussed: a
1302 SubjectPublickeyInfo wrapped key - and drop all but the trailing 32-bytes (it
1303 should be a DER, with exactly 12 leading bytes - but we could accept a BER also,
1304 which could be any size). We still rely on the crypto library for checking for
1307 When the RFC is published this should be re-addressed. */
1310 check_bare_ed25519_pubkey(pdkim_pubkey * p)
1312 int excess = p->key.len - 32;
1316 debug_printf("DKIM: unexpected pubkey len %lu\n", (unsigned long) p->key.len);
1317 p->key.data += excess; p->key.len = 32;
1322 static pdkim_pubkey *
1323 pdkim_key_from_dns(pdkim_ctx * ctx, pdkim_signature * sig, ev_ctx * vctx,
1324 const uschar ** errstr)
1326 uschar * dns_txt_name, * dns_txt_reply;
1329 /* Fetch public key for signing domain, from DNS */
1331 dns_txt_name = string_sprintf("%s._domainkey.%s.", sig->selector, sig->domain);
1333 if ( !(dns_txt_reply = ctx->dns_txt_callback(dns_txt_name))
1334 || dns_txt_reply[0] == '\0'
1337 sig->verify_status = PDKIM_VERIFY_INVALID;
1338 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE;
1345 "DKIM >> Parsing public key record >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"
1347 " Raw record: %Z\n",
1352 if ( !(p = pdkim_parse_pubkey_record(CUS dns_txt_reply))
1353 || (Ustrcmp(p->srvtype, "*") != 0 && Ustrcmp(p->srvtype, "email") != 0)
1356 sig->verify_status = PDKIM_VERIFY_INVALID;
1357 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_DNSRECORD;
1362 debug_printf(" Invalid public key service type '%s'\n", p->srvtype);
1364 debug_printf(" Error while parsing public key record\n");
1366 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1371 DEBUG(D_acl) debug_printf(
1372 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1374 /* Import public key */
1376 /* Normally we use the signature a= tag to tell us the pubkey format.
1377 When signing under debug we do a test-import of the pubkey, and at that
1378 time we do not have a signature so we must interpret the pubkey k= tag
1379 instead. Assume writing on the sig is ok in that case. */
1381 if (sig->keytype < 0)
1382 if ((sig->keytype = pdkim_keyname_to_keytype(p->keytype)) < 0)
1384 DEBUG(D_acl) debug_printf("verify_init: unhandled keytype %s\n", p->keytype);
1385 sig->verify_status = PDKIM_VERIFY_INVALID;
1386 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
1390 if (sig->keytype == KEYTYPE_ED25519)
1391 check_bare_ed25519_pubkey(p);
1393 if ((*errstr = exim_dkim_verify_init(&p->key,
1394 sig->keytype == KEYTYPE_ED25519 ? KEYFMT_ED25519_BARE : KEYFMT_DER,
1395 vctx, &sig->keybits)))
1397 DEBUG(D_acl) debug_printf("verify_init: %s\n", *errstr);
1398 sig->verify_status = PDKIM_VERIFY_INVALID;
1399 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_IMPORT;
1403 vctx->keytype = sig->keytype;
1408 /* -------------------------------------------------------------------------- */
1409 /* Sort and filter the sigs developed from the message */
1411 static pdkim_signature *
1412 sort_sig_methods(pdkim_signature * siglist)
1414 pdkim_signature * yield, ** ss;
1415 const uschar * prefs;
1419 if (!siglist) return NULL;
1421 /* first select in order of hashtypes */
1422 DEBUG(D_acl) debug_printf("DKIM: dkim_verify_hashes '%s'\n", dkim_verify_hashes);
1423 for (prefs = dkim_verify_hashes, sep = 0, yield = NULL, ss = &yield;
1424 ele = string_nextinlist(&prefs, &sep, NULL, 0); )
1426 int i = pdkim_hashname_to_hashtype(CUS ele, 0);
1427 for (pdkim_signature * s = siglist, * next, ** prev = &siglist; s;
1431 if (s->hashtype == i)
1432 { *prev = next; s->next = NULL; *ss = s; ss = &s->next; }
1438 /* then in order of keytypes */
1440 DEBUG(D_acl) debug_printf("DKIM: dkim_verify_keytypes '%s'\n", dkim_verify_keytypes);
1441 for (prefs = dkim_verify_keytypes, sep = 0, yield = NULL, ss = &yield;
1442 ele = string_nextinlist(&prefs, &sep, NULL, 0); )
1444 int i = pdkim_keyname_to_keytype(CUS ele);
1445 for (pdkim_signature * s = siglist, * next, ** prev = &siglist; s;
1449 if (s->keytype == i)
1450 { *prev = next; s->next = NULL; *ss = s; ss = &s->next; }
1456 DEBUG(D_acl) for (pdkim_signature * s = yield; s; s = s->next)
1457 debug_printf(" retain d=%s s=%s a=%s\n",
1458 s->domain, s->selector, dkim_sig_to_a_tag(s));
1463 /* -------------------------------------------------------------------------- */
1466 pdkim_feed_finish(pdkim_ctx * ctx, pdkim_signature ** return_signatures,
1467 const uschar ** err)
1469 BOOL verify_pass = FALSE;
1471 /* Check if we must still flush a (partial) header. If that is the
1472 case, the message has no body, and we must compute a body hash
1473 out of '<CR><LF>' */
1474 if (ctx->cur_header && ctx->cur_header->ptr > 0)
1479 if ((rc = pdkim_header_complete(ctx)) != PDKIM_OK)
1482 for (pdkim_bodyhash * b = ctx->bodyhash; b; b = b->next)
1483 rnl = pdkim_update_ctx_bodyhash(b, &lineending, rnl);
1484 if (rnl) store_free(rnl);
1487 DEBUG(D_acl) debug_printf(
1488 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1490 /* Build (and/or evaluate) body hash. Do this even if no DKIM sigs, in case we
1491 have a hash to do for ARC. */
1493 pdkim_finish_bodyhash(ctx);
1495 /* Sort and filter the recived signatures */
1497 if (!(ctx->flags & PDKIM_MODE_SIGN))
1498 ctx->sig = sort_sig_methods(ctx->sig);
1502 DEBUG(D_acl) debug_printf("DKIM: no signatures\n");
1503 *return_signatures = NULL;
1507 for (pdkim_signature * sig = ctx->sig; sig; sig = sig->next)
1510 uschar * sig_hdr = US"";
1512 gstring * hdata = NULL;
1515 if ( !(ctx->flags & PDKIM_MODE_SIGN)
1516 && sig->verify_status == PDKIM_VERIFY_FAIL)
1519 debug_printf("DKIM: [%s] abandoning this signature\n", sig->domain);
1523 /*XXX The hash of the headers is needed for GCrypt (for which we can do RSA
1524 signing only, as it happens) and for either GnuTLS and OpenSSL when we are
1525 signing with EC (specifically, Ed25519). The former is because the GCrypt
1526 signing operation is pure (does not do its own hash) so we must hash. The
1527 latter is because we (stupidly, but this is what the IETF draft is saying)
1528 must hash with the declared hash method, then pass the result to the library
1529 hash-and-sign routine (because that's all the libraries are providing. And
1530 we're stuck with whatever that hidden hash method is, too). We may as well
1531 do this hash incrementally.
1532 We don't need the hash we're calculating here for the GnuTLS and OpenSSL
1533 cases of RSA signing, since those library routines can do hash-and-sign.
1535 Some time in the future we could easily avoid doing the hash here for those
1536 cases (which will be common for a long while. We could also change from
1537 the current copy-all-the-headers-into-one-block, then call the hash-and-sign
1538 implementation - to a proper incremental one. Unfortunately, GnuTLS just
1539 cannot do incremental - either signing or verification. Unsure about GCrypt.
1542 /*XXX The header hash is also used (so far) by the verify operation */
1544 if (!exim_sha_init(&hhash_ctx, pdkim_hashes[sig->hashtype].exim_hashmethod))
1546 log_write(0, LOG_MAIN|LOG_PANIC,
1547 "DKIM: hash setup error, possibly nonhandled hashtype");
1551 if (ctx->flags & PDKIM_MODE_SIGN)
1552 DEBUG(D_acl) debug_printf(
1553 "DKIM >> Headers to be signed: >>>>>>>>>>>>\n"
1557 DEBUG(D_acl) debug_printf(
1558 "DKIM >> Header data for hash, canonicalized (%-7s), in sequence >>\n",
1559 pdkim_canons[sig->canon_headers]);
1562 /* SIGNING ---------------------------------------------------------------- */
1563 /* When signing, walk through our header list and add them to the hash. As we
1564 go, construct a list of the header's names to use for the h= parameter.
1565 Then append to that list any remaining header names for which there was no
1568 if (ctx->flags & PDKIM_MODE_SIGN)
1575 /* Import private key, including the keytype which we need for building
1576 the signature header */
1578 if ((*err = exim_dkim_signing_init(CUS sig->privkey, &sctx)))
1580 log_write(0, LOG_MAIN|LOG_PANIC, "signing_init: %s", *err);
1581 return PDKIM_ERR_RSA_PRIVKEY;
1583 sig->keytype = sctx.keytype;
1585 sig->headernames = NULL; /* Collected signed header names */
1586 for (pdkim_stringlist * p = sig->headers; p; p = p->next)
1588 uschar * rh = p->value;
1590 if (header_name_match(rh, sig->sign_headers) == PDKIM_OK)
1592 /* Collect header names (Note: colon presence is guaranteed here) */
1593 g = string_append_listele_n(g, ':', rh, Ustrchr(rh, ':') - rh);
1595 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1596 rh = pdkim_relax_header(rh, TRUE); /* cook header for relaxed canon */
1598 /* Feed header to the hash algorithm */
1599 exim_sha_update_string(&hhash_ctx, CUS rh);
1601 /* Remember headers block for signing (when the library cannot do incremental) */
1602 /*XXX we could avoid doing this for all but the GnuTLS/RSA case */
1603 hdata = exim_dkim_data_append(hdata, rh);
1605 DEBUG(D_acl) debug_printf("%Z\n", rh);
1609 /* Any headers we wanted to sign but were not present must also be listed.
1610 Ignore elements that have been ticked-off or are marked as never-oversign. */
1612 l = sig->sign_headers;
1613 while((s = string_nextinlist(&l, &sep, NULL, 0)))
1615 if (*s == '+') /* skip oversigning marker */
1617 if (*s != '_' && *s != '=')
1618 g = string_append_listele(g, ':', s);
1620 sig->headernames = string_from_gstring(g);
1622 /* Create signature header with b= omitted */
1623 sig_hdr = pdkim_create_header(sig, FALSE);
1626 /* VERIFICATION ----------------------------------------------------------- */
1627 /* When verifying, walk through the header name list in the h= parameter and
1628 add the headers to the hash in that order. */
1631 uschar * p = sig->headernames;
1637 for (pdkim_stringlist * hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1643 if ((q = Ustrchr(p, ':')))
1646 /*XXX walk the list of headers in same order as received. */
1647 for (pdkim_stringlist * hdrs = ctx->headers; hdrs; hdrs = hdrs->next)
1649 && strncasecmp(CCS hdrs->value, CCS p, Ustrlen(p)) == 0
1650 && (hdrs->value)[Ustrlen(p)] == ':'
1653 /* cook header for relaxed canon, or just copy it for simple */
1655 uschar * rh = sig->canon_headers == PDKIM_CANON_RELAXED
1656 ? pdkim_relax_header(hdrs->value, TRUE)
1657 : string_copy(CUS hdrs->value);
1659 /* Feed header to the hash algorithm */
1660 exim_sha_update_string(&hhash_ctx, CUS rh);
1662 DEBUG(D_acl) debug_printf("%Z\n", rh);
1671 sig_hdr = string_copy(sig->rawsig_no_b_val);
1675 DEBUG(D_acl) debug_printf(
1676 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1681 "DKIM >> Signed DKIM-Signature header, pre-canonicalized >>>>>>>>>>>>>\n");
1682 debug_printf("%Z\n", CUS sig_hdr);
1684 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1687 /* Relax header if necessary */
1688 if (sig->canon_headers == PDKIM_CANON_RELAXED)
1689 sig_hdr = pdkim_relax_header(sig_hdr, FALSE);
1693 debug_printf("DKIM >> Signed DKIM-Signature header, canonicalized (%-7s) >>>>>>>\n",
1694 pdkim_canons[sig->canon_headers]);
1695 debug_printf("%Z\n", CUS sig_hdr);
1697 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1700 /* Finalize header hash */
1701 exim_sha_update_string(&hhash_ctx, CUS sig_hdr);
1702 exim_sha_finish(&hhash_ctx, &hhash);
1706 debug_printf("DKIM [%s] Header %s computed: ",
1707 sig->domain, pdkim_hashes[sig->hashtype].dkim_hashname);
1708 debug_printf("%.*H\n", hhash.len, hhash.data);
1711 /* Remember headers block for signing (when the signing library cannot do
1713 if (ctx->flags & PDKIM_MODE_SIGN)
1714 hdata = exim_dkim_data_append(hdata, US sig_hdr);
1716 /* SIGNING ---------------------------------------------------------------- */
1717 if (ctx->flags & PDKIM_MODE_SIGN)
1719 hashmethod hm = sig->keytype == KEYTYPE_ED25519
1720 #if defined(SIGN_OPENSSL)
1725 : pdkim_hashes[sig->hashtype].exim_hashmethod;
1727 #ifdef SIGN_HAVE_ED25519
1728 /* For GCrypt, and for EC, we pass the hash-of-headers to the signing
1729 routine. For anything else we just pass the headers. */
1731 if (sig->keytype != KEYTYPE_ED25519)
1734 hhash.data = hdata->s;
1735 hhash.len = hdata->ptr;
1738 if ((*err = exim_dkim_sign(&sctx, hm, &hhash, &sig->sighash)))
1740 log_write(0, LOG_MAIN|LOG_PANIC, "signing: %s", *err);
1741 return PDKIM_ERR_RSA_SIGNING;
1746 debug_printf( "DKIM [%s] b computed: ", sig->domain);
1747 debug_printf("%.*H\n", sig->sighash.len, sig->sighash.data);
1750 sig->signature_header = pdkim_create_header(sig, TRUE);
1753 /* VERIFICATION ----------------------------------------------------------- */
1759 /* Make sure we have all required signature tags */
1760 if (!( sig->domain && *sig->domain
1761 && sig->selector && *sig->selector
1762 && sig->headernames && *sig->headernames
1763 && sig->bodyhash.data
1764 && sig->sighash.data
1765 && sig->keytype >= 0
1766 && sig->hashtype >= 0
1770 sig->verify_status = PDKIM_VERIFY_INVALID;
1771 sig->verify_ext_status = PDKIM_VERIFY_INVALID_SIGNATURE_ERROR;
1773 DEBUG(D_acl) debug_printf(
1774 " Error in DKIM-Signature header: tags missing or invalid (%s)\n"
1775 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n",
1776 !(sig->domain && *sig->domain) ? "d="
1777 : !(sig->selector && *sig->selector) ? "s="
1778 : !(sig->headernames && *sig->headernames) ? "h="
1779 : !sig->bodyhash.data ? "bh="
1780 : !sig->sighash.data ? "b="
1781 : sig->keytype < 0 || sig->hashtype < 0 ? "a="
1787 /* Make sure sig uses supported DKIM version (only v1) */
1788 if (sig->version != 1)
1790 sig->verify_status = PDKIM_VERIFY_INVALID;
1791 sig->verify_ext_status = PDKIM_VERIFY_INVALID_DKIM_VERSION;
1793 DEBUG(D_acl) debug_printf(
1794 " Error in DKIM-Signature header: unsupported DKIM version\n"
1795 "DKIM <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1801 debug_printf( "DKIM [%s] b from mail: ", sig->domain);
1802 debug_printf("%.*H\n", sig->sighash.len, sig->sighash.data);
1805 if (!(sig->pubkey = pdkim_key_from_dns(ctx, sig, &vctx, err)))
1807 log_write(0, LOG_MAIN, "DKIM: %s%s %s%s [failed key import]",
1808 sig->domain ? "d=" : "", sig->domain ? sig->domain : US"",
1809 sig->selector ? "s=" : "", sig->selector ? sig->selector : US"");
1813 /* If the pubkey limits to a list of specific hashes, ignore sigs that
1814 do not have the hash part of the sig algorithm matching */
1816 if (sig->pubkey->hashes)
1818 const uschar * list = sig->pubkey->hashes, * ele;
1820 while ((ele = string_nextinlist(&list, &sep, NULL, 0)))
1821 if (Ustrcmp(ele, pdkim_hashes[sig->hashtype].dkim_hashname) == 0) break;
1824 DEBUG(D_acl) debug_printf("pubkey h=%s vs. sig a=%s_%s\n",
1825 sig->pubkey->hashes,
1826 pdkim_keytypes[sig->keytype],
1827 pdkim_hashes[sig->hashtype].dkim_hashname);
1828 sig->verify_status = PDKIM_VERIFY_FAIL;
1829 sig->verify_ext_status = PDKIM_VERIFY_FAIL_SIG_ALGO_MISMATCH;
1834 hm = sig->keytype == KEYTYPE_ED25519
1835 #if defined(SIGN_OPENSSL)
1840 : pdkim_hashes[sig->hashtype].exim_hashmethod;
1842 /* Check the signature */
1844 if ((*err = exim_dkim_verify(&vctx, hm, &hhash, &sig->sighash)))
1846 DEBUG(D_acl) debug_printf("headers verify: %s\n", *err);
1847 sig->verify_status = PDKIM_VERIFY_FAIL;
1848 sig->verify_ext_status = PDKIM_VERIFY_FAIL_MESSAGE;
1851 if (*dkim_verify_min_keysizes)
1854 const uschar * ss = expand_getkeyed(US pdkim_keytypes[sig->keytype],
1855 dkim_verify_min_keysizes);
1856 if (ss && (minbits = atoi(CCS ss)) > sig->keybits)
1858 DEBUG(D_acl) debug_printf("Key too short: Actual: %s %u Minima '%s'\n",
1859 pdkim_keytypes[sig->keytype], sig->keybits, dkim_verify_min_keysizes);
1860 sig->verify_status = PDKIM_VERIFY_FAIL;
1861 sig->verify_ext_status = PDKIM_VERIFY_INVALID_PUBKEY_KEYSIZE;
1866 /* We have a winner! (if bodyhash was correct earlier) */
1867 if (sig->verify_status == PDKIM_VERIFY_NONE)
1869 sig->verify_status = PDKIM_VERIFY_PASS;
1871 /*XXX We used to "break" here if dkim_verify_minimal, but that didn't
1872 stop the ACL being called. So move that test. Unfortunately, we
1873 need to eval all the sigs here only to possibly ignore some later,
1874 because we don't know what verify options might say.
1875 Could we change to a later eval of the sig?
1876 Both bits are called from receive_msg().
1877 Moving the test is also suboptimal for the case of no ACL (or no
1878 signers to check!) so keep it for that case, but after debug output */
1884 debug_printf("DKIM [%s] %s signature status: %s",
1885 sig->domain, dkim_sig_to_a_tag(sig),
1886 pdkim_verify_status_str(sig->verify_status));
1887 if (sig->verify_ext_status > 0)
1888 debug_printf(" (%s)\n",
1889 pdkim_verify_ext_status_str(sig->verify_ext_status));
1894 if ( verify_pass && dkim_verify_minimal
1895 && !(acl_smtp_dkim && dkim_verify_signers && *dkim_verify_signers))
1900 /* If requested, set return pointer to signature(s) */
1901 if (return_signatures)
1902 *return_signatures = ctx->sig;
1904 return ctx->flags & PDKIM_MODE_SIGN || verify_pass
1905 ? PDKIM_OK : PDKIM_FAIL;
1909 /* -------------------------------------------------------------------------- */
1911 DLLEXPORT pdkim_ctx *
1912 pdkim_init_verify(uschar * (*dns_txt_callback)(const uschar *), BOOL dot_stuffing)
1916 ctx = store_get(sizeof(pdkim_ctx), GET_UNTAINTED);
1917 memset(ctx, 0, sizeof(pdkim_ctx));
1919 if (dot_stuffing) ctx->flags = PDKIM_DOT_TERM;
1920 /* The line-buffer is for message data, hence tainted */
1921 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN, GET_TAINTED);
1922 ctx->dns_txt_callback = dns_txt_callback;
1923 ctx->cur_header = string_get_tainted(36, GET_TAINTED);
1929 /* -------------------------------------------------------------------------- */
1931 DLLEXPORT pdkim_signature *
1932 pdkim_init_sign(pdkim_ctx * ctx,
1933 uschar * domain, uschar * selector, uschar * privkey,
1934 uschar * hashname, const uschar ** errstr)
1937 pdkim_signature * sig;
1939 if (!domain || !selector || !privkey)
1942 /* Allocate & init one signature struct */
1944 sig = store_get(sizeof(pdkim_signature), GET_UNTAINTED);
1945 memset(sig, 0, sizeof(pdkim_signature));
1947 sig->bodylength = -1;
1949 sig->domain = string_copy(US domain);
1950 sig->selector = string_copy(US selector);
1951 sig->privkey = string_copy(US privkey);
1954 for (hashtype = 0; hashtype < nelem(pdkim_hashes); hashtype++)
1955 if (Ustrcmp(hashname, pdkim_hashes[hashtype].dkim_hashname) == 0)
1956 { sig->hashtype = hashtype; break; }
1957 if (hashtype >= nelem(pdkim_hashes))
1959 log_write(0, LOG_MAIN|LOG_PANIC,
1960 "DKIM: unrecognised hashname '%s'", hashname);
1966 pdkim_signature s = *sig;
1969 debug_printf("DKIM (checking verify key)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
1970 if (!pdkim_key_from_dns(ctx, &s, &vctx, errstr))
1971 debug_printf("WARNING: bad dkim key in dns\n");
1972 debug_printf("DKIM (finished checking verify key)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
1978 /* -------------------------------------------------------------------------- */
1981 pdkim_set_optional(pdkim_signature * sig,
1982 char * sign_headers,
1987 unsigned long created,
1988 unsigned long expires)
1991 sig->identity = string_copy(US identity);
1993 sig->sign_headers = string_copy(sign_headers
1994 ? US sign_headers : US PDKIM_DEFAULT_SIGN_HEADERS);
1996 sig->canon_headers = canon_headers;
1997 sig->canon_body = canon_body;
1998 sig->bodylength = bodylength;
1999 sig->created = created;
2000 sig->expires = expires;
2007 /* Set up a blob for calculating the bodyhash according to the
2008 given needs. Use an existing one if possible, or create a new one.
2010 Return: hashblob pointer, or NULL on error
2013 pdkim_set_bodyhash(pdkim_ctx * ctx, int hashtype, int canon_method,
2018 if (hashtype == -1 || canon_method == -1) return NULL;
2022 DEBUG(D_receive) debug_printf("pdkim_set_bodyhash: null context\n");
2026 for (b = ctx->bodyhash; b; b = b->next)
2027 if ( hashtype == b->hashtype
2028 && canon_method == b->canon_method
2029 && bodylength == b->bodylength)
2031 DEBUG(D_receive) debug_printf("DKIM: using existing bodyhash %s/%s/%ld\n",
2032 pdkim_hashes[hashtype].dkim_hashname, pdkim_canons[canon_method], bodylength);
2036 DEBUG(D_receive) debug_printf("DKIM: new bodyhash %s/%s/%ld\n",
2037 pdkim_hashes[hashtype].dkim_hashname, pdkim_canons[canon_method], bodylength);
2038 b = store_get(sizeof(pdkim_bodyhash), GET_UNTAINTED);
2039 b->next = ctx->bodyhash;
2040 b->hashtype = hashtype;
2041 b->canon_method = canon_method;
2042 b->bodylength = bodylength;
2043 if (!exim_sha_init(&b->body_hash_ctx, /*XXX hash method: extend for sha512 */
2044 pdkim_hashes[hashtype].exim_hashmethod))
2047 debug_printf("DKIM: hash init error, possibly nonhandled hashtype\n");
2050 b->signed_body_bytes = 0;
2051 b->num_buffered_blanklines = 0;
2057 /* Set up a blob for calculating the bodyhash according to the
2058 needs of this signature. Use an existing one if possible, or
2061 Return: hashblob pointer, or NULL on error (only used as a boolean).
2064 pdkim_set_sig_bodyhash(pdkim_ctx * ctx, pdkim_signature * sig)
2066 pdkim_bodyhash * b = pdkim_set_bodyhash(ctx,
2067 sig->hashtype, sig->canon_body, sig->bodylength);
2068 sig->calc_body_hash = b;
2073 /* -------------------------------------------------------------------------- */
2077 pdkim_init_context(pdkim_ctx * ctx, BOOL dot_stuffed,
2078 uschar * (*dns_txt_callback)(const uschar *))
2080 memset(ctx, 0, sizeof(pdkim_ctx));
2081 ctx->flags = dot_stuffed ? PDKIM_MODE_SIGN | PDKIM_DOT_TERM : PDKIM_MODE_SIGN;
2082 /* The line buffer is for message data, hence tainted */
2083 ctx->linebuf = store_get(PDKIM_MAX_BODY_LINE_LEN, GET_TAINTED);
2084 DEBUG(D_acl) ctx->dns_txt_callback = dns_txt_callback;
2091 exim_dkim_signers_init();
2096 #endif /*DISABLE_DKIM*/