2 * Copyright (c) 2019 Martijn van Duren <martijn@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
19 #include <openssl/sha.h>
31 #include "openbsd-compat.h"
32 #include "opensmtpd.h"
35 struct dkim_signature {
46 size_t body_whitelines;
48 struct dkim_signature signature;
53 /* RFC 6376 section 5.4.1 */
54 static char *dsign_headers[] = {
75 static char **sign_headers = dsign_headers;
76 static size_t nsign_headers = sizeof(dsign_headers) / sizeof(*dsign_headers);
78 static char *hashalg = "sha256";
79 static char *cryptalg = "rsa";
81 #define CANON_SIMPLE 0
82 #define CANON_RELAXED 1
83 static int canonheader = CANON_SIMPLE;
84 static int canonbody = CANON_SIMPLE;
86 static int addtime = 0;
87 static long long addexpire = 0;
88 static int addheaders = 0;
90 static char **domain = NULL;
91 static size_t ndomains = 0;
92 static char *selector = NULL;
94 static EVP_PKEY *pkey;
95 static const EVP_MD *hash_md;
96 static int keyid = EVP_PKEY_RSA;
97 static int sephash = 0;
99 #define DKIM_SIGNATURE_LINELEN 78
102 void dkim_err(struct dkim_message *, char *);
103 void dkim_errx(struct dkim_message *, char *);
104 void dkim_headers_set(char *);
105 void dkim_dataline(struct osmtpd_ctx *, const char *);
106 void dkim_commit(struct osmtpd_ctx *);
107 void *dkim_message_new(struct osmtpd_ctx *);
108 void dkim_message_free(struct osmtpd_ctx *, void *);
109 void dkim_parse_header(struct dkim_message *, char *, int);
110 void dkim_parse_body(struct dkim_message *, char *);
111 void dkim_sign(struct osmtpd_ctx *);
112 int dkim_signature_printheader(struct dkim_message *, const char *);
113 int dkim_signature_printf(struct dkim_message *, char *, ...)
114 __attribute__((__format__ (printf, 2, 3)));
115 int dkim_signature_normalize(struct dkim_message *);
116 const char *dkim_domain_select(struct dkim_message *, char *);
117 int dkim_signature_need(struct dkim_message *, size_t);
118 int dkim_sign_init(struct dkim_message *);
121 main(int argc, char *argv[])
127 while ((ch = getopt(argc, argv, "a:c:d:h:k:s:tx:z")) != -1) {
130 if (strncmp(optarg, "rsa-", 4) == 0) {
132 hashalg = optarg + 4;
133 keyid = EVP_PKEY_RSA;
136 } else if (strncmp(optarg, "ed25519-", 8) == 0) {
137 hashalg = optarg + 8;
138 cryptalg = "ed25519";
139 keyid = EVP_PKEY_ED25519;
143 osmtpd_errx(1, "invalid algorithm");
146 if (strncmp(optarg, "simple", 6) == 0) {
147 canonheader = CANON_SIMPLE;
149 } else if (strncmp(optarg, "relaxed", 7) == 0) {
150 canonheader = CANON_RELAXED;
153 osmtpd_err(1, "Invalid canonicalization");
154 if (optarg[0] == '/') {
155 if (strcmp(optarg + 1, "simple") == 0)
156 canonbody = CANON_SIMPLE;
157 else if (strcmp(optarg + 1, "relaxed") == 0)
158 canonbody = CANON_RELAXED;
161 "Invalid canonicalization");
162 } else if (optarg[0] == '\0')
163 canonbody = CANON_SIMPLE;
165 osmtpd_err(1, "Invalid canonicalization");
168 if ((domain = reallocarray(domain, ndomains + 1,
169 sizeof(*domain))) == NULL)
170 osmtpd_err(1, "malloc");
171 domain[ndomains++] = optarg;
174 dkim_headers_set(optarg);
177 if ((keyfile = fopen(optarg, "r")) == NULL)
178 osmtpd_err(1, "Can't open key file (%s)",
180 pkey = PEM_read_PrivateKey(keyfile, NULL, NULL, NULL);
182 osmtpd_errx(1, "Can't read key file");
192 addexpire = strtonum(optarg, 1, INT64_MAX, &errstr);
194 osmtpd_errx(1, "Expire offset is %s", errstr);
204 OpenSSL_add_all_digests();
206 if (pledge("tmppath stdio", NULL) == -1)
207 osmtpd_err(1, "pledge");
209 if ((hash_md = EVP_get_digestbyname(hashalg)) == NULL)
210 osmtpd_errx(1, "Can't find hash: %s", hashalg);
212 if (domain == NULL || selector == NULL || pkey == NULL)
215 if (EVP_PKEY_id(pkey) != keyid)
216 osmtpd_errx(1, "Key is not of type %s", cryptalg);
218 osmtpd_register_filter_dataline(dkim_dataline);
219 osmtpd_register_filter_commit(dkim_commit);
220 osmtpd_local_message(dkim_message_new, dkim_message_free);
227 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
229 struct dkim_message *message = ctx->local_message;
234 if (line[0] == '.' && line[1] =='\0')
235 osmtpd_filter_dataline(ctx, ".");
239 linelen = strlen(line);
240 if (fprintf(message->origf, "%s\n", line) < (int) linelen)
241 dkim_errx(message, "Couldn't write to tempfile");
243 if (line[0] == '.' && line[1] =='\0') {
245 } else if (linelen != 0 && message->parsing_headers) {
248 if ((linedup = strdup(line)) == NULL)
249 osmtpd_err(1, "strdup");
250 dkim_parse_header(message, linedup, 0);
252 } else if (linelen == 0 && message->parsing_headers) {
253 if (addheaders > 0 && !dkim_signature_printf(message, "; "))
255 message->parsing_headers = 0;
259 if ((linedup = strdup(line)) == NULL)
260 osmtpd_err(1, "strdup");
261 dkim_parse_body(message, linedup);
267 dkim_commit(struct osmtpd_ctx *ctx)
269 struct dkim_message *message = ctx->local_message;
272 osmtpd_filter_disconnect(ctx, "Internal server error");
274 osmtpd_filter_proceed(ctx);
278 dkim_message_new(struct osmtpd_ctx *ctx)
280 struct dkim_message *message;
282 if ((message = calloc(1, sizeof(*message))) == NULL) {
283 dkim_err(message, "Failed to create message context");
287 if ((message->origf = tmpfile()) == NULL) {
288 dkim_err(message, "Failed to open tempfile");
291 message->parsing_headers = 1;
293 message->body_whitelines = 0;
294 message->headers = calloc(1, sizeof(*(message->headers)));
295 if (message->headers == NULL) {
296 dkim_err(message, "Can't save headers");
299 message->lastheader = 0;
300 message->signature.signature = NULL;
301 message->signature.size = 0;
302 message->signature.len = 0;
305 if (!dkim_signature_printf(message,
306 "DKIM-Signature: v=%s; a=%s-%s; c=%s/%s; s=%s; ", "1",
308 canonheader == CANON_SIMPLE ? "simple" : "relaxed",
309 canonbody == CANON_SIMPLE ? "simple" : "relaxed", selector))
311 if (addheaders > 0 && !dkim_signature_printf(message, "z="))
314 if ((message->dctx = EVP_MD_CTX_new()) == NULL) {
315 dkim_errx(message, "Failed to create hash context");
318 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) <= 0) {
319 dkim_errx(message, "Failed to initialize hash context");
324 free(message->headers);
325 EVP_MD_CTX_free(message->dctx);
331 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
333 struct dkim_message *message = data;
336 fclose(message->origf);
337 EVP_MD_CTX_free(message->dctx);
338 free(message->signature.signature);
339 for (i = 0; message->headers[i] != NULL; i++)
340 free(message->headers[i]);
341 free(message->headers);
346 dkim_headers_set(char *headers)
353 for (i = 0; headers[i] != '\0'; i++) {
354 /* RFC 5322 field-name */
355 if (!(headers[i] >= 33 && headers[i] <= 126))
356 osmtpd_errx(1, "-h: invalid character");
357 if (headers[i] == ':') {
358 /* Test for empty headers */
359 if (i == 0 || headers[i - 1] == ':')
360 osmtpd_errx(1, "-h: header can't be empty");
363 headers[i] = tolower(headers[i]);
365 if (headers[i - 1] == ':')
366 osmtpd_errx(1, "-h: header can't be empty");
368 if ((sign_headers = reallocarray(NULL, nsign_headers + 1,
369 sizeof(*sign_headers))) == NULL)
370 osmtpd_errx(1, NULL);
372 for (i = 0; i < nsign_headers; i++) {
373 sign_headers[i] = headers;
374 if (i != nsign_headers - 1) {
375 headers = strchr(headers, ':');
378 if (strcasecmp(sign_headers[i], "from") == 0)
382 osmtpd_errx(1, "From header must be included");
386 dkim_err(struct dkim_message *message, char *msg)
389 fprintf(stderr, "%s: %s\n", msg, strerror(errno));
393 dkim_errx(struct dkim_message *message, char *msg)
396 fprintf(stderr, "%s\n", msg);
400 dkim_parse_header(struct dkim_message *message, char *line, int force)
412 if (addheaders == 2 && !force &&
413 !dkim_signature_printheader(message, line))
416 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
418 if ((line[0] != ' ' && line[0] != '\t')) {
419 message->lastheader = 0;
420 for (i = 0; i < nsign_headers; i++) {
421 hlen = strlen(sign_headers[i]);
422 if (strncasecmp(line, sign_headers[i], hlen) == 0) {
423 while (line[hlen] == ' ' || line[hlen] == '\t')
425 if (line[hlen] != ':')
430 if (i == nsign_headers && !force)
434 if (addheaders == 1 && !force &&
435 !dkim_signature_printheader(message, line))
438 if (canonheader == CANON_RELAXED) {
439 if (!message->lastheader)
441 for (r = w = 0; line[r] != '\0'; r++) {
442 if (line[r] == ':' && fieldname) {
443 if (w > 0 && line[w - 1] == ' ')
448 while (line[r + 1] == ' ' ||
453 if (line[r] == ' ' || line[r] == '\t' ||
454 line[r] == '\r' || line[r] == '\n') {
455 if (r != 0 && w != 0 && line[w - 1] == ' ')
459 } else if (fieldname) {
460 line[w++] = tolower(line[r]);
465 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
466 line[linelen] = '\0';
468 linelen = strlen(line);
470 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
472 if (!message->lastheader) {
473 mtmp = recallocarray(message->headers, lastheader + 1,
474 lastheader + 2, sizeof(*mtmp));
476 dkim_err(message, "Can't store header");
479 message->headers = mtmp;
481 message->headers[lastheader] = strdup(line);
482 message->headers[lastheader + 1 ] = NULL;
483 message->lastheader = 1;
486 linelen += strlen(message->headers[lastheader]);
487 if (canonheader == CANON_SIMPLE)
490 htmp = reallocarray(message->headers[lastheader], linelen,
493 dkim_err(message, "Can't store header");
496 message->headers[lastheader] = htmp;
497 if (canonheader == CANON_SIMPLE) {
498 if (strlcat(htmp, "\r\n", linelen) >= linelen)
499 osmtpd_errx(1, "Missized header");
500 } else if (canonheader == CANON_RELAXED &&
501 (tmp = strchr(message->headers[lastheader], ':')) != NULL &&
505 if (strlcat(htmp, line, linelen) >= linelen)
506 osmtpd_errx(1, "Missized header");
511 dkim_parse_body(struct dkim_message *message, char *line)
516 if (canonbody == CANON_RELAXED) {
517 for (r = w = 0; line[r] != '\0'; r++) {
518 if (line[r] == ' ' || line[r] == '\t') {
519 if (r != 0 && line[w - 1] == ' ')
526 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
527 line[linelen] = '\0';
529 linelen = strlen(line);
531 if (line[0] == '\0') {
532 message->body_whitelines++;
536 while (message->body_whitelines--) {
537 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
538 dkim_errx(message, "Can't update hash context");
542 message->body_whitelines = 0;
543 message->has_body = 1;
545 if (EVP_DigestUpdate(message->dctx, line, linelen) == 0 ||
546 EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
547 dkim_errx(message, "Can't update hash context");
553 dkim_sign(struct osmtpd_ctx *ctx)
555 struct dkim_message *message = ctx->local_message;
556 /* Use largest hash size here */
557 char bdigest[EVP_MAX_MD_SIZE];
558 char digest[(((sizeof(bdigest) + 2) / 3) * 4) + 1];
560 const char *sdomain = domain[0], *tsdomain;
567 if (addtime || addexpire)
569 if (addtime && !dkim_signature_printf(message, "t=%lld; ",
572 if (addexpire != 0 && !dkim_signature_printf(message, "x=%lld; ",
573 now + addexpire < now ? INT64_MAX : now + addexpire))
576 if (canonbody == CANON_SIMPLE && !message->has_body) {
577 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
578 dkim_errx(message, "Can't update hash context");
582 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0) {
583 dkim_errx(message, "Can't finalize hash context");
586 EVP_EncodeBlock(digest, bdigest, digestsz);
587 if (!dkim_signature_printf(message, "bh=%s; h=", digest))
589 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
590 for (i = 0; message->headers[i] != NULL; i++)
592 EVP_MD_CTX_reset(message->dctx);
594 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
596 dkim_errx(message, "Failed to initialize signature "
601 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1) {
602 dkim_errx(message, "Failed to initialize hash context");
606 for (i--; i >= 0; i--) {
608 if (EVP_DigestSignUpdate(message->dctx,
610 strlen(message->headers[i])) != 1 ||
611 EVP_DigestSignUpdate(message->dctx, "\r\n",
613 dkim_errx(message, "Failed to update signature "
618 if (EVP_DigestUpdate(message->dctx, message->headers[i],
619 strlen(message->headers[i])) != 1 ||
620 EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
621 dkim_errx(message, "Failed to update digest "
626 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
628 /* We're done with the cached header after hashing */
629 for (tmp = message->headers[i]; tmp[0] != ':'; tmp++) {
630 if (tmp[0] == ' ' || tmp[0] == '\t')
632 tmp[0] = tolower(tmp[0]);
635 if (!dkim_signature_printf(message, "%s%s",
636 message->headers[i + 1] == NULL ? "" : ":",
637 message->headers[i]))
640 dkim_signature_printf(message, "; d=%s; b=", sdomain);
641 if (!dkim_signature_normalize(message))
643 if ((tmp = strdup(message->signature.signature)) == NULL) {
644 dkim_err(message, "Can't create DKIM signature");
647 dkim_parse_header(message, tmp, 1);
649 if (EVP_DigestSignUpdate(message->dctx, tmp,
651 dkim_errx(message, "Failed to update signature "
656 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1) {
657 dkim_errx(message, "Failed to update digest context");
663 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1) {
664 dkim_errx(message, "Can't finalize signature context");
669 if (EVP_DigestFinal_ex(message->dctx, bdigest,
671 dkim_errx(message, "Can't finalize hash context");
674 EVP_MD_CTX_reset(message->dctx);
675 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
677 dkim_errx(message, "Failed to initialize signature "
681 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
683 dkim_errx(message, "Failed to finalize signature");
688 if ((tmp = malloc(linelen)) == NULL) {
689 dkim_err(message, "Can't allocate space for signature");
693 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1) {
694 dkim_errx(message, "Failed to finalize signature");
699 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
701 dkim_errx(message, "Failed to finalize signature");
706 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL) {
707 dkim_err(message, "Can't create DKIM signature");
710 EVP_EncodeBlock(b, tmp, linelen);
712 dkim_signature_printf(message, "%s\r\n", b);
714 dkim_signature_normalize(message);
715 tmp = message->signature.signature;
716 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
718 osmtpd_filter_dataline(ctx, "%s", tmp);
723 rewind(message->origf);
724 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
726 osmtpd_filter_dataline(ctx, "%s", tmp);
731 osmtpd_filter_dataline(ctx, ".");
735 dkim_signature_normalize(struct dkim_message *message)
741 size_t *headerlen = &(message->signature.len);
744 char *sig = message->signature.signature;
746 for (linelen = i = 0; sig[i] != '\0'; i++) {
747 if (sig[i] == '\r' && sig[i + 1] == '\n') {
754 linelen = (linelen + 8) & ~7;
764 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
765 for (skip = checkpoint + 1;
766 sig[skip] == ' ' || sig[skip] == '\t';
769 skip -= checkpoint + 1;
770 if (!dkim_signature_need(message,
771 skip > 3 ? 0 : 3 - skip + 1))
773 sig = message->signature.signature;
775 memmove(sig + checkpoint + 3,
776 sig + checkpoint + skip,
777 *headerlen - skip - checkpoint + 1);
778 sig[checkpoint + 1] = '\r';
779 sig[checkpoint + 2] = '\n';
780 sig[checkpoint + 3] = '\t';
782 *headerlen = *headerlen + 3 - skip;
802 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
803 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
816 dkim_signature_printheader(struct dkim_message *message, const char *header)
819 static char *fmtheader = NULL;
821 static size_t size = 0;
824 len = strlen(header);
825 if ((len + 3) * 3 < len) {
827 dkim_err(message, "Can't add z-component to header");
830 if ((len + 3) * 3 > size) {
831 if ((tmp = reallocarray(fmtheader, 3, len + 3)) == NULL) {
832 dkim_err(message, "Can't add z-component to header");
836 size = (len + 1) * 3;
839 first = message->signature.signature[message->signature.len - 1] == '=';
840 for (j = i = 0; header[i] != '\0'; i++, j++) {
841 if (i == 0 && header[i] != ' ' && header[i] != '\t' && !first)
842 fmtheader[j++] = '|';
843 if ((header[i] >= 0x21 && header[i] <= 0x3A) ||
844 (header[i] == 0x3C) ||
845 (header[i] >= 0x3E && header[i] <= 0x7B) ||
846 (header[i] >= 0x7D && header[i] <= 0x7E))
847 fmtheader[j] = header[i];
849 fmtheader[j++] = '=';
850 (void) sprintf(fmtheader + j, "%02hhX", header[i]);
854 (void) sprintf(fmtheader + j, "=%02hhX=%02hhX", (unsigned char) '\r',
855 (unsigned char) '\n');
857 return dkim_signature_printf(message, "%s", fmtheader);
861 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
863 struct dkim_signature *sig = &(message->signature);
868 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
869 fmt, ap)) >= sig->size - sig->len) {
871 if (!dkim_signature_need(message, len + 1))
874 if ((len = vsnprintf(sig->signature + sig->len,
875 sig->size - sig->len, fmt, ap)) >= sig->size - sig->len)
876 osmtpd_errx(1, "Miscalculated header size");
884 dkim_domain_select(struct dkim_message *message, char *from)
886 char *mdomain0, *mdomain;
889 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL) {
890 if (errno != EINVAL) {
891 dkim_errx(message, "Couldn't parse from header");
897 while (mdomain != NULL && mdomain[0] != '\0') {
898 for (i = 0; i < ndomains; i++) {
899 if (strcasecmp(mdomain, domain[i]) == 0) {
904 if ((mdomain = strchr(mdomain, '.')) != NULL)
912 dkim_signature_need(struct dkim_message *message, size_t len)
914 struct dkim_signature *sig = &(message->signature);
917 if (sig->len + len < sig->size)
919 sig->size = (((len + sig->len) / 512) + 1) * 512;
920 if ((tmp = realloc(sig->signature, sig->size)) == NULL) {
921 dkim_err(message, "No room for signature");
924 sig->signature = tmp;
931 fprintf(stderr, "usage: filter-dkimsign [-tz] [-a signalg] "
932 "[-c canonicalization] \n [-h headerfields]"
933 "[-x seconds] -d domain -k keyfile -s selector\n");