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_adddomain(char *);
103 void dkim_err(struct dkim_message *, char *);
104 void dkim_errx(struct dkim_message *, char *);
105 void dkim_headers_set(char *);
106 void dkim_dataline(struct osmtpd_ctx *, const char *);
107 void dkim_commit(struct osmtpd_ctx *);
108 void *dkim_message_new(struct osmtpd_ctx *);
109 void dkim_message_free(struct osmtpd_ctx *, void *);
110 void dkim_parse_header(struct dkim_message *, char *, int);
111 void dkim_parse_body(struct dkim_message *, char *);
112 void dkim_sign(struct osmtpd_ctx *);
113 int dkim_signature_printheader(struct dkim_message *, const char *);
114 int dkim_signature_printf(struct dkim_message *, char *, ...)
115 __attribute__((__format__ (printf, 2, 3)));
116 int dkim_signature_normalize(struct dkim_message *);
117 const char *dkim_domain_select(struct dkim_message *, char *);
118 int dkim_signature_need(struct dkim_message *, size_t);
119 int dkim_sign_init(struct dkim_message *);
122 main(int argc, char *argv[])
131 while ((ch = getopt(argc, argv, "a:c:D:d:h:k:s:tx:z")) != -1) {
134 if (strncmp(optarg, "rsa-", 4) == 0) {
136 hashalg = optarg + 4;
137 keyid = EVP_PKEY_RSA;
140 } else if (strncmp(optarg, "ed25519-", 8) == 0) {
141 hashalg = optarg + 8;
142 cryptalg = "ed25519";
143 keyid = EVP_PKEY_ED25519;
147 osmtpd_errx(1, "invalid algorithm");
150 if (strncmp(optarg, "simple", 6) == 0) {
151 canonheader = CANON_SIMPLE;
153 } else if (strncmp(optarg, "relaxed", 7) == 0) {
154 canonheader = CANON_RELAXED;
157 osmtpd_err(1, "Invalid canonicalization");
158 if (optarg[0] == '/') {
159 if (strcmp(optarg + 1, "simple") == 0)
160 canonbody = CANON_SIMPLE;
161 else if (strcmp(optarg + 1, "relaxed") == 0)
162 canonbody = CANON_RELAXED;
165 "Invalid canonicalization");
166 } else if (optarg[0] == '\0')
167 canonbody = CANON_SIMPLE;
169 osmtpd_err(1, "Invalid canonicalization");
172 if ((file = fopen(optarg, "r")) == NULL)
173 osmtpd_err(1, "Can't open domain file (%s)",
178 linelen = getline(&line, &linesz, file);
180 if (line[linelen - 1] == '\n')
181 line[linelen - 1] = '\0';
182 dkim_adddomain(line);
184 } while (linelen != -1);
186 osmtpd_err(1, "Error reading domain file (%s)",
191 dkim_adddomain(optarg);
194 dkim_headers_set(optarg);
197 if ((file = fopen(optarg, "r")) == NULL)
198 osmtpd_err(1, "Can't open key file (%s)",
200 pkey = PEM_read_PrivateKey(file, NULL, NULL, NULL);
202 osmtpd_errx(1, "Can't read key file");
212 addexpire = strtonum(optarg, 1, INT64_MAX, &errstr);
214 osmtpd_errx(1, "Expire offset is %s", errstr);
224 OpenSSL_add_all_digests();
226 if (pledge("tmppath stdio", NULL) == -1)
227 osmtpd_err(1, "pledge");
229 if ((hash_md = EVP_get_digestbyname(hashalg)) == NULL)
230 osmtpd_errx(1, "Can't find hash: %s", hashalg);
232 if (domain == NULL || selector == NULL || pkey == NULL)
235 if (EVP_PKEY_id(pkey) != keyid)
236 osmtpd_errx(1, "Key is not of type %s", cryptalg);
238 osmtpd_register_filter_dataline(dkim_dataline);
239 osmtpd_register_filter_commit(dkim_commit);
240 osmtpd_local_message(dkim_message_new, dkim_message_free);
247 dkim_adddomain(char *d)
249 domain = reallocarray(domain, ndomains + 1, sizeof(*domain));
251 osmtpd_err(1, "malloc");
252 domain[ndomains++] = d;
257 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
259 struct dkim_message *message = ctx->local_message;
264 if (line[0] == '.' && line[1] =='\0')
265 osmtpd_filter_dataline(ctx, ".");
269 linelen = strlen(line);
270 if (fprintf(message->origf, "%s\n", line) < (int) linelen)
271 dkim_errx(message, "Couldn't write to tempfile");
273 if (line[0] == '.' && line[1] =='\0') {
275 } else if (linelen != 0 && message->parsing_headers) {
278 if ((linedup = strdup(line)) == NULL)
279 osmtpd_err(1, "strdup");
280 dkim_parse_header(message, linedup, 0);
282 } else if (linelen == 0 && message->parsing_headers) {
283 if (addheaders > 0 && !dkim_signature_printf(message, "; "))
285 message->parsing_headers = 0;
289 if ((linedup = strdup(line)) == NULL)
290 osmtpd_err(1, "strdup");
291 dkim_parse_body(message, linedup);
297 dkim_commit(struct osmtpd_ctx *ctx)
299 struct dkim_message *message = ctx->local_message;
302 osmtpd_filter_disconnect(ctx, "Internal server error");
304 osmtpd_filter_proceed(ctx);
308 dkim_message_new(struct osmtpd_ctx *ctx)
310 struct dkim_message *message;
312 if ((message = calloc(1, sizeof(*message))) == NULL) {
313 dkim_err(message, "Failed to create message context");
317 if ((message->origf = tmpfile()) == NULL) {
318 dkim_err(message, "Failed to open tempfile");
321 message->parsing_headers = 1;
323 message->body_whitelines = 0;
324 message->headers = calloc(1, sizeof(*(message->headers)));
325 if (message->headers == NULL) {
326 dkim_err(message, "Can't save headers");
329 message->lastheader = 0;
330 message->signature.signature = NULL;
331 message->signature.size = 0;
332 message->signature.len = 0;
335 if (!dkim_signature_printf(message,
336 "DKIM-Signature: v=%s; a=%s-%s; c=%s/%s; s=%s; ", "1",
338 canonheader == CANON_SIMPLE ? "simple" : "relaxed",
339 canonbody == CANON_SIMPLE ? "simple" : "relaxed", selector))
341 if (addheaders > 0 && !dkim_signature_printf(message, "z="))
344 if ((message->dctx = EVP_MD_CTX_new()) == NULL) {
345 dkim_errx(message, "Failed to create hash context");
348 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) <= 0) {
349 dkim_errx(message, "Failed to initialize hash context");
354 dkim_message_free(ctx, message);
359 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
361 struct dkim_message *message = data;
364 fclose(message->origf);
365 EVP_MD_CTX_free(message->dctx);
366 free(message->signature.signature);
367 for (i = 0; message->headers != NULL &&
368 message->headers[i] != NULL; i++)
369 free(message->headers[i]);
370 free(message->headers);
375 dkim_headers_set(char *headers)
382 for (i = 0; headers[i] != '\0'; i++) {
383 /* RFC 5322 field-name */
384 if (!(headers[i] >= 33 && headers[i] <= 126))
385 osmtpd_errx(1, "-h: invalid character");
386 if (headers[i] == ':') {
387 /* Test for empty headers */
388 if (i == 0 || headers[i - 1] == ':')
389 osmtpd_errx(1, "-h: header can't be empty");
392 headers[i] = tolower(headers[i]);
394 if (headers[i - 1] == ':')
395 osmtpd_errx(1, "-h: header can't be empty");
397 if ((sign_headers = reallocarray(NULL, nsign_headers + 1,
398 sizeof(*sign_headers))) == NULL)
399 osmtpd_errx(1, NULL);
401 for (i = 0; i < nsign_headers; i++) {
402 sign_headers[i] = headers;
403 if (i != nsign_headers - 1) {
404 headers = strchr(headers, ':');
407 if (strcasecmp(sign_headers[i], "from") == 0)
411 osmtpd_errx(1, "From header must be included");
415 dkim_err(struct dkim_message *message, char *msg)
418 fprintf(stderr, "%s: %s\n", msg, strerror(errno));
422 dkim_errx(struct dkim_message *message, char *msg)
425 fprintf(stderr, "%s\n", msg);
429 dkim_parse_header(struct dkim_message *message, char *line, int force)
441 if (addheaders == 2 && !force &&
442 !dkim_signature_printheader(message, line))
445 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
447 if ((line[0] != ' ' && line[0] != '\t')) {
448 message->lastheader = 0;
449 for (i = 0; i < nsign_headers; i++) {
450 hlen = strlen(sign_headers[i]);
451 if (strncasecmp(line, sign_headers[i], hlen) == 0) {
452 while (line[hlen] == ' ' || line[hlen] == '\t')
454 if (line[hlen] != ':')
459 if (i == nsign_headers && !force)
463 if (addheaders == 1 && !force &&
464 !dkim_signature_printheader(message, line))
467 if (canonheader == CANON_RELAXED) {
468 if (!message->lastheader)
470 for (r = w = 0; line[r] != '\0'; r++) {
471 if (line[r] == ':' && fieldname) {
472 if (w > 0 && line[w - 1] == ' ')
477 while (line[r + 1] == ' ' ||
482 if (line[r] == ' ' || line[r] == '\t' ||
483 line[r] == '\r' || line[r] == '\n') {
484 if (r != 0 && w != 0 && line[w - 1] == ' ')
488 } else if (fieldname) {
489 line[w++] = tolower(line[r]);
494 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
495 line[linelen] = '\0';
497 linelen = strlen(line);
499 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
501 if (!message->lastheader) {
502 mtmp = recallocarray(message->headers, lastheader + 1,
503 lastheader + 2, sizeof(*mtmp));
505 dkim_err(message, "Can't store header");
508 message->headers = mtmp;
510 if ((message->headers[lastheader] = strdup(line)) == NULL) {
511 dkim_err(message, "Can't store header");
514 message->headers[lastheader + 1 ] = NULL;
515 message->lastheader = 1;
518 linelen += strlen(message->headers[lastheader]);
519 if (canonheader == CANON_SIMPLE)
522 htmp = reallocarray(message->headers[lastheader], linelen,
525 dkim_err(message, "Can't store header");
528 message->headers[lastheader] = htmp;
529 if (canonheader == CANON_SIMPLE) {
530 if (strlcat(htmp, "\r\n", linelen) >= linelen)
531 osmtpd_errx(1, "Missized header");
532 } else if (canonheader == CANON_RELAXED &&
533 (tmp = strchr(message->headers[lastheader], ':')) != NULL &&
537 if (strlcat(htmp, line, linelen) >= linelen)
538 osmtpd_errx(1, "Missized header");
543 dkim_parse_body(struct dkim_message *message, char *line)
548 if (canonbody == CANON_RELAXED) {
549 for (r = w = 0; line[r] != '\0'; r++) {
550 if (line[r] == ' ' || line[r] == '\t') {
551 if (r != 0 && line[w - 1] == ' ')
558 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
559 line[linelen] = '\0';
561 linelen = strlen(line);
563 if (line[0] == '\0') {
564 message->body_whitelines++;
568 while (message->body_whitelines--) {
569 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
570 dkim_errx(message, "Can't update hash context");
574 message->body_whitelines = 0;
575 message->has_body = 1;
577 if (EVP_DigestUpdate(message->dctx, line, linelen) == 0 ||
578 EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
579 dkim_errx(message, "Can't update hash context");
585 dkim_sign(struct osmtpd_ctx *ctx)
587 struct dkim_message *message = ctx->local_message;
588 /* Use largest hash size here */
589 unsigned char bdigest[EVP_MAX_MD_SIZE];
590 unsigned char digest[(((sizeof(bdigest) + 2) / 3) * 4) + 1];
592 const char *sdomain = domain[0], *tsdomain;
597 unsigned int digestsz;
599 if (addtime || addexpire)
601 if (addtime && !dkim_signature_printf(message, "t=%lld; ",
604 if (addexpire != 0 && !dkim_signature_printf(message, "x=%lld; ",
605 now + addexpire < now ? INT64_MAX : now + addexpire))
608 if (canonbody == CANON_SIMPLE && !message->has_body) {
609 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
610 dkim_errx(message, "Can't update hash context");
614 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0) {
615 dkim_errx(message, "Can't finalize hash context");
618 EVP_EncodeBlock(digest, bdigest, digestsz);
619 if (!dkim_signature_printf(message, "bh=%s; h=", digest))
621 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
622 for (i = 0; message->headers[i] != NULL; i++)
624 EVP_MD_CTX_reset(message->dctx);
626 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
628 dkim_errx(message, "Failed to initialize signature "
633 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1) {
634 dkim_errx(message, "Failed to initialize hash context");
638 for (i--; i >= 0; i--) {
640 if (EVP_DigestSignUpdate(message->dctx,
642 strlen(message->headers[i])) != 1 ||
643 EVP_DigestSignUpdate(message->dctx, "\r\n",
645 dkim_errx(message, "Failed to update signature "
650 if (EVP_DigestUpdate(message->dctx, message->headers[i],
651 strlen(message->headers[i])) != 1 ||
652 EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0) {
653 dkim_errx(message, "Failed to update digest "
658 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
660 /* We're done with the cached header after hashing */
661 for (tmp = message->headers[i]; tmp[0] != ':'; tmp++) {
662 if (tmp[0] == ' ' || tmp[0] == '\t')
664 tmp[0] = tolower(tmp[0]);
667 if (!dkim_signature_printf(message, "%s%s",
668 message->headers[i + 1] == NULL ? "" : ":",
669 message->headers[i]))
672 dkim_signature_printf(message, "; d=%s; b=", sdomain);
673 if (!dkim_signature_normalize(message))
675 if ((tmp = strdup(message->signature.signature)) == NULL) {
676 dkim_err(message, "Can't create DKIM signature");
679 dkim_parse_header(message, tmp, 1);
681 if (EVP_DigestSignUpdate(message->dctx, tmp,
683 dkim_errx(message, "Failed to update signature "
688 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1) {
689 dkim_errx(message, "Failed to update digest context");
695 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1) {
696 dkim_errx(message, "Can't finalize signature context");
701 if (EVP_DigestFinal_ex(message->dctx, bdigest,
703 dkim_errx(message, "Can't finalize hash context");
706 EVP_MD_CTX_reset(message->dctx);
707 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
709 dkim_errx(message, "Failed to initialize signature "
713 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
715 dkim_errx(message, "Failed to finalize signature");
720 if ((tmp = malloc(linelen)) == NULL) {
721 dkim_err(message, "Can't allocate space for signature");
725 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1) {
726 dkim_errx(message, "Failed to finalize signature");
731 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
733 dkim_errx(message, "Failed to finalize signature");
738 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL) {
739 dkim_err(message, "Can't create DKIM signature");
742 EVP_EncodeBlock(b, tmp, linelen);
744 dkim_signature_printf(message, "%s\r\n", b);
746 dkim_signature_normalize(message);
747 tmp = message->signature.signature;
748 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
750 osmtpd_filter_dataline(ctx, "%s", tmp);
755 rewind(message->origf);
756 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
758 osmtpd_filter_dataline(ctx, "%s", tmp);
763 osmtpd_filter_dataline(ctx, ".");
767 dkim_signature_normalize(struct dkim_message *message)
773 size_t *headerlen = &(message->signature.len);
776 char *sig = message->signature.signature;
778 for (linelen = i = 0; sig[i] != '\0'; i++) {
779 if (sig[i] == '\r' && sig[i + 1] == '\n') {
786 linelen = (linelen + 8) & ~7;
796 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
797 for (skip = checkpoint + 1;
798 sig[skip] == ' ' || sig[skip] == '\t';
801 skip -= checkpoint + 1;
802 if (!dkim_signature_need(message,
803 skip > 3 ? 0 : 3 - skip + 1))
805 sig = message->signature.signature;
807 memmove(sig + checkpoint + 3,
808 sig + checkpoint + skip,
809 *headerlen - skip - checkpoint + 1);
810 sig[checkpoint + 1] = '\r';
811 sig[checkpoint + 2] = '\n';
812 sig[checkpoint + 3] = '\t';
814 *headerlen = *headerlen + 3 - skip;
834 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
835 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
848 dkim_signature_printheader(struct dkim_message *message, const char *header)
851 static char *fmtheader = NULL;
853 static size_t size = 0;
856 len = strlen(header);
857 if ((len + 3) * 3 < len) {
859 dkim_err(message, "Can't add z-component to header");
862 if ((len + 3) * 3 > size) {
863 if ((tmp = reallocarray(fmtheader, 3, len + 3)) == NULL) {
864 dkim_err(message, "Can't add z-component to header");
868 size = (len + 1) * 3;
871 first = message->signature.signature[message->signature.len - 1] == '=';
872 for (j = i = 0; header[i] != '\0'; i++, j++) {
873 if (i == 0 && header[i] != ' ' && header[i] != '\t' && !first)
874 fmtheader[j++] = '|';
875 if ((header[i] >= 0x21 && header[i] <= 0x3A) ||
876 (header[i] == 0x3C) ||
877 (header[i] >= 0x3E && header[i] <= 0x7B) ||
878 (header[i] >= 0x7D && header[i] <= 0x7E))
879 fmtheader[j] = header[i];
881 fmtheader[j++] = '=';
882 (void) sprintf(fmtheader + j, "%02hhX", header[i]);
886 (void) sprintf(fmtheader + j, "=%02hhX=%02hhX", (unsigned char) '\r',
887 (unsigned char) '\n');
889 return dkim_signature_printf(message, "%s", fmtheader);
893 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
895 struct dkim_signature *sig = &(message->signature);
900 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
901 fmt, ap)) >= sig->size - sig->len) {
903 if (!dkim_signature_need(message, len + 1))
906 if ((len = vsnprintf(sig->signature + sig->len,
907 sig->size - sig->len, fmt, ap)) >= sig->size - sig->len)
908 osmtpd_errx(1, "Miscalculated header size");
916 dkim_domain_select(struct dkim_message *message, char *from)
918 char *mdomain0, *mdomain;
921 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL) {
922 if (errno != EINVAL) {
923 dkim_errx(message, "Couldn't parse from header");
929 while (mdomain != NULL && mdomain[0] != '\0') {
930 for (i = 0; i < ndomains; i++) {
931 if (strcasecmp(mdomain, domain[i]) == 0) {
936 if ((mdomain = strchr(mdomain, '.')) != NULL)
944 dkim_signature_need(struct dkim_message *message, size_t len)
946 struct dkim_signature *sig = &(message->signature);
949 if (sig->len + len < sig->size)
951 sig->size = (((len + sig->len) / 512) + 1) * 512;
952 if ((tmp = realloc(sig->signature, sig->size)) == NULL) {
953 dkim_err(message, "No room for signature");
956 sig->signature = tmp;
963 fprintf(stderr, "usage: filter-dkimsign [-tz] [-a signalg] "
964 "[-c canonicalization] \n [-h headerfields]"
965 "[-x seconds] -D file -d domain -k keyfile -s selector\n");