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_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 *);
121 int
122 main(int argc, char *argv[])
124 int ch;
125 FILE *file;
126 char *line;
127 size_t linesz;
128 ssize_t linelen;
129 const char *errstr;
131 while ((ch = getopt(argc, argv, "a:c:D:d:h:k:s:tx:z")) != -1) {
132 switch (ch) {
133 case 'a':
134 if (strncmp(optarg, "rsa-", 4) == 0) {
135 cryptalg = "rsa";
136 hashalg = optarg + 4;
137 keyid = EVP_PKEY_RSA;
138 sephash = 0;
139 #ifdef HAVE_ED25519
140 } else if (strncmp(optarg, "ed25519-", 8) == 0) {
141 hashalg = optarg + 8;
142 cryptalg = "ed25519";
143 keyid = EVP_PKEY_ED25519;
144 sephash = 1;
145 #endif
146 } else
147 osmtpd_errx(1, "invalid algorithm");
148 break;
149 case 'c':
150 if (strncmp(optarg, "simple", 6) == 0) {
151 canonheader = CANON_SIMPLE;
152 optarg += 6;
153 } else if (strncmp(optarg, "relaxed", 7) == 0) {
154 canonheader = CANON_RELAXED;
155 optarg += 7;
156 } else
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;
163 else
164 osmtpd_err(1,
165 "Invalid canonicalization");
166 } else if (optarg[0] == '\0')
167 canonbody = CANON_SIMPLE;
168 else
169 osmtpd_err(1, "Invalid canonicalization");
170 break;
171 case 'D':
172 if ((file = fopen(optarg, "r")) == NULL)
173 osmtpd_err(1, "Can't open domain file (%s)",
174 optarg);
175 do {
176 line = NULL;
177 linesz = 0;
178 linelen = getline(&line, &linesz, file);
179 if (linelen > 0) {
180 if (line[linelen - 1] == '\n')
181 line[linelen - 1] = '\0';
182 dkim_adddomain(line);
184 } while (linelen != -1);
185 if (ferror(file))
186 osmtpd_err(1, "Error reading domain file (%s)",
187 optarg);
188 fclose(file);
189 break;
190 case 'd':
191 dkim_adddomain(optarg);
192 break;
193 case 'h':
194 dkim_headers_set(optarg);
195 break;
196 case 'k':
197 if ((file = fopen(optarg, "r")) == NULL)
198 osmtpd_err(1, "Can't open key file (%s)",
199 optarg);
200 pkey = PEM_read_PrivateKey(file, NULL, NULL, NULL);
201 if (pkey == NULL)
202 osmtpd_errx(1, "Can't read key file");
203 fclose(file);
204 break;
205 case 's':
206 selector = optarg;
207 break;
208 case 't':
209 addtime = 1;
210 break;
211 case 'x':
212 addexpire = strtonum(optarg, 1, INT64_MAX, &errstr);
213 if (addexpire == 0)
214 osmtpd_errx(1, "Expire offset is %s", errstr);
215 break;
216 case 'z':
217 addheaders++;
218 break;
219 default:
220 usage();
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)
233 usage();
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);
241 osmtpd_run();
243 return 0;
246 void
247 dkim_adddomain(char *d)
249 domain = reallocarray(domain, ndomains + 1, sizeof(*domain));
250 if (domain == NULL)
251 osmtpd_err(1, "malloc");
252 domain[ndomains++] = d;
256 void
257 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
259 struct dkim_message *message = ctx->local_message;
260 char *linedup;
261 size_t linelen;
263 if (message->err) {
264 if (line[0] == '.' && line[1] =='\0')
265 osmtpd_filter_dataline(ctx, ".");
266 return;
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') {
274 dkim_sign(ctx);
275 } else if (linelen != 0 && message->parsing_headers) {
276 if (line[0] == '.')
277 line++;
278 if ((linedup = strdup(line)) == NULL)
279 osmtpd_err(1, "strdup");
280 dkim_parse_header(message, linedup, 0);
281 free(linedup);
282 } else if (linelen == 0 && message->parsing_headers) {
283 if (addheaders > 0 && !dkim_signature_printf(message, "; "))
284 return;
285 message->parsing_headers = 0;
286 } else {
287 if (line[0] == '.')
288 line++;
289 if ((linedup = strdup(line)) == NULL)
290 osmtpd_err(1, "strdup");
291 dkim_parse_body(message, linedup);
292 free(linedup);
296 void
297 dkim_commit(struct osmtpd_ctx *ctx)
299 struct dkim_message *message = ctx->local_message;
301 if (message->err)
302 osmtpd_filter_disconnect(ctx, "Internal server error");
303 else
304 osmtpd_filter_proceed(ctx);
307 void *
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");
314 return NULL;
317 if ((message->origf = tmpfile()) == NULL) {
318 dkim_err(message, "Failed to open tempfile");
319 goto fail;
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");
327 goto fail;
329 message->lastheader = 0;
330 message->signature.signature = NULL;
331 message->signature.size = 0;
332 message->signature.len = 0;
333 message->err = 0;
335 if (!dkim_signature_printf(message,
336 "DKIM-Signature: v=%s; a=%s-%s; c=%s/%s; s=%s; ", "1",
337 cryptalg, hashalg,
338 canonheader == CANON_SIMPLE ? "simple" : "relaxed",
339 canonbody == CANON_SIMPLE ? "simple" : "relaxed", selector))
340 goto fail;
341 if (addheaders > 0 && !dkim_signature_printf(message, "z="))
342 goto fail;
344 if ((message->dctx = EVP_MD_CTX_new()) == NULL) {
345 dkim_errx(message, "Failed to create hash context");
346 goto fail;
348 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) <= 0) {
349 dkim_errx(message, "Failed to initialize hash context");
350 goto fail;
352 return message;
353 fail:
354 dkim_message_free(ctx, message);
355 return NULL;
358 void
359 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
361 struct dkim_message *message = data;
362 size_t i;
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);
371 free(message);
374 void
375 dkim_headers_set(char *headers)
377 size_t i;
378 int has_from = 0;
380 nsign_headers = 1;
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");
390 nsign_headers++;
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, ':');
405 headers++[0] = '\0';
407 if (strcasecmp(sign_headers[i], "from") == 0)
408 has_from = 1;
410 if (!has_from)
411 osmtpd_errx(1, "From header must be included");
414 void
415 dkim_err(struct dkim_message *message, char *msg)
417 message->err = 1;
418 fprintf(stderr, "%s: %s\n", msg, strerror(errno));
421 void
422 dkim_errx(struct dkim_message *message, char *msg)
424 message->err = 1;
425 fprintf(stderr, "%s\n", msg);
428 void
429 dkim_parse_header(struct dkim_message *message, char *line, int force)
431 size_t i;
432 size_t r, w;
433 size_t linelen;
434 size_t lastheader;
435 size_t hlen;
436 int fieldname = 0;
437 char **mtmp;
438 char *htmp;
439 char *tmp;
441 if (addheaders == 2 && !force &&
442 !dkim_signature_printheader(message, line))
443 return;
445 if ((line[0] == ' ' || line[0] == '\t') && !message->lastheader)
446 return;
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')
453 hlen++;
454 if (line[hlen] != ':')
455 continue;
456 break;
459 if (i == nsign_headers && !force)
460 return;
463 if (addheaders == 1 && !force &&
464 !dkim_signature_printheader(message, line))
465 return;
467 if (canonheader == CANON_RELAXED) {
468 if (!message->lastheader)
469 fieldname = 1;
470 for (r = w = 0; line[r] != '\0'; r++) {
471 if (line[r] == ':' && fieldname) {
472 if (w > 0 && line[w - 1] == ' ')
473 line[w - 1] = ':';
474 else
475 line[w++] = ':';
476 fieldname = 0;
477 while (line[r + 1] == ' ' ||
478 line[r + 1] == '\t')
479 r++;
480 continue;
482 if (line[r] == ' ' || line[r] == '\t' ||
483 line[r] == '\r' || line[r] == '\n') {
484 if (r != 0 && w != 0 && line[w - 1] == ' ')
485 continue;
486 else
487 line[w++] = ' ';
488 } else if (fieldname) {
489 line[w++] = tolower(line[r]);
490 continue;
491 } else
492 line[w++] = line[r];
494 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
495 line[linelen] = '\0';
496 } else
497 linelen = strlen(line);
499 for (lastheader = 0; message->headers[lastheader] != NULL; lastheader++)
500 continue;
501 if (!message->lastheader) {
502 mtmp = recallocarray(message->headers, lastheader + 1,
503 lastheader + 2, sizeof(*mtmp));
504 if (mtmp == NULL) {
505 dkim_err(message, "Can't store header");
506 return;
508 message->headers = mtmp;
510 if ((message->headers[lastheader] = strdup(line)) == NULL) {
511 dkim_err(message, "Can't store header");
512 return;
514 message->headers[lastheader + 1 ] = NULL;
515 message->lastheader = 1;
516 } else {
517 lastheader--;
518 linelen += strlen(message->headers[lastheader]);
519 if (canonheader == CANON_SIMPLE)
520 linelen += 2;
521 linelen++;
522 htmp = reallocarray(message->headers[lastheader], linelen,
523 sizeof(*htmp));
524 if (htmp == NULL) {
525 dkim_err(message, "Can't store header");
526 return;
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 &&
534 tmp[1] == '\0')
535 line++;
537 if (strlcat(htmp, line, linelen) >= linelen)
538 osmtpd_errx(1, "Missized header");
542 void
543 dkim_parse_body(struct dkim_message *message, char *line)
545 size_t r, w;
546 size_t linelen;
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] == ' ')
552 continue;
553 else
554 line[w++] = ' ';
555 } else
556 line[w++] = line[r];
558 linelen = (w != 0 && line[w - 1] == ' ') ? w - 1 : w;
559 line[linelen] = '\0';
560 } else
561 linelen = strlen(line);
563 if (line[0] == '\0') {
564 message->body_whitelines++;
565 return;
568 while (message->body_whitelines--) {
569 if (EVP_DigestUpdate(message->dctx, "\r\n", 2) == 0) {
570 dkim_errx(message, "Can't update hash context");
571 return;
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");
580 return;
584 void
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];
591 unsigned char *b;
592 const char *sdomain = domain[0], *tsdomain;
593 time_t now;
594 ssize_t i;
595 size_t linelen = 0;
596 char *tmp, *tmp2;
597 unsigned int digestsz;
599 if (addtime || addexpire)
600 now = time(NULL);
601 if (addtime && !dkim_signature_printf(message, "t=%lld; ",
602 (long long)now))
603 goto fail;
604 if (addexpire != 0 && !dkim_signature_printf(message, "x=%lld; ",
605 now + addexpire < now ? INT64_MAX : now + addexpire))
606 goto fail;
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");
611 goto fail;
614 if (EVP_DigestFinal_ex(message->dctx, bdigest, &digestsz) == 0) {
615 dkim_errx(message, "Can't finalize hash context");
616 goto fail;
618 EVP_EncodeBlock(digest, bdigest, digestsz);
619 if (!dkim_signature_printf(message, "bh=%s; h=", digest))
620 goto fail;
621 /* Reverse order for ease of use of RFC6367 section 5.4.2 */
622 for (i = 0; message->headers[i] != NULL; i++)
623 continue;
624 EVP_MD_CTX_reset(message->dctx);
625 if (!sephash) {
626 if (EVP_DigestSignInit(message->dctx, NULL, hash_md, NULL,
627 pkey) != 1) {
628 dkim_errx(message, "Failed to initialize signature "
629 "context");
630 goto fail;
632 } else {
633 if (EVP_DigestInit_ex(message->dctx, hash_md, NULL) != 1) {
634 dkim_errx(message, "Failed to initialize hash context");
635 goto fail;
638 for (i--; i >= 0; i--) {
639 if (!sephash) {
640 if (EVP_DigestSignUpdate(message->dctx,
641 message->headers[i],
642 strlen(message->headers[i])) != 1 ||
643 EVP_DigestSignUpdate(message->dctx, "\r\n",
644 2) <= 0) {
645 dkim_errx(message, "Failed to update signature "
646 "context");
647 goto fail;
649 } else {
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 "
654 "context");
655 goto fail;
658 if ((tsdomain = dkim_domain_select(message, message->headers[i])) != NULL)
659 sdomain = tsdomain;
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')
663 break;
664 tmp[0] = tolower(tmp[0]);
666 tmp[0] = '\0';
667 if (!dkim_signature_printf(message, "%s%s",
668 message->headers[i + 1] == NULL ? "" : ":",
669 message->headers[i]))
670 goto fail;
672 dkim_signature_printf(message, "; d=%s; b=", sdomain);
673 if (!dkim_signature_normalize(message))
674 goto fail;
675 if ((tmp = strdup(message->signature.signature)) == NULL) {
676 dkim_err(message, "Can't create DKIM signature");
677 goto fail;
679 dkim_parse_header(message, tmp, 1);
680 if (!sephash) {
681 if (EVP_DigestSignUpdate(message->dctx, tmp,
682 strlen(tmp)) != 1) {
683 dkim_errx(message, "Failed to update signature "
684 "context");
685 goto fail;
687 } else {
688 if (EVP_DigestUpdate(message->dctx, tmp, strlen(tmp)) != 1) {
689 dkim_errx(message, "Failed to update digest context");
690 goto fail;
693 free(tmp);
694 if (!sephash) {
695 if (EVP_DigestSignFinal(message->dctx, NULL, &linelen) != 1) {
696 dkim_errx(message, "Can't finalize signature context");
697 goto fail;
699 #ifdef HAVE_ED25519
700 } else {
701 if (EVP_DigestFinal_ex(message->dctx, bdigest,
702 &digestsz) != 1) {
703 dkim_errx(message, "Can't finalize hash context");
704 goto fail;
706 EVP_MD_CTX_reset(message->dctx);
707 if (EVP_DigestSignInit(message->dctx, NULL, NULL, NULL,
708 pkey) != 1) {
709 dkim_errx(message, "Failed to initialize signature "
710 "context");
711 goto fail;
713 if (EVP_DigestSign(message->dctx, NULL, &linelen, bdigest,
714 digestsz) != 1) {
715 dkim_errx(message, "Failed to finalize signature");
716 goto fail;
718 #endif
720 if ((tmp = malloc(linelen)) == NULL) {
721 dkim_err(message, "Can't allocate space for signature");
722 goto fail;
724 if (!sephash) {
725 if (EVP_DigestSignFinal(message->dctx, tmp, &linelen) != 1) {
726 dkim_errx(message, "Failed to finalize signature");
727 goto fail;
729 #ifdef HAVE_ED25519
730 } else {
731 if (EVP_DigestSign(message->dctx, tmp, &linelen, bdigest,
732 digestsz) != 1) {
733 dkim_errx(message, "Failed to finalize signature");
734 goto fail;
736 #endif
738 if ((b = malloc((((linelen + 2) / 3) * 4) + 1)) == NULL) {
739 dkim_err(message, "Can't create DKIM signature");
740 goto fail;
742 EVP_EncodeBlock(b, tmp, linelen);
743 free(tmp);
744 dkim_signature_printf(message, "%s\r\n", b);
745 free(b);
746 dkim_signature_normalize(message);
747 tmp = message->signature.signature;
748 while ((tmp2 = strchr(tmp, '\r')) != NULL) {
749 tmp2[0] = '\0';
750 osmtpd_filter_dataline(ctx, "%s", tmp);
751 tmp = tmp2 + 2;
753 tmp = NULL;
754 linelen = 0;
755 rewind(message->origf);
756 while ((i = getline(&tmp, &linelen, message->origf)) != -1) {
757 tmp[i - 1] = '\0';
758 osmtpd_filter_dataline(ctx, "%s", tmp);
760 free(tmp);
761 return;
762 fail:
763 osmtpd_filter_dataline(ctx, ".");
766 int
767 dkim_signature_normalize(struct dkim_message *message)
769 size_t i;
770 size_t linelen;
771 size_t checkpoint;
772 size_t skip;
773 size_t *headerlen = &(message->signature.len);
774 int headername = 1;
775 char tag = '\0';
776 char *sig = message->signature.signature;
778 for (linelen = i = 0; sig[i] != '\0'; i++) {
779 if (sig[i] == '\r' && sig[i + 1] == '\n') {
780 i++;
781 checkpoint = 0;
782 linelen = 0;
783 continue;
785 if (sig[i] == '\t')
786 linelen = (linelen + 8) & ~7;
787 else
788 linelen++;
789 if (headername) {
790 if (sig[i] == ':') {
791 headername = 0;
792 checkpoint = i;
794 continue;
796 if (linelen > DKIM_SIGNATURE_LINELEN && checkpoint != 0) {
797 for (skip = checkpoint + 1;
798 sig[skip] == ' ' || sig[skip] == '\t';
799 skip++)
800 continue;
801 skip -= checkpoint + 1;
802 if (!dkim_signature_need(message,
803 skip > 3 ? 0 : 3 - skip + 1))
804 return 0;
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';
813 linelen = 8;
814 *headerlen = *headerlen + 3 - skip;
815 i = checkpoint + 3;
816 checkpoint = 0;
818 if (sig[i] == ';') {
819 checkpoint = i;
820 tag = '\0';
821 continue;
823 switch (tag) {
824 case 'B':
825 case 'b':
826 case 'z':
827 checkpoint = i;
828 break;
829 case 'h':
830 if (sig[i] == ':')
831 checkpoint = i;
832 break;
834 if (tag == '\0' && sig[i] != ' ' && sig[i] != '\t') {
835 if ((tag = sig[i]) == 'b' && sig[i + 1] == 'h' &&
836 sig[i + 2] == '=') {
837 tag = 'B';
838 linelen += 2;
839 i += 2;
840 } else
841 tag = sig[i];
844 return 1;
847 int
848 dkim_signature_printheader(struct dkim_message *message, const char *header)
850 size_t i, j, len;
851 static char *fmtheader = NULL;
852 char *tmp;
853 static size_t size = 0;
854 int first;
856 len = strlen(header);
857 if ((len + 3) * 3 < len) {
858 errno = EOVERFLOW;
859 dkim_err(message, "Can't add z-component to header");
860 return 0;
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");
865 return 0;
867 fmtheader = tmp;
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];
880 else {
881 fmtheader[j++] = '=';
882 (void) sprintf(fmtheader + j, "%02hhX", header[i]);
883 j++;
886 (void) sprintf(fmtheader + j, "=%02hhX=%02hhX", (unsigned char) '\r',
887 (unsigned char) '\n');
889 return dkim_signature_printf(message, "%s", fmtheader);
892 int
893 dkim_signature_printf(struct dkim_message *message, char *fmt, ...)
895 struct dkim_signature *sig = &(message->signature);
896 va_list ap;
897 size_t len;
899 va_start(ap, fmt);
900 if ((len = vsnprintf(sig->signature + sig->len, sig->size - sig->len,
901 fmt, ap)) >= sig->size - sig->len) {
902 va_end(ap);
903 if (!dkim_signature_need(message, len + 1))
904 return 0;
905 va_start(ap, fmt);
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");
910 sig->len += len;
911 va_end(ap);
912 return 1;
915 const char *
916 dkim_domain_select(struct dkim_message *message, char *from)
918 char *mdomain0, *mdomain;
919 size_t i;
921 if ((mdomain = mdomain0 = osmtpd_mheader_from_domain(from)) == NULL) {
922 if (errno != EINVAL) {
923 dkim_errx(message, "Couldn't parse from header");
924 return NULL;
926 return NULL;
929 while (mdomain != NULL && mdomain[0] != '\0') {
930 for (i = 0; i < ndomains; i++) {
931 if (strcasecmp(mdomain, domain[i]) == 0) {
932 free(mdomain0);
933 return domain[i];
936 if ((mdomain = strchr(mdomain, '.')) != NULL)
937 mdomain++;
939 free(mdomain0);
940 return NULL;
943 int
944 dkim_signature_need(struct dkim_message *message, size_t len)
946 struct dkim_signature *sig = &(message->signature);
947 char *tmp;
949 if (sig->len + len < sig->size)
950 return 1;
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");
954 return 0;
956 sig->signature = tmp;
957 return 1;
960 __dead void
961 usage(void)
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");
966 exit(1);