Blob


1 /*
2 * Copyright (c) 2019 Martijn van Duren <martijn@openbsd.org>
3 *
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.
7 *
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.
15 */
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
19 #include <openssl/sha.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <syslog.h>
28 #include <time.h>
29 #include <unistd.h>
31 #include "openbsd-compat.h"
32 #include "opensmtpd.h"
33 #include "mheader.h"
35 struct dkim_signature {
36 char *signature;
37 size_t size;
38 size_t len;
39 };
41 struct dkim_message {
42 FILE *origf;
43 int parsing_headers;
44 char **headers;
45 int lastheader;
46 size_t body_whitelines;
47 int has_body;
48 struct dkim_signature signature;
49 int err;
50 EVP_MD_CTX *dctx;
51 };
53 /* RFC 6376 section 5.4.1 */
54 static char *dsign_headers[] = {
55 "from",
56 "reply-to",
57 "subject",
58 "date",
59 "to",
60 "cc",
61 "resent-date",
62 "resent-from",
63 "resent-to",
64 "resent-cc",
65 "in-reply-to",
66 "references",
67 "list-id",
68 "list-help",
69 "list-unsubscribe",
70 "list-subscribe",
71 "list-post",
72 "list-owner",
73 "list-archive"
74 };
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
101 void usage(void);
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 *);
120 int
121 main(int argc, char *argv[])
123 int ch;
124 FILE *keyfile;
125 const char *errstr;
127 while ((ch = getopt(argc, argv, "a:c:d:h:k:s:tx:z")) != -1) {
128 switch (ch) {
129 case 'a':
130 if (strncmp(optarg, "rsa-", 4) == 0) {
131 cryptalg = "rsa";
132 hashalg = optarg + 4;
133 keyid = EVP_PKEY_RSA;
134 sephash = 0;
135 #ifdef HAVE_ED25519
136 } else if (strncmp(optarg, "ed25519-", 8) == 0) {
137 hashalg = optarg + 8;
138 cryptalg = "ed25519";
139 keyid = EVP_PKEY_ED25519;
140 sephash = 1;
141 #endif
142 } else
143 osmtpd_errx(1, "invalid algorithm");
144 break;
145 case 'c':
146 if (strncmp(optarg, "simple", 6) == 0) {
147 canonheader = CANON_SIMPLE;
148 optarg += 6;
149 } else if (strncmp(optarg, "relaxed", 7) == 0) {
150 canonheader = CANON_RELAXED;
151 optarg += 7;
152 } else
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;
159 else
160 osmtpd_err(1,
161 "Invalid canonicalization");
162 } else if (optarg[0] == '\0')
163 canonbody = CANON_SIMPLE;
164 else
165 osmtpd_err(1, "Invalid canonicalization");
166 break;
167 case 'd':
168 if ((domain = reallocarray(domain, ndomains + 1,
169 sizeof(*domain))) == NULL)
170 osmtpd_err(1, "malloc");
171 domain[ndomains++] = optarg;
172 break;
173 case 'h':
174 dkim_headers_set(optarg);
175 break;
176 case 'k':
177 if ((keyfile = fopen(optarg, "r")) == NULL)
178 osmtpd_err(1, "Can't open key file (%s)",
179 optarg);
180 pkey = PEM_read_PrivateKey(keyfile, NULL, NULL, NULL);
181 if (pkey == NULL)
182 osmtpd_errx(1, "Can't read key file");
183 fclose(keyfile);
184 break;
185 case 's':
186 selector = optarg;
187 break;
188 case 't':
189 addtime = 1;
190 break;
191 case 'x':
192 addexpire = strtonum(optarg, 1, INT64_MAX, &errstr);
193 if (addexpire == 0)
194 osmtpd_errx(1, "Expire offset is %s", errstr);
195 break;
196 case 'z':
197 addheaders++;
198 break;
199 default:
200 usage();
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)
213 usage();
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);
221 osmtpd_run();
223 return 0;
226 void
227 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
229 struct dkim_message *message = ctx->local_message;
230 char *linedup;
231 size_t linelen;
233 if (message->err) {
234 if (line[0] == '.' && line[1] =='\0')
235 osmtpd_filter_dataline(ctx, ".");
236 return;
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') {
244 dkim_sign(ctx);
245 } else if (linelen != 0 && message->parsing_headers) {
246 if (line[0] == '.')
247 line++;
248 if ((linedup = strdup(line)) == NULL)
249 osmtpd_err(1, "strdup");
250 dkim_parse_header(message, linedup, 0);
251 free(linedup);
252 } else if (linelen == 0 && message->parsing_headers) {
253 if (addheaders > 0 && !dkim_signature_printf(message, "; "))
254 return;
255 message->parsing_headers = 0;
256 } else {
257 if (line[0] == '.')
258 line++;
259 if ((linedup = strdup(line)) == NULL)
260 osmtpd_err(1, "strdup");
261 dkim_parse_body(message, linedup);
262 free(linedup);
266 void
267 dkim_commit(struct osmtpd_ctx *ctx)
269 struct dkim_message *message = ctx->local_message;
271 if (message->err)
272 osmtpd_filter_disconnect(ctx, "Internal server error");
273 else
274 osmtpd_filter_proceed(ctx);
277 void *
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");
284 return NULL;
287 if ((message->origf = tmpfile()) == NULL) {
288 dkim_err(message, "Failed to open tempfile");
289 goto fail;
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");
297 goto fail;
299 message->lastheader = 0;
300 message->signature.signature = NULL;
301 message->signature.size = 0;
302 message->signature.len = 0;
303 message->err = 0;
305 if (!dkim_signature_printf(message,
306 "DKIM-Signature: v=%s; a=%s-%s; c=%s/%s; s=%s; ", "1",
307 cryptalg, hashalg,
308 canonheader == CANON_SIMPLE ? "simple" : "relaxed",
309 canonbody == CANON_SIMPLE ? "simple" : "relaxed", selector))
310 goto fail;
311 if (addheaders > 0 && !dkim_signature_printf(message, "z="))
312 goto fail;
314 if ((message->dctx = EVP_MD_CTX_new()) == NULL) {
315 dkim_errx(message, "Failed to create hash context");
316 goto fail;
318 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) <= 0) {
319 dkim_errx(message, "Failed to initialize hash context");
320 goto fail;
322 return message;
323 fail:
324 free(message->headers);
325 EVP_MD_CTX_free(message->dctx);
326 free(message);
327 return NULL;
330 void
331 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
333 struct dkim_message *message = data;
334 size_t i;
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);
342 free(message);
345 void
346 dkim_headers_set(char *headers)
348 size_t i;
349 int has_from = 0;
351 nsign_headers = 1;
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");
361 nsign_headers++;
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, ':');
376 headers++[0] = '\0';
378 if (strcasecmp(sign_headers[i], "from") == 0)
379 has_from = 1;
381 if (!has_from)
382 osmtpd_errx(1, "From header must be included");
385 void
386 dkim_err(struct dkim_message *message, char *msg)
388 message->err = 1;
389 fprintf(stderr, "%s: %s\n", msg, strerror(errno));
392 void
393 dkim_errx(struct dkim_message *message, char *msg)
395 message->err = 1;
396 fprintf(stderr, "%s\n", msg);
399 void
400 dkim_parse_header(struct dkim_message *message, char *line, int force)
402 size_t i;
403 size_t r, w;
404 size_t linelen;
405 size_t lastheader;
406 size_t hlen;
407 int fieldname = 0;
408 char **mtmp;
409 char *htmp;
410 char *tmp;
412 if (addheaders == 2 && !force &&
413 !dkim_signature_printheader(message, line))
414 return;
416 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
417 return;
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')
424 hlen++;
425 if (line[hlen] != ':')
426 continue;
427 break;
430 if (i == nsign_headers && !force)
431 return;
434 if (addheaders == 1 && !force &&
435 !dkim_signature_printheader(message, line))
436 return;
438 if (canonheader == CANON_RELAXED) {
439 if (!message->lastheader)
440 fieldname = 1;
441 for (r = w = 0; line[r] != '\0'; r++) {
442 if (line[r] == ':' && fieldname) {
443 if (w > 0 && line[w - 1] == ' ')
444 line[w - 1] = ':';
445 else
446 line[w++] = ':';
447 fieldname = 0;
448 while (line[r + 1] == ' ' ||
449 line[r + 1] == '\t')
450 r++;
451 continue;
453 if (line[r] == ' ' || line[r] == '\t' ||
454 line[r] == '\r' || line[r] == '\n') {
455 if (r != 0 && w != 0 && line[w - 1] == ' ')
456 continue;
457 else
458 line[w++] = ' ';
459 } else if (fieldname) {
460 line[w++] = tolower(line[r]);
461 continue;
462 } else
463 line[w++] = line[r];
465 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
466 line[linelen] = '\0';
467 } else
468 linelen = strlen(line);
470 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
471 continue;
472 if (!message->lastheader) {
473 mtmp = recallocarray(message->headers, lastheader + 1,
474 lastheader + 2, sizeof(*mtmp));
475 if (mtmp == NULL) {
476 dkim_err(message, "Can't store header");
477 return;
479 message->headers = mtmp;
481 message->headers[lastheader] = strdup(line);
482 message->headers[lastheader + 1 ] = NULL;
483 message->lastheader = 1;
484 } else {
485 lastheader--;
486 linelen += strlen(message->headers[lastheader]);
487 if (canonheader == CANON_SIMPLE)
488 linelen += 2;
489 linelen++;
490 htmp = reallocarray(message->headers[lastheader], linelen,
491 sizeof(*htmp));
492 if (htmp == NULL) {
493 dkim_err(message, "Can't store header");
494 return;
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 &&
502 tmp[1] == '\0')
503 line++;
505 if (strlcat(htmp, line, linelen) >= linelen)
506 osmtpd_errx(1, "Missized header");
510 void
511 dkim_parse_body(struct dkim_message *message, char *line)
513 size_t r, w;
514 size_t linelen;
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] == ' ')
520 continue;
521 else
522 line[w++] = ' ';
523 } else
524 line[w++] = line[r];
526 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
527 line[linelen] = '\0';
528 } else
529 linelen = strlen(line);
531 if (line[0] == '\0') {
532 message->body_whitelines++;
533 return;
536 while (message->body_whitelines--) {
537 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
538 dkim_errx(message, "Can't update hash context");
539 return;
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");
548 return;
552 void
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];
559 char *b;
560 const char *sdomain = domain[0], *tsdomain;
561 time_t now;
562 ssize_t i;
563 size_t linelen = 0;
564 char *tmp, *tmp2;
565 int digestsz;
567 if (addtime || addexpire)
568 now = time(NULL);
569 if (addtime && !dkim_signature_printf(message, "t=%lld; ",
570 (long long)now))
571 goto fail;
572 if (addexpire != 0 && !dkim_signature_printf(message, "x=%lld; ",
573 now + addexpire < now ? INT64_MAX : now + addexpire))
574 goto fail;
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");
579 goto fail;
582 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0) {
583 dkim_errx(message, "Can't finalize hash context");
584 goto fail;
586 EVP_EncodeBlock(digest, bdigest, digestsz);
587 if (!dkim_signature_printf(message, "bh=%s; h=", digest))
588 goto fail;
589 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
590 for (i = 0; message->headers[i] != NULL; i++)
591 continue;
592 EVP_MD_CTX_reset(message->dctx);
593 if (!sephash) {
594 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
595 pkey) != 1) {
596 dkim_errx(message, "Failed to initialize signature "
597 "context");
598 goto fail;
600 } else {
601 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1) {
602 dkim_errx(message, "Failed to initialize hash context");
603 goto fail;
606 for (i--; i >= 0; i--) {
607 if (!sephash) {
608 if (EVP_DigestSignUpdate(message->dctx,
609 message->headers[i],
610 strlen(message->headers[i])) != 1 ||
611 EVP_DigestSignUpdate(message->dctx, "\r\n",
612 2) <= 0) {
613 dkim_errx(message, "Failed to update signature "
614 "context");
615 goto fail;
617 } else {
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 "
622 "context");
623 goto fail;
626 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
627 sdomain = tsdomain;
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')
631 break;
632 tmp[0] = tolower(tmp[0]);
634 tmp[0] = '\0';
635 if (!dkim_signature_printf(message, "%s%s",
636 message->headers[i + 1] == NULL ? "" : ":",
637 message->headers[i]))
638 goto fail;
640 dkim_signature_printf(message, "; d=%s; b=", sdomain);
641 if (!dkim_signature_normalize(message))
642 goto fail;
643 if ((tmp = strdup(message->signature.signature)) == NULL) {
644 dkim_err(message, "Can't create DKIM signature");
645 goto fail;
647 dkim_parse_header(message, tmp, 1);
648 if (!sephash) {
649 if (EVP_DigestSignUpdate(message->dctx, tmp,
650 strlen(tmp)) != 1) {
651 dkim_errx(message, "Failed to update signature "
652 "context");
653 goto fail;
655 } else {
656 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1) {
657 dkim_errx(message, "Failed to update digest context");
658 goto fail;
661 free(tmp);
662 if (!sephash) {
663 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1) {
664 dkim_errx(message, "Can't finalize signature context");
665 goto fail;
667 #ifdef HAVE_ED25519
668 } else {
669 if (EVP_DigestFinal_ex(message->dctx, bdigest,
670 &digestsz) != 1) {
671 dkim_errx(message, "Can't finalize hash context");
672 goto fail;
674 EVP_MD_CTX_reset(message->dctx);
675 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
676 pkey) != 1) {
677 dkim_errx(message, "Failed to initialize signature "
678 "context");
679 goto fail;
681 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
682 digestsz) != 1) {
683 dkim_errx(message, "Failed to finalize signature");
684 goto fail;
686 #endif
688 if ((tmp = malloc(linelen)) == NULL) {
689 dkim_err(message, "Can't allocate space for signature");
690 goto fail;
692 if (!sephash) {
693 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1) {
694 dkim_errx(message, "Failed to finalize signature");
695 goto fail;
697 #ifdef HAVE_ED25519
698 } else {
699 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
700 digestsz) != 1) {
701 dkim_errx(message, "Failed to finalize signature");
702 goto fail;
704 #endif
706 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL) {
707 dkim_err(message, "Can't create DKIM signature");
708 goto fail;
710 EVP_EncodeBlock(b, tmp, linelen);
711 free(tmp);
712 dkim_signature_printf(message, "%s\r\n", b);
713 free(b);
714 dkim_signature_normalize(message);
715 tmp = message->signature.signature;
716 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
717 tmp2[0] = '\0';
718 osmtpd_filter_dataline(ctx, "%s", tmp);
719 tmp = tmp2 + 2;
721 tmp = NULL;
722 linelen = 0;
723 rewind(message->origf);
724 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
725 tmp[i - 1] = '\0';
726 osmtpd_filter_dataline(ctx, "%s", tmp);
728 free(tmp);
729 return;
730 fail:
731 osmtpd_filter_dataline(ctx, ".");
734 int
735 dkim_signature_normalize(struct dkim_message *message)
737 size_t i;
738 size_t linelen;
739 size_t checkpoint;
740 size_t skip;
741 size_t *headerlen = &(message->signature.len);
742 int headername = 1;
743 char tag = '\0';
744 char *sig = message->signature.signature;
746 for (linelen = i = 0; sig[i] != '\0'; i++) {
747 if (sig[i] == '\r' && sig[i + 1] == '\n') {
748 i++;
749 checkpoint = 0;
750 linelen = 0;
751 continue;
753 if (sig[i] == '\t')
754 linelen = (linelen + 8) & ~7;
755 else
756 linelen++;
757 if (headername) {
758 if (sig[i] == ':') {
759 headername = 0;
760 checkpoint = i;
762 continue;
764 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
765 for (skip = checkpoint + 1;
766 sig[skip] == ' ' || sig[skip] == '\t';
767 skip++)
768 continue;
769 skip -= checkpoint + 1;
770 if (!dkim_signature_need(message,
771 skip > 3 ? 0 : 3 - skip + 1))
772 return 0;
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';
781 linelen = 8;
782 *headerlen = *headerlen + 3 - skip;
783 i = checkpoint + 3;
784 checkpoint = 0;
786 if (sig[i] == ';') {
787 checkpoint = i;
788 tag = '\0';
789 continue;
791 switch (tag) {
792 case 'B':
793 case 'b':
794 case 'z':
795 checkpoint = i;
796 break;
797 case 'h':
798 if (sig[i] == ':')
799 checkpoint = i;
800 break;
802 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
803 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
804 sig[i + 2] == '=') {
805 tag = 'B';
806 linelen += 2;
807 i += 2;
808 } else
809 tag = sig[i];
812 return 1;
815 int
816 dkim_signature_printheader(struct dkim_message *message, const char *header)
818 size_t i, j, len;
819 static char *fmtheader = NULL;
820 char *tmp;
821 static size_t size = 0;
822 int first;
824 len = strlen(header);
825 if ((len + 3) * 3 < len) {
826 errno = EOVERFLOW;
827 dkim_err(message, "Can't add z-component to header");
828 return 0;
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");
833 return 0;
835 fmtheader = tmp;
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];
848 else {
849 fmtheader[j++] = '=';
850 (void) sprintf(fmtheader + j, "%02hhX", header[i]);
851 j++;
854 (void) sprintf(fmtheader + j, "=%02hhX=%02hhX", (unsigned char) '\r',
855 (unsigned char) '\n');
857 return dkim_signature_printf(message, "%s", fmtheader);
860 int
861 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
863 struct dkim_signature *sig = &(message->signature);
864 va_list ap;
865 size_t len;
867 va_start(ap, fmt);
868 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
869 fmt, ap)) >= sig->size - sig->len) {
870 va_end(ap);
871 if (!dkim_signature_need(message, len + 1))
872 return 0;
873 va_start(ap, fmt);
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");
878 sig->len += len;
879 va_end(ap);
880 return 1;
883 const char *
884 dkim_domain_select(struct dkim_message *message, char *from)
886 char *mdomain0, *mdomain;
887 size_t i;
889 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL) {
890 if (errno != EINVAL) {
891 dkim_errx(message, "Couldn't parse from header");
892 return NULL;
894 return NULL;
897 while (mdomain != NULL && mdomain[0] != '\0') {
898 for (i = 0; i < ndomains; i++) {
899 if (strcasecmp(mdomain, domain[i]) == 0) {
900 free(mdomain0);
901 return domain[i];
904 if ((mdomain = strchr(mdomain, '.')) != NULL)
905 mdomain++;
907 free(mdomain0);
908 return NULL;
911 int
912 dkim_signature_need(struct dkim_message *message, size_t len)
914 struct dkim_signature *sig = &(message->signature);
915 char *tmp;
917 if (sig->len + len < sig->size)
918 return 1;
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");
922 return 0;
924 sig->signature = tmp;
925 return 1;
928 __dead void
929 usage(void)
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");
934 exit(1);