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>
32 #include "openbsd-compat.h"
33 #include "opensmtpd.h"
36 struct dkim_signature {
47 size_t body_whitelines;
49 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_headers_set(char *);
104 int dkim_dataline(struct osmtpd_ctx *, const char *);
105 void *dkim_message_new(struct osmtpd_ctx *);
106 void dkim_message_free(struct osmtpd_ctx *, void *);
107 void dkim_parse_header(struct dkim_message *, char *, int);
108 void dkim_parse_body(struct dkim_message *, char *);
109 void dkim_sign(struct osmtpd_ctx *);
110 void dkim_signature_printheader(struct dkim_message *, const char *);
111 void dkim_signature_printf(struct dkim_message *, char *, ...)
112 __attribute__((__format__ (printf, 2, 3)));
113 void dkim_signature_normalize(struct dkim_message *);
114 const char *dkim_domain_select(struct dkim_message *, char *);
115 void dkim_signature_need(struct dkim_message *, size_t);
116 int dkim_sign_init(struct dkim_message *);
119 main(int argc, char *argv[])
128 while ((ch = getopt(argc, argv, "a:c:D:d:h:k:s:tx:z")) != -1) {
131 if (strncmp(optarg, "rsa-", 4) == 0) {
133 hashalg = optarg + 4;
134 keyid = EVP_PKEY_RSA;
137 } else if (strncmp(optarg, "ed25519-", 8) == 0) {
138 hashalg = optarg + 8;
139 cryptalg = "ed25519";
140 keyid = EVP_PKEY_ED25519;
144 osmtpd_errx(1, "invalid algorithm");
147 if (strncmp(optarg, "simple", 6) == 0) {
148 canonheader = CANON_SIMPLE;
150 } else if (strncmp(optarg, "relaxed", 7) == 0) {
151 canonheader = CANON_RELAXED;
154 osmtpd_errx(1, "Invalid canonicalization");
155 if (optarg[0] == '/') {
156 if (strcmp(optarg + 1, "simple") == 0)
157 canonbody = CANON_SIMPLE;
158 else if (strcmp(optarg + 1, "relaxed") == 0)
159 canonbody = CANON_RELAXED;
162 "Invalid canonicalization");
163 } else if (optarg[0] == '\0')
164 canonbody = CANON_SIMPLE;
166 osmtpd_errx(1, "Invalid canonicalization");
169 if ((file = fopen(optarg, "r")) == NULL)
170 osmtpd_err(1, "Can't open domain file (%s)",
175 linelen = getline(&line, &linesz, file);
177 if (line[linelen - 1] == '\n')
178 line[linelen - 1] = '\0';
181 dkim_adddomain(line);
183 } while (linelen != -1);
185 osmtpd_err(1, "Error reading domain file (%s)",
190 dkim_adddomain(optarg);
193 dkim_headers_set(optarg);
196 if ((file = fopen(optarg, "r")) == NULL)
197 osmtpd_err(1, "Can't open key file (%s)",
199 pkey = PEM_read_PrivateKey(file, NULL, NULL, NULL);
201 osmtpd_errx(1, "Can't read key file");
211 addexpire = strtonum(optarg, 1, INT64_MAX, &errstr);
213 osmtpd_errx(1, "Expire offset is %s", errstr);
223 OpenSSL_add_all_digests();
225 if (pledge("tmppath stdio", NULL) == -1)
226 osmtpd_err(1, "pledge");
228 if ((hash_md = EVP_get_digestbyname(hashalg)) == NULL)
229 osmtpd_errx(1, "Can't find hash: %s", hashalg);
231 if (domain == NULL || selector == NULL || pkey == NULL)
234 if (EVP_PKEY_id(pkey) != keyid)
235 osmtpd_errx(1, "Key is not of type %s", cryptalg);
237 osmtpd_register_filter_dataline(dkim_dataline);
238 osmtpd_local_message(dkim_message_new, dkim_message_free);
245 dkim_adddomain(char *d)
247 domain = reallocarray(domain, ndomains + 1, sizeof(*domain));
249 osmtpd_err(1, "reallocarray");
250 domain[ndomains++] = d;
254 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
256 struct dkim_message *message = ctx->local_message;
260 linelen = strlen(line);
261 if (fprintf(message->origf, "%s\n", line) < (int) linelen) {
262 osmtpd_warnx(ctx, "Couldn't write to tempfile");
266 if (line[0] == '.' && line[1] =='\0') {
268 } else if (linelen != 0 && message->parsing_headers) {
271 if ((linedup = strdup(line)) == NULL)
272 osmtpd_err(1, "strdup");
273 dkim_parse_header(message, linedup, 0);
275 } else if (linelen == 0 && message->parsing_headers) {
277 dkim_signature_printf(message, "; ");
278 message->parsing_headers = 0;
282 if ((linedup = strdup(line)) == NULL)
283 osmtpd_err(1, "strdup");
284 dkim_parse_body(message, linedup);
292 dkim_message_new(struct osmtpd_ctx *ctx)
294 struct dkim_message *message;
296 if ((message = calloc(1, sizeof(*message))) == NULL) {
297 osmtpd_warn(ctx, "calloc");
301 if ((message->origf = tmpfile()) == NULL) {
302 osmtpd_warn(ctx, "Failed to open tempfile");
305 message->parsing_headers = 1;
307 message->body_whitelines = 0;
308 message->headers = calloc(1, sizeof(*(message->headers)));
309 if (message->headers == NULL) {
310 osmtpd_warn(ctx, "calloc");
313 message->lastheader = 0;
314 message->signature.signature = NULL;
315 message->signature.size = 0;
316 message->signature.len = 0;
318 dkim_signature_printf(message,
319 "DKIM-Signature: v=%s; a=%s-%s; c=%s/%s; s=%s; ", "1",
321 canonheader == CANON_SIMPLE ? "simple" : "relaxed",
322 canonbody == CANON_SIMPLE ? "simple" : "relaxed", selector);
324 dkim_signature_printf(message, "z=");
326 if ((message->dctx = EVP_MD_CTX_new()) == NULL) {
327 osmtpd_warnx(ctx, "EVP_MD_CTX_new");
330 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) <= 0) {
331 osmtpd_warnx(ctx, "EVP_DigestInit_ex");
337 dkim_message_free(ctx, message);
342 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
344 struct dkim_message *message = data;
347 fclose(message->origf);
348 EVP_MD_CTX_free(message->dctx);
349 free(message->signature.signature);
350 for (i = 0; message->headers != NULL &&
351 message->headers[i] != NULL; i++)
352 free(message->headers[i]);
353 free(message->headers);
358 dkim_headers_set(char *headers)
365 for (i = 0; headers[i] != '\0'; i++) {
366 /* RFC 5322 field-name */
367 if (!(headers[i] >= 33 && headers[i] <= 126))
368 osmtpd_errx(1, "-h: invalid character");
369 if (headers[i] == ':') {
370 /* Test for empty headers */
371 if (i == 0 || headers[i - 1] == ':')
372 osmtpd_errx(1, "-h: header can't be empty");
375 headers[i] = tolower(headers[i]);
377 if (headers[i - 1] == ':')
378 osmtpd_errx(1, "-h: header can't be empty");
380 if ((sign_headers = reallocarray(NULL, nsign_headers + 1,
381 sizeof(*sign_headers))) == NULL)
382 osmtpd_errx(1, "reallocarray");
384 for (i = 0; i < nsign_headers; i++) {
385 sign_headers[i] = headers;
386 if (i != nsign_headers - 1) {
387 headers = strchr(headers, ':');
390 if (strcasecmp(sign_headers[i], "from") == 0)
394 osmtpd_errx(1, "From header must be included");
398 dkim_parse_header(struct dkim_message *message, char *line, int force)
410 if (addheaders == 2 && !force)
411 dkim_signature_printheader(message, line);
413 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
415 if ((line[0] != ' ' && line[0] != '\t')) {
416 message->lastheader = 0;
417 for (i = 0; i < nsign_headers; i++) {
418 hlen = strlen(sign_headers[i]);
419 if (strncasecmp(line, sign_headers[i], hlen) == 0) {
420 while (line[hlen] == ' ' || line[hlen] == '\t')
422 if (line[hlen] != ':')
427 if (i == nsign_headers && !force)
431 if (addheaders == 1 && !force)
432 dkim_signature_printheader(message, line);
434 if (canonheader == CANON_RELAXED) {
435 if (!message->lastheader)
437 for (r = w = 0; line[r] != '\0'; r++) {
438 if (line[r] == ':' && fieldname) {
439 if (w > 0 && line[w - 1] == ' ')
444 while (line[r + 1] == ' ' ||
449 if (line[r] == ' ' || line[r] == '\t' ||
450 line[r] == '\r' || line[r] == '\n') {
451 if (r != 0 && w != 0 && line[w - 1] == ' ')
455 } else if (fieldname) {
456 line[w++] = tolower(line[r]);
461 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
462 line[linelen] = '\0';
464 linelen = strlen(line);
466 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
468 if (!message->lastheader) {
469 mtmp = recallocarray(message->headers, lastheader + 1,
470 lastheader + 2, sizeof(*mtmp));
472 osmtpd_err(1, "reallocarray");
473 message->headers = mtmp;
475 if ((message->headers[lastheader] = strdup(line)) == NULL)
476 osmtpd_err(1, "strdup");
477 message->headers[lastheader + 1 ] = NULL;
478 message->lastheader = 1;
481 linelen += strlen(message->headers[lastheader]);
482 if (canonheader == CANON_SIMPLE)
485 htmp = reallocarray(message->headers[lastheader], linelen,
488 osmtpd_err(1, "reallocarray");
489 message->headers[lastheader] = htmp;
490 if (canonheader == CANON_SIMPLE) {
491 (void)strlcat(htmp, "\r\n", linelen);
492 } else if (canonheader == CANON_RELAXED &&
493 (tmp = strchr(message->headers[lastheader], ':')) != NULL &&
497 (void)strlcat(htmp, line, linelen);
502 dkim_parse_body(struct dkim_message *message, char *line)
507 if (canonbody == CANON_RELAXED) {
508 for (r = w = 0; line[r] != '\0'; r++) {
509 if (line[r] == ' ' || line[r] == '\t') {
510 if (r != 0 && line[w - 1] == ' ')
517 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
518 line[linelen] = '\0';
520 linelen = strlen(line);
522 if (line[0] == '\0') {
523 message->body_whitelines++;
527 while (message->body_whitelines--) {
528 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0)
529 osmtpd_errx(1, "EVP_DigestUpdate");
531 message->body_whitelines = 0;
532 message->has_body = 1;
534 if (EVP_DigestUpdate(message->dctx, line, linelen) == 0 ||
535 EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0)
536 osmtpd_errx(1, "EVP_DigestUpdate");
540 dkim_sign(struct osmtpd_ctx *ctx)
542 struct dkim_message *message = ctx->local_message;
543 /* Use largest hash size here */
544 unsigned char bdigest[EVP_MAX_MD_SIZE];
545 unsigned char digest[(((sizeof(bdigest) + 2) / 3) * 4) + 1];
547 const char *sdomain = domain[0], *tsdomain;
552 unsigned int digestsz;
554 if (addtime || addexpire)
557 dkim_signature_printf(message, "t=%lld; ", (long long)now);
559 dkim_signature_printf(message, "x=%lld; ",
560 now + addexpire < now ? LLONG_MAX : now + addexpire);
562 if (canonbody == CANON_SIMPLE && !message->has_body) {
563 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0)
564 osmtpd_errx(1, "EVP_DigestUpdate");
566 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0)
567 osmtpd_errx(1, "EVP_DigestFinal_ex");
568 EVP_EncodeBlock(digest, bdigest, digestsz);
569 dkim_signature_printf(message, "bh=%s; h=", digest);
570 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
571 for (i = 0; message->headers[i] != NULL; i++)
573 EVP_MD_CTX_reset(message->dctx);
575 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
577 osmtpd_errx(1, "EVP_DigestSignInit");
579 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1)
580 osmtpd_errx(1, "EVP_DigestInit_ex");
582 for (i--; i >= 0; i--) {
584 if (EVP_DigestSignUpdate(message->dctx,
586 strlen(message->headers[i])) != 1 ||
587 EVP_DigestSignUpdate(message->dctx, "\r\n",
589 osmtpd_errx(1, "EVP_DigestSignUpdate");
591 if (EVP_DigestUpdate(message->dctx, message->headers[i],
592 strlen(message->headers[i])) != 1 ||
593 EVP_DigestUpdate(message->dctx, "\r\n", 2) <= 0)
594 osmtpd_errx(1, "EVP_DigestSignUpdate");
596 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
598 /* We're done with the cached header after hashing */
599 for (tmp = message->headers[i]; tmp[0] != ':'; tmp++) {
600 if (tmp[0] == ' ' || tmp[0] == '\t')
602 tmp[0] = tolower(tmp[0]);
605 dkim_signature_printf(message, "%s%s",
606 message->headers[i + 1] == NULL ? "" : ":",
607 message->headers[i]);
609 dkim_signature_printf(message, "; d=%s; b=", sdomain);
610 dkim_signature_normalize(message);
611 if ((tmp = strdup(message->signature.signature)) == NULL)
612 osmtpd_err(1, "strdup");
613 dkim_parse_header(message, tmp, 1);
615 if (EVP_DigestSignUpdate(message->dctx, tmp,
617 osmtpd_errx(1, "EVP_DigestSignUpdate");
619 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1)
620 osmtpd_errx(1, "EVP_DigestUpdate");
624 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1)
625 osmtpd_errx(1, "EVP_DigestSignFinal");
628 if (EVP_DigestFinal_ex(message->dctx, bdigest,
630 osmtpd_errx(1, "EVP_DigestFinal_ex");
631 EVP_MD_CTX_reset(message->dctx);
632 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
634 osmtpd_errx(1, "EVP_DigestSignInit");
635 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
637 osmtpd_errx(1, "EVP_DigestSign");
640 if ((tmp = malloc(linelen)) == NULL)
641 osmtpd_err(1, "malloc");
643 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1)
644 osmtpd_errx(1, "EVP_DigestSignFinal");
647 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
649 osmtpd_errx(1, "EVP_DigestSign");
652 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL)
653 osmtpd_err(1, "malloc");
654 EVP_EncodeBlock(b, tmp, linelen);
656 dkim_signature_printf(message, "%s\r\n", b);
658 dkim_signature_normalize(message);
659 tmp = message->signature.signature;
660 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
662 osmtpd_filter_dataline(ctx, "%s", tmp);
667 rewind(message->origf);
668 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
670 osmtpd_filter_dataline(ctx, "%s", tmp);
677 dkim_signature_normalize(struct dkim_message *message)
683 size_t *headerlen = &(message->signature.len);
686 char *sig = message->signature.signature;
688 for (linelen = i = 0; sig[i] != '\0'; i++) {
689 if (sig[i] == '\r' && sig[i + 1] == '\n') {
696 linelen = (linelen + 8) & ~7;
706 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
707 for (skip = checkpoint + 1;
708 sig[skip] == ' ' || sig[skip] == '\t';
711 skip -= checkpoint + 1;
712 dkim_signature_need(message,
713 skip > 3 ? 0 : 3 - skip + 1);
714 sig = message->signature.signature;
716 memmove(sig + checkpoint + 3,
717 sig + checkpoint + skip,
718 *headerlen - skip - checkpoint + 1);
719 sig[checkpoint + 1] = '\r';
720 sig[checkpoint + 2] = '\n';
721 sig[checkpoint + 3] = '\t';
723 *headerlen = *headerlen + 3 - skip;
743 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
744 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
756 dkim_signature_printheader(struct dkim_message *message, const char *line)
761 first = message->signature.signature[message->signature.len - 1] == '=';
762 for (i = 0; line[i] != '\0'; i++) {
763 if (i == 0 && line[i] != ' ' && line[i] != '\t' && !first)
764 dkim_signature_printf(message, "|");
765 if ((line[i] >= 0x21 && line[i] <= 0x3A) ||
767 (line[i] >= 0x3E && line[i] <= 0x7B) ||
768 (line[i] >= 0x7D && line[i] <= 0x7E)) {
769 dkim_signature_printf(message, "%c", line[i]);
771 dkim_signature_printf(message, "=%02hhX", line[i]);
773 dkim_signature_printf(message, "=%02hhX=%02hhX", '\r', '\n');
777 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
779 struct dkim_signature *sig = &(message->signature);
784 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
785 fmt, ap)) >= sig->size - sig->len) {
787 dkim_signature_need(message, len + 1);
789 if ((len = vsnprintf(sig->signature + sig->len,
790 sig->size - sig->len, fmt, ap)) >= sig->size - sig->len)
791 osmtpd_errx(1, "Miscalculated header size");
798 dkim_domain_select(struct dkim_message *message, char *from)
800 char *mdomain0, *mdomain;
803 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL)
806 while (mdomain != NULL && mdomain[0] != '\0') {
807 for (i = 0; i < ndomains; i++) {
808 if (strcasecmp(mdomain, domain[i]) == 0) {
813 if ((mdomain = strchr(mdomain, '.')) != NULL)
821 dkim_signature_need(struct dkim_message *message, size_t len)
823 struct dkim_signature *sig = &(message->signature);
826 if (sig->len + len < sig->size)
828 sig->size = (((len + sig->len) / 512) + 1) * 512;
829 if ((tmp = realloc(sig->signature, sig->size)) == NULL)
830 osmtpd_err(1, "malloc");
831 sig->signature = tmp;
837 fprintf(stderr, "usage: filter-dkimsign [-tz] [-a signalg] "
838 "[-c canonicalization] \n [-h headerfields]"
839 "[-x seconds] -D file -d domain -k keyfile -s selector\n");