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 dkim_message_free(ctx, message);
329 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
331 struct dkim_message *message = data;
334 fclose(message->origf);
335 EVP_MD_CTX_free(message->dctx);
336 free(message->signature.signature);
337 for (i = 0; message->headers != NULL &&
338 message->headers[i] != NULL; i++)
339 free(message->headers[i]);
340 free(message->headers);
345 dkim_headers_set(char *headers)
352 for (i = 0; headers[i] != '\0'; i++) {
353 /* RFC 5322 field-name */
354 if (!(headers[i] >= 33 && headers[i] <= 126))
355 osmtpd_errx(1, "-h: invalid character");
356 if (headers[i] == ':') {
357 /* Test for empty headers */
358 if (i == 0 || headers[i - 1] == ':')
359 osmtpd_errx(1, "-h: header can't be empty");
362 headers[i] = tolower(headers[i]);
364 if (headers[i - 1] == ':')
365 osmtpd_errx(1, "-h: header can't be empty");
367 if ((sign_headers = reallocarray(NULL, nsign_headers + 1,
368 sizeof(*sign_headers))) == NULL)
369 osmtpd_errx(1, NULL);
371 for (i = 0; i < nsign_headers; i++) {
372 sign_headers[i] = headers;
373 if (i != nsign_headers - 1) {
374 headers = strchr(headers, ':');
377 if (strcasecmp(sign_headers[i], "from") == 0)
381 osmtpd_errx(1, "From header must be included");
385 dkim_err(struct dkim_message *message, char *msg)
388 fprintf(stderr, "%s: %s\n", msg, strerror(errno));
392 dkim_errx(struct dkim_message *message, char *msg)
395 fprintf(stderr, "%s\n", msg);
399 dkim_parse_header(struct dkim_message *message, char *line, int force)
411 if (addheaders == 2 && !force &&
412 !dkim_signature_printheader(message, line))
415 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
417 if ((line[0] != ' ' && line[0] != '\t')) {
418 message->lastheader = 0;
419 for (i = 0; i < nsign_headers; i++) {
420 hlen = strlen(sign_headers[i]);
421 if (strncasecmp(line, sign_headers[i], hlen) == 0) {
422 while (line[hlen] == ' ' || line[hlen] == '\t')
424 if (line[hlen] != ':')
429 if (i == nsign_headers && !force)
433 if (addheaders == 1 && !force &&
434 !dkim_signature_printheader(message, line))
437 if (canonheader == CANON_RELAXED) {
438 if (!message->lastheader)
440 for (r = w = 0; line[r] != '\0'; r++) {
441 if (line[r] == ':' && fieldname) {
442 if (w > 0 && line[w - 1] == ' ')
447 while (line[r + 1] == ' ' ||
452 if (line[r] == ' ' || line[r] == '\t' ||
453 line[r] == '\r' || line[r] == '\n') {
454 if (r != 0 && w != 0 && line[w - 1] == ' ')
458 } else if (fieldname) {
459 line[w++] = tolower(line[r]);
464 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
465 line[linelen] = '\0';
467 linelen = strlen(line);
469 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
471 if (!message->lastheader) {
472 mtmp = recallocarray(message->headers, lastheader + 1,
473 lastheader + 2, sizeof(*mtmp));
475 dkim_err(message, "Can't store header");
478 message->headers = mtmp;
480 if ((message->headers[lastheader] = strdup(line)) == NULL) {
481 dkim_err(message, "Can't store header");
484 message->headers[lastheader + 1 ] = NULL;
485 message->lastheader = 1;
488 linelen += strlen(message->headers[lastheader]);
489 if (canonheader == CANON_SIMPLE)
492 htmp = reallocarray(message->headers[lastheader], linelen,
495 dkim_err(message, "Can't store header");
498 message->headers[lastheader] = htmp;
499 if (canonheader == CANON_SIMPLE) {
500 if (strlcat(htmp, "\r\n", linelen) >= linelen)
501 osmtpd_errx(1, "Missized header");
502 } else if (canonheader == CANON_RELAXED &&
503 (tmp = strchr(message->headers[lastheader], ':')) != NULL &&
507 if (strlcat(htmp, line, linelen) >= linelen)
508 osmtpd_errx(1, "Missized header");
513 dkim_parse_body(struct dkim_message *message, char *line)
518 if (canonbody == CANON_RELAXED) {
519 for (r = w = 0; line[r] != '\0'; r++) {
520 if (line[r] == ' ' || line[r] == '\t') {
521 if (r != 0 && line[w - 1] == ' ')
528 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
529 line[linelen] = '\0';
531 linelen = strlen(line);
533 if (line[0] == '\0') {
534 message->body_whitelines++;
538 while (message->body_whitelines--) {
539 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
540 dkim_errx(message, "Can't update hash context");
544 message->body_whitelines = 0;
545 message->has_body = 1;
547 if (EVP_DigestUpdate(message->dctx, line, linelen) == 0 ||
548 EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
549 dkim_errx(message, "Can't update hash context");
555 dkim_sign(struct osmtpd_ctx *ctx)
557 struct dkim_message *message = ctx->local_message;
558 /* Use largest hash size here */
559 unsigned char bdigest[EVP_MAX_MD_SIZE];
560 unsigned char digest[(((sizeof(bdigest) + 2) / 3) * 4) + 1];
562 const char *sdomain = domain[0], *tsdomain;
567 unsigned int digestsz;
569 if (addtime || addexpire)
571 if (addtime && !dkim_signature_printf(message, "t=%lld; ",
574 if (addexpire != 0 && !dkim_signature_printf(message, "x=%lld; ",
575 now + addexpire < now ? INT64_MAX : now + addexpire))
578 if (canonbody == CANON_SIMPLE && !message->has_body) {
579 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
580 dkim_errx(message, "Can't update hash context");
584 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0) {
585 dkim_errx(message, "Can't finalize hash context");
588 EVP_EncodeBlock(digest, bdigest, digestsz);
589 if (!dkim_signature_printf(message, "bh=%s; h=", digest))
591 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
592 for (i = 0; message->headers[i] != NULL; i++)
594 EVP_MD_CTX_reset(message->dctx);
596 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
598 dkim_errx(message, "Failed to initialize signature "
603 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1) {
604 dkim_errx(message, "Failed to initialize hash context");
608 for (i--; i >= 0; i--) {
610 if (EVP_DigestSignUpdate(message->dctx,
612 strlen(message->headers[i])) != 1 ||
613 EVP_DigestSignUpdate(message->dctx, "\r\n",
615 dkim_errx(message, "Failed to update signature "
620 if (EVP_DigestUpdate(message->dctx, message->headers[i],
621 strlen(message->headers[i])) != 1 ||
622 EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
623 dkim_errx(message, "Failed to update digest "
628 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
630 /* We're done with the cached header after hashing */
631 for (tmp = message->headers[i]; tmp[0] != ':'; tmp++) {
632 if (tmp[0] == ' ' || tmp[0] == '\t')
634 tmp[0] = tolower(tmp[0]);
637 if (!dkim_signature_printf(message, "%s%s",
638 message->headers[i + 1] == NULL ? "" : ":",
639 message->headers[i]))
642 dkim_signature_printf(message, "; d=%s; b=", sdomain);
643 if (!dkim_signature_normalize(message))
645 if ((tmp = strdup(message->signature.signature)) == NULL) {
646 dkim_err(message, "Can't create DKIM signature");
649 dkim_parse_header(message, tmp, 1);
651 if (EVP_DigestSignUpdate(message->dctx, tmp,
653 dkim_errx(message, "Failed to update signature "
658 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1) {
659 dkim_errx(message, "Failed to update digest context");
665 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1) {
666 dkim_errx(message, "Can't finalize signature context");
671 if (EVP_DigestFinal_ex(message->dctx, bdigest,
673 dkim_errx(message, "Can't finalize hash context");
676 EVP_MD_CTX_reset(message->dctx);
677 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
679 dkim_errx(message, "Failed to initialize signature "
683 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
685 dkim_errx(message, "Failed to finalize signature");
690 if ((tmp = malloc(linelen)) == NULL) {
691 dkim_err(message, "Can't allocate space for signature");
695 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1) {
696 dkim_errx(message, "Failed to finalize signature");
701 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
703 dkim_errx(message, "Failed to finalize signature");
708 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL) {
709 dkim_err(message, "Can't create DKIM signature");
712 EVP_EncodeBlock(b, tmp, linelen);
714 dkim_signature_printf(message, "%s\r\n", b);
716 dkim_signature_normalize(message);
717 tmp = message->signature.signature;
718 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
720 osmtpd_filter_dataline(ctx, "%s", tmp);
725 rewind(message->origf);
726 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
728 osmtpd_filter_dataline(ctx, "%s", tmp);
733 osmtpd_filter_dataline(ctx, ".");
737 dkim_signature_normalize(struct dkim_message *message)
743 size_t *headerlen = &(message->signature.len);
746 char *sig = message->signature.signature;
748 for (linelen = i = 0; sig[i] != '\0'; i++) {
749 if (sig[i] == '\r' && sig[i + 1] == '\n') {
756 linelen = (linelen + 8) & ~7;
766 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
767 for (skip = checkpoint + 1;
768 sig[skip] == ' ' || sig[skip] == '\t';
771 skip -= checkpoint + 1;
772 if (!dkim_signature_need(message,
773 skip > 3 ? 0 : 3 - skip + 1))
775 sig = message->signature.signature;
777 memmove(sig + checkpoint + 3,
778 sig + checkpoint + skip,
779 *headerlen - skip - checkpoint + 1);
780 sig[checkpoint + 1] = '\r';
781 sig[checkpoint + 2] = '\n';
782 sig[checkpoint + 3] = '\t';
784 *headerlen = *headerlen + 3 - skip;
804 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
805 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
818 dkim_signature_printheader(struct dkim_message *message, const char *header)
821 static char *fmtheader = NULL;
823 static size_t size = 0;
826 len = strlen(header);
827 if ((len + 3) * 3 < len) {
829 dkim_err(message, "Can't add z-component to header");
832 if ((len + 3) * 3 > size) {
833 if ((tmp = reallocarray(fmtheader, 3, len + 3)) == NULL) {
834 dkim_err(message, "Can't add z-component to header");
838 size = (len + 1) * 3;
841 first = message->signature.signature[message->signature.len - 1] == '=';
842 for (j = i = 0; header[i] != '\0'; i++, j++) {
843 if (i == 0 && header[i] != ' ' && header[i] != '\t' && !first)
844 fmtheader[j++] = '|';
845 if ((header[i] >= 0x21 && header[i] <= 0x3A) ||
846 (header[i] == 0x3C) ||
847 (header[i] >= 0x3E && header[i] <= 0x7B) ||
848 (header[i] >= 0x7D && header[i] <= 0x7E))
849 fmtheader[j] = header[i];
851 fmtheader[j++] = '=';
852 (void) sprintf(fmtheader + j, "%02hhX", header[i]);
856 (void) sprintf(fmtheader + j, "=%02hhX=%02hhX", (unsigned char) '\r',
857 (unsigned char) '\n');
859 return dkim_signature_printf(message, "%s", fmtheader);
863 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
865 struct dkim_signature *sig = &(message->signature);
870 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
871 fmt, ap)) >= sig->size - sig->len) {
873 if (!dkim_signature_need(message, len + 1))
876 if ((len = vsnprintf(sig->signature + sig->len,
877 sig->size - sig->len, fmt, ap)) >= sig->size - sig->len)
878 osmtpd_errx(1, "Miscalculated header size");
886 dkim_domain_select(struct dkim_message *message, char *from)
888 char *mdomain0, *mdomain;
891 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL) {
892 if (errno != EINVAL) {
893 dkim_errx(message, "Couldn't parse from header");
899 while (mdomain != NULL && mdomain[0] != '\0') {
900 for (i = 0; i < ndomains; i++) {
901 if (strcasecmp(mdomain, domain[i]) == 0) {
906 if ((mdomain = strchr(mdomain, '.')) != NULL)
914 dkim_signature_need(struct dkim_message *message, size_t len)
916 struct dkim_signature *sig = &(message->signature);
919 if (sig->len + len < sig->size)
921 sig->size = (((len + sig->len) / 512) + 1) * 512;
922 if ((tmp = realloc(sig->signature, sig->size)) == NULL) {
923 dkim_err(message, "No room for signature");
926 sig->signature = tmp;
933 fprintf(stderr, "usage: filter-dkimsign [-tz] [-a signalg] "
934 "[-c canonicalization] \n [-h headerfields]"
935 "[-x seconds] -d domain -k keyfile -s selector\n");