2 * Copyright (c) 2022 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 <sys/types.h>
17 #include <sys/socket.h>
19 #include <openssl/evp.h>
20 #include <openssl/pem.h>
21 #include <openssl/sha.h>
22 #include <openssl/err.h>
24 #include <arpa/nameser.h>
31 #include <opensmtpd.h>
40 #include "unpack_dns.h"
44 * Use RFC8601 (Authentication-Results) codes instead of RFC6376 codes,
45 * since they're more expressive.
58 struct header *header;
60 const char *state_reason;
71 #define HEADER_B_MAX_LEN 8
72 char bheaderclean[HEADER_B_MAX_LEN + 1];
73 /* Make sure padding bits for base64 decoding fit */
74 char bh[EVP_MAX_MD_SIZE + (3 - (EVP_MAX_MD_SIZE % 3))];
78 #define CANON_HEADER_SIMPLE 0
79 #define CANON_HEADER_RELAXED 1
80 #define CANON_HEADER 1
81 #define CANON_BODY_SIMPLE 0
82 #define CANON_BODY_RELAXED 1 << 1
83 #define CANON_BODY 1 << 1
84 #define CANON_DONE 1 << 2
85 char d[HOST_NAME_MAX + 1];
91 char s[HOST_NAME_MAX + 1];
92 time_t t; /* Signature t=/timestamp */
95 int kt; /* Key t=/Flags */
98 struct event_asr *query;
108 struct signature *sig;
111 #define AUTHENTICATION_RESULTS_LINELEN 78
112 #define MIN(a, b) ((a) < (b) ? (a) : (b))
115 struct osmtpd_ctx *ctx;
118 size_t body_whitelines;
120 struct header *header;
127 void dkim_err(struct message *, char *);
128 void dkim_errx(struct message *, char *);
129 void dkim_conf(const char *, const char *);
130 void dkim_dataline(struct osmtpd_ctx *, const char *);
131 void dkim_commit(struct osmtpd_ctx *);
132 void *dkim_message_new(struct osmtpd_ctx *);
133 void dkim_message_free(struct osmtpd_ctx *, void *);
134 void dkim_header_add(struct osmtpd_ctx *, const char *);
135 void dkim_signature_parse(struct header *);
136 void dkim_signature_parse_v(struct signature *, const char *, const char *);
137 void dkim_signature_parse_a(struct signature *, const char *, const char *);
138 void dkim_signature_parse_b(struct signature *, const char *, const char *);
139 void dkim_signature_parse_bh(struct signature *, const char *, const char *);
140 void dkim_signature_parse_c(struct signature *, const char *, const char *);
141 void dkim_signature_parse_d(struct signature *, const char *, const char *);
142 void dkim_signature_parse_h(struct signature *, const char *, const char *);
143 void dkim_signature_parse_i(struct signature *, const char *, const char *);
144 void dkim_signature_parse_l(struct signature *, const char *, const char *);
145 void dkim_signature_parse_q(struct signature *, const char *, const char *);
146 void dkim_signature_parse_s(struct signature *, const char *, const char *);
147 void dkim_signature_parse_t(struct signature *, const char *, const char *);
148 void dkim_signature_parse_x(struct signature *, const char *, const char *);
149 void dkim_signature_parse_z(struct signature *, const char *, const char *);
150 void dkim_signature_verify(struct signature *);
151 void dkim_signature_header(EVP_MD_CTX *, struct signature *, struct header *);
152 void dkim_signature_state(struct signature *, enum state, const char *);
153 const char *dkim_state2str(enum state);
154 void dkim_header_cat(struct osmtpd_ctx *, const char *);
155 void dkim_body_parse(struct message *, const char *);
156 void dkim_body_verify(struct signature *);
157 void dkim_rr_resolve(struct asr_result *, void *);
158 void dkim_message_verify(struct message *);
159 ssize_t dkim_ar_cat(char **ar, size_t *n, size_t aroff, const char *fmt, ...)
160 __attribute__((__format__ (printf, 4, 5)));
161 int dkim_ar_print(struct osmtpd_ctx *, const char *);
162 int dkim_key_text_parse(struct signature *, const char *);
165 EVP_ENCODE_CTX *ectx = NULL;
168 main(int argc, char *argv[])
171 osmtpd_errx(1, "Invalid argument count");
173 OpenSSL_add_all_digests();
175 if (pledge("tmppath stdio dns", NULL) == -1)
176 osmtpd_err(1, "pledge");
178 if ((ectx = EVP_ENCODE_CTX_new()) == NULL)
179 osmtpd_err(1, "EVP_ENCODE_CTX_new");
181 osmtpd_register_conf(dkim_conf);
182 osmtpd_register_filter_dataline(dkim_dataline);
183 osmtpd_register_filter_commit(dkim_commit);
184 osmtpd_local_message(dkim_message_new, dkim_message_free);
191 dkim_conf(const char *key, const char *value)
196 if (authservid == NULL)
197 osmtpd_errx(1, "Didn't receive admd config option");
200 if (strcmp(key, "admd") == 0 && authservid == NULL) {
201 if ((authservid = strdup(value)) == NULL)
202 osmtpd_err(1, "malloc");
203 end = osmtpd_ltok_skip_value(authservid, 0);
204 if (authservid + strlen(authservid) != end)
205 osmtpd_errx(1, "Invalid authservid");
210 dkim_dataline(struct osmtpd_ctx *ctx, const char *line)
212 struct message *msg = ctx->local_message;
216 if (line[0] == '.' && line[1] =='\0') {
218 osmtpd_filter_dataline(ctx, ".");
223 if (fprintf(msg->origf, "%s\n", line) < 0) {
224 dkim_err(msg, "Couldn't write to tempfile");
227 if (line[0] == '.') {
229 if (line[0] == '\0') {
231 for (i = 0; i < msg->nheaders; i++) {
232 if (msg->header[i].sig == NULL)
234 dkim_body_verify(msg->header[i].sig);
236 dkim_message_verify(msg);
240 if (msg->parsing_headers) {
241 dkim_header_add(ctx, line);
242 if (line[0] == '\0') {
243 msg->parsing_headers = 0;
244 for (i = 0; i < msg->nheaders; i++) {
245 if (msg->header[i].sig == NULL)
247 if (msg->header[i].sig->query == NULL)
248 dkim_signature_verify(
254 dkim_body_parse(msg, line);
259 dkim_commit(struct osmtpd_ctx *ctx)
261 struct message *msg = ctx->local_message;
264 osmtpd_filter_disconnect(ctx, "Internal server error");
266 osmtpd_filter_proceed(ctx);
270 dkim_message_new(struct osmtpd_ctx *ctx)
274 if ((msg = malloc(sizeof(*msg))) == NULL)
277 if ((msg->origf = tmpfile()) == NULL) {
278 dkim_err(msg, "Can't open tempfile");
283 msg->parsing_headers = 1;
284 msg->body_whitelines = 0;
295 dkim_message_free(struct osmtpd_ctx *ctx, void *data)
297 struct message *msg = data;
301 for (i = 0; i < msg->nheaders; i++) {
302 if (msg->header[i].sig != NULL) {
303 free(msg->header[i].sig->b);
304 EVP_MD_CTX_free(msg->header[i].sig->bhctx);
305 for (j = 0; msg->header[i].sig->h != NULL &&
306 msg->header[i].sig->h[j] != NULL; j++)
307 free(msg->header[i].sig->h[j]);
308 free(msg->header[i].sig->h);
309 EVP_PKEY_free(msg->header[i].sig->p);
311 free(msg->header[i].buf);
312 free(msg->header[i].sig);
319 dkim_header_add(struct osmtpd_ctx *ctx, const char *line)
321 struct message *msg = ctx->local_message;
322 const char *start, *end, *verify;
323 struct header *headers;
326 if (msg->nheaders > 0 &&
327 msg->header[msg->nheaders - 1].readdone == 0) {
328 if (line[0] != ' ' && line[0] != '\t') {
329 msg->header[msg->nheaders - 1].readdone = 1;
330 start = msg->header[msg->nheaders - 1].buf;
331 end = osmtpd_ltok_skip_field_name(start, 0);
332 /* In case someone uses an obs-optional */
334 verify = osmtpd_ltok_skip_wsp(end, 1);
337 start, "DKIM-Signature", end - start) == 0 &&
339 dkim_signature_parse(
340 &msg->header[msg->nheaders - 1]);
344 dkim_header_cat(ctx, line);
348 if (msg->nheaders % 10 == 0) {
349 if ((headers = recallocarray(msg->header, msg->nheaders,
350 msg->nheaders + 10, sizeof(*msg->header))) == NULL) {
351 dkim_err(msg, "malloc");
354 msg->header = headers;
355 for (i = 0; i < msg->nheaders; i++) {
356 if (msg->header[i].sig == NULL)
358 msg->header[i].sig->header = &msg->header[i];
361 msg->header[msg->nheaders].msg = msg;
363 dkim_header_cat(ctx, line);
367 dkim_header_cat(struct osmtpd_ctx *ctx, const char *line)
369 struct message *msg = ctx->local_message;
370 struct header *header = &msg->header[msg->nheaders - 1];
373 size_t needed = header->buflen + strlen(line) + 2;
375 if (needed > (header->buflen / 1024) + 1) {
376 buf = reallocarray(header->buf, (needed / 1024) + 1, 1024);
378 dkim_err(msg, "malloc");
383 header->buflen += snprintf(header->buf + header->buflen,
384 (((needed / 1024) + 1) * 1024) - header->buflen, "%s%s",
385 header->buflen == 0 ? "" : "\r\n", line);
389 dkim_signature_parse(struct header *header)
391 struct signature *sig;
392 struct asr_query *query;
393 const char *buf, *i, *end;
395 char subdomain[HOST_NAME_MAX + 1];
398 /* Format checked by dkim_header_add */
399 buf = osmtpd_ltok_skip_field_name(header->buf, 0);
400 buf = osmtpd_ltok_skip_wsp(buf, 1) + 1;
402 if ((header->sig = calloc(1, sizeof(*header->sig))) == NULL) {
403 dkim_err(header->msg, "malloc");
407 sig->header = header;
412 end = osmtpd_ltok_skip_tag_list(buf, 0);
413 if (end == NULL || end[0] != '\0') {
414 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid tag-list");
418 while (buf[0] != '\0') {
419 buf = osmtpd_ltok_skip_fws(buf, 1);
420 end = osmtpd_ltok_skip_tag_name(buf, 0);
422 /* Unknown tag-name */
423 if ((size_t)(end - buf) >= sizeof(tagname))
426 strlcpy(tagname, buf, (end - buf) + 1);
427 buf = osmtpd_ltok_skip_fws(end, 1);
429 buf = osmtpd_ltok_skip_fws(buf + 1, 1);
430 end = osmtpd_ltok_skip_tag_value(buf, 1);
431 if (strcmp(tagname, "v") == 0)
432 dkim_signature_parse_v(sig, buf, end);
433 else if (strcmp(tagname, "a") == 0)
434 dkim_signature_parse_a(sig, buf, end);
435 else if (strcmp(tagname, "b") == 0)
436 dkim_signature_parse_b(sig, buf, end);
437 else if (strcmp(tagname, "bh") == 0)
438 dkim_signature_parse_bh(sig, buf, end);
439 else if (strcmp(tagname, "c") == 0)
440 dkim_signature_parse_c(sig, buf, end);
441 else if (strcmp(tagname, "d") == 0)
442 dkim_signature_parse_d(sig, buf, end);
443 else if (strcmp(tagname, "h") == 0)
444 dkim_signature_parse_h(sig, buf, end);
445 else if (strcmp(tagname, "i") == 0)
446 dkim_signature_parse_i(sig, buf, end);
447 else if (strcmp(tagname, "l") == 0)
448 dkim_signature_parse_l(sig, buf, end);
449 else if (strcmp(tagname, "q") == 0)
450 dkim_signature_parse_q(sig, buf, end);
451 else if (strcmp(tagname, "s") == 0)
452 dkim_signature_parse_s(sig, buf, end);
453 else if (strcmp(tagname, "t") == 0)
454 dkim_signature_parse_t(sig, buf, end);
455 else if (strcmp(tagname, "x") == 0)
456 dkim_signature_parse_x(sig, buf, end);
457 else if (strcmp(tagname, "z") == 0)
458 dkim_signature_parse_z(sig, buf, end);
460 buf = osmtpd_ltok_skip_fws(end, 1);
463 else if (buf[0] != '\0') {
464 dkim_signature_state(sig, DKIM_PERMERROR,
469 if (sig->state != DKIM_UNKNOWN)
473 dkim_signature_state(sig, DKIM_PERMERROR, "Missing v tag");
474 else if (sig->ah == NULL)
475 dkim_signature_state(sig, DKIM_PERMERROR, "Missing a tag");
476 else if (sig->b == NULL)
477 dkim_signature_state(sig, DKIM_PERMERROR, "Missing b tag");
478 else if (sig->bhsz == 0)
479 dkim_signature_state(sig, DKIM_PERMERROR, "Missing bh tag");
480 else if (sig->d[0] == '\0')
481 dkim_signature_state(sig, DKIM_PERMERROR, "Missing d tag");
482 else if (sig->h == NULL)
483 dkim_signature_state(sig, DKIM_PERMERROR, "Missing h tag");
484 else if (sig->s[0] == '\0')
485 dkim_signature_state(sig, DKIM_PERMERROR, "Missing s tag");
486 if (sig->state != DKIM_UNKNOWN)
489 if (sig->i != NULL) {
490 i = osmtpd_ltok_skip_local_part(sig->i, 1) + 1;
491 ilen = sig->isz - (size_t)(i - sig->i);
492 dlen = strlen(sig->d);
494 dkim_signature_state(sig, DKIM_PERMERROR,
495 "i tag not subdomain of d");
499 if ((i[-1] != '.' && i[-1] != '@') ||
500 strncasecmp(i, sig->d, dlen) != 0) {
501 dkim_signature_state(sig, DKIM_PERMERROR,
502 "i tag not subdomain of d");
506 if (sig->t != -1 && sig->x != -1 && sig->t > sig->x) {
507 dkim_signature_state(sig, DKIM_PERMERROR, "t tag after x tag");
511 if ((size_t)snprintf(subdomain, sizeof(subdomain), "%s._domainkey.%s",
512 sig->s, sig->d) >= sizeof(subdomain)) {
513 dkim_signature_state(sig, DKIM_PERMERROR,
514 "dns/txt query too long");
518 if ((query = res_query_async(subdomain, C_IN, T_TXT, NULL)) == NULL) {
519 dkim_err(header->msg, "res_query_async");
522 if ((sig->query = event_asr_run(query, dkim_rr_resolve, sig)) == NULL) {
523 dkim_err(header->msg, "event_asr_run");
530 dkim_signature_parse_v(struct signature *sig, const char *start, const char *end)
532 if (sig->v != 0) { /* Duplicate tag */
533 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate v tag");
536 /* Unsupported version */
537 if (start[0] != '1' || start + 1 != end)
538 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsupported v tag");
544 dkim_signature_parse_a(struct signature *sig, const char *start, const char *end)
546 char ah[sizeof("sha256")];
548 if (sig->ah != NULL) {
549 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate a tag");
553 if (osmtpd_ltok_skip_sig_a_tag_alg(start, 0) != end) {
554 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid a tag");
558 sig->asz = (size_t)(end - start);
559 if (strncmp(start, "rsa-", 4) == 0) {
561 sig->ak = EVP_PKEY_RSA;
564 } else if (strncmp(start, "ed25519-", 8) == 0) {
566 sig->ak = EVP_PKEY_ED25519;
570 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag k");
573 if ((size_t)(end - start) >= sizeof(ah)) {
574 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag h");
577 strlcpy(ah, start, sizeof(ah));
578 ah[end - start] = '\0';
579 if ((sig->ah = EVP_get_digestbyname(ah)) == NULL) {
580 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag h");
583 if ((sig->bhctx = EVP_MD_CTX_new()) == NULL) {
584 dkim_err(sig->header->msg, "EVP_MD_CTX_new");
587 if (EVP_DigestInit_ex(sig->bhctx, sig->ah, NULL) <= 0) {
588 dkim_err(sig->header->msg, "EVP_DigestInit_ex");
594 dkim_signature_parse_b(struct signature *sig, const char *start, const char *end)
599 if (sig->b != NULL) {
600 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate b tag");
603 sig->bheader = start;
604 sig->bheadersz = end - start;
605 if ((sig->b = malloc(((sig->bheadersz / 4) + 1) * 3)) == NULL)
606 osmtpd_err(1, "malloc");
607 /* EVP_DecodeBlock doesn't handle internal whitespace */
608 EVP_DecodeInit(ectx);
609 if (EVP_DecodeUpdate(ectx, sig->b, &decodesz, sig->bheader,
610 (int) sig->bheadersz) == -1) {
611 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid b tag");
615 if (EVP_DecodeFinal(ectx, sig->b + sig->bsz,
617 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid b tag");
620 sig->bsz += decodesz;
622 i < sig->bheadersz && j < HEADER_B_MAX_LEN; i++) {
623 if (isalnum(sig->bheader[i]) || sig->bheader[i] == '/'
624 || sig->bheader[i] == '+' || sig->bheader[i] == '=')
625 sig->bheaderclean[j++] = sig->bheader[i];
627 sig->bheaderclean[j] = '\0';
631 dkim_signature_parse_bh(struct signature *sig, const char *start, const char *end)
637 if (sig->bhsz != 0) {
638 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate bh tag");
642 * EVP_Decode* expects sig->bh to be large enough,
643 * so count the actual b64 characters.
648 b64 = osmtpd_ltok_skip_fws(b64, 1);
649 if (osmtpd_ltok_skip_alphadigitps(b64, 0) == NULL)
656 b64 = osmtpd_ltok_skip_fws(b64 + 1, 1);
662 /* Invalid tag value */
663 if (b64 != end || n % 4 != 0 || (n / 4) * 3 > sizeof(sig->bh)) {
664 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
667 /* EVP_DecodeBlock doesn't handle internal whitespace */
668 EVP_DecodeInit(ectx);
669 if (EVP_DecodeUpdate(ectx, sig->bh, &decodesz, start,
670 (int)(end - start)) == -1) {
672 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
675 sig->bhsz = decodesz;
676 if (EVP_DecodeFinal(ectx, sig->bh + sig->bhsz, &decodesz) == -1) {
678 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
681 sig->bhsz += decodesz;
685 dkim_signature_parse_c(struct signature *sig, const char *start, const char *end)
688 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate c tag");
691 if (strncmp(start, "simple", 6) == 0) {
692 sig->c = CANON_HEADER_SIMPLE;
694 } else if (strncmp(start, "relaxed", 7) == 0) {
695 sig->c = CANON_HEADER_RELAXED;
698 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid c tag");
701 if (start[0] == '/') {
703 if (strncmp(start, "simple", 6) == 0) {
704 sig->c |= CANON_BODY_SIMPLE;
706 } else if (strncmp(start, "relaxed", 7) == 0) {
707 sig->c |= CANON_BODY_RELAXED;
710 dkim_signature_state(sig, DKIM_PERMERROR,
717 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid c tag");
720 sig->c |= CANON_DONE;
724 dkim_signature_parse_d(struct signature *sig, const char *start, const char *end)
726 if (sig->d[0] != '\0') {
727 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate d tag");
730 if (osmtpd_ltok_skip_sig_d_tag_value(start, 0) != end ||
731 (size_t)(end - start) >= sizeof(sig->d)) {
732 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid d tag");
735 strlcpy(sig->d, start, end - start + 1);
739 dkim_signature_parse_h(struct signature *sig, const char *start, const char *end)
744 if (sig->h != NULL) {
745 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate h tag");
748 if (osmtpd_ltok_skip_sig_h_tag_value(start, 0) < end) {
749 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid h tag");
754 if ((h = osmtpd_ltok_skip_hdr_name(h, 0)) == NULL) {
755 dkim_signature_state(sig, DKIM_PERMERROR,
760 /* ';' is part of hdr-name */
765 h = osmtpd_ltok_skip_fws(h, 1);
768 h = osmtpd_ltok_skip_fws(h + 1, 1);
770 if ((sig->h = calloc(n + 1, sizeof(*sig->h))) == NULL) {
771 dkim_err(sig->header->msg, "malloc");
777 h = osmtpd_ltok_skip_hdr_name(start, 0);
778 /* ';' is part of hdr-name */
780 sig->h[n] = strndup(start, end - start);
783 if ((sig->h[n++] = strndup(start, h - start)) == NULL) {
784 dkim_err(sig->header->msg, "malloc");
787 start = osmtpd_ltok_skip_fws(h, 1);
790 start = osmtpd_ltok_skip_fws(start + 1, 1);
795 dkim_signature_parse_i(struct signature *sig, const char *start, const char *end)
797 if (sig->i != NULL) {
798 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate i tag");
801 if (osmtpd_ltok_skip_sig_i_tag_value(start, 0) != end) {
802 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid i tag");
806 sig->isz = (size_t)(end - start);
810 dkim_signature_parse_l(struct signature *sig, const char *start, const char *end)
815 if (sig->l != -1) { /* Duplicate tag */
816 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate l tag");
820 l = strtoll(start, &lend, 10);
821 /* > 76 digits in stroll is an overflow */
822 if (osmtpd_ltok_skip_digit(start, 0) == NULL ||
823 lend != end || errno != 0) {
824 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid l tag");
828 dkim_signature_state(sig, DKIM_PERMERROR, "l tag too large");
835 dkim_signature_parse_q(struct signature *sig, const char *start, const char *end)
840 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate q tag");
845 start = osmtpd_ltok_skip_fws(start, 1);
846 qend = osmtpd_ltok_skip_sig_q_tag_method(start, 0);
848 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid q tag");
851 if (strncmp(start, "dns/txt", qend - start) == 0)
853 start = osmtpd_ltok_skip_fws(qend, 1);
858 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid q tag");
863 dkim_signature_state(sig, DKIM_NEUTRAL, "No useable q found");
869 dkim_signature_parse_s(struct signature *sig, const char *start, const char *end)
871 if (sig->s[0] != '\0') {
872 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate s tag");
875 if (osmtpd_ltok_skip_selector(start, 0) != end) {
876 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid s tag");
879 strlcpy(sig->s, start, end - start + 1);
883 dkim_signature_parse_t(struct signature *sig, const char *start, const char *end)
888 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate t tag");
892 sig->t = strtoll(start, &tend, 10);
893 if (osmtpd_ltok_skip_digit(start, 0) == NULL || tend != end ||
894 tend - start > 12 || errno != 0) {
895 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid t tag");
901 dkim_signature_parse_x(struct signature *sig, const char *start, const char *end)
906 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate x tag");
910 sig->x = strtoll(start, &xend, 10);
911 if (osmtpd_ltok_skip_digit(start, 0) == NULL || xend != end ||
912 xend - start > 12 || errno != 0) {
913 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid x tag");
919 dkim_signature_parse_z(struct signature *sig, const char *start, const char *end)
922 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate z tag");
927 if (osmtpd_ltok_skip_sig_z_tag_value(start, 0) != end) {
928 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid z tag");
934 dkim_signature_verify(struct signature *sig)
936 struct message *msg = sig->header->msg;
937 static EVP_MD_CTX *bctx = NULL;
938 char digest[EVP_MAX_MD_SIZE];
939 unsigned int digestsz;
943 if (sig->state != DKIM_UNKNOWN)
947 if ((bctx = EVP_MD_CTX_new()) == NULL) {
948 dkim_errx(msg, "EVP_MD_CTX_new");
952 EVP_MD_CTX_reset(bctx);
954 if (EVP_DigestVerifyInit(bctx, NULL, sig->ah, NULL,
956 dkim_errx(msg, "EVP_DigestVerifyInit");
960 if (EVP_DigestInit_ex(bctx, sig->ah, NULL) != 1) {
961 dkim_errx(msg, "EVP_DigestInit_ex");
966 for (i = 0; i < msg->nheaders; i++)
967 msg->header[i].parsed = 0;
969 for (header = 0; sig->h[header] != NULL; header++) {
970 for (i = msg->nheaders; i > 0; ) {
972 if (msg->header[i].parsed ||
973 strncasecmp(msg->header[i].buf, sig->h[header],
974 strlen(sig->h[header])) != 0 ||
975 msg->header[i].sig == sig)
977 end = osmtpd_ltok_skip_fws(
978 msg->header[i].buf + strlen(sig->h[header]), 1);
981 dkim_signature_header(bctx, sig, &(msg->header[i]));
982 msg->header[i].parsed = 1;
986 dkim_signature_header(bctx, sig, sig->header);
988 if (EVP_DigestVerifyFinal(bctx, sig->b, sig->bsz) != 1)
989 dkim_signature_state(sig, DKIM_FAIL, "b mismatch");
991 if (EVP_DigestFinal_ex(bctx, digest, &digestsz) == 0) {
992 dkim_errx(msg, "EVP_DigestFinal_ex");
995 if (EVP_DigestVerifyInit(bctx, NULL, NULL, NULL, sig->p) != 1) {
996 dkim_errx(msg, "EVP_DigestVerifyInit");
999 switch (EVP_DigestVerify(bctx, sig->b, sig->bsz, digest,
1004 dkim_signature_state(sig, DKIM_FAIL, "b mismatch");
1007 dkim_errx(msg, "EVP_DigestVerify");
1013 /* EVP_DigestVerifyUpdate is a macro, so we can't alias this on a variable */
1014 #define dkim_b_digest_update(a, b, c) \
1015 (sig->sephash ? EVP_DigestUpdate((a), (b), (c)) :\
1016 EVP_DigestVerifyUpdate((a), (b), (c)))
1019 dkim_signature_header(EVP_MD_CTX *bctx, struct signature *sig,
1020 struct header *header)
1023 const char *ptr = header->buf, *end;
1025 int canon = sig->c & CANON_HEADER;
1027 for (ptr = header->buf; ptr[0] != '\0'; ptr++) {
1029 if (canon == CANON_HEADER_RELAXED) {
1030 ptr = osmtpd_ltok_skip_fws(ptr, 1);
1031 c = tolower(ptr[0]);
1036 if (canon == CANON_HEADER_RELAXED)
1037 ptr = osmtpd_ltok_skip_fws(
1040 if (dkim_b_digest_update(bctx, &c, 1) == 0) {
1041 dkim_errx(sig->header->msg,
1042 "dkim_b_digest_update");
1047 end = osmtpd_ltok_skip_fws(ptr, 1);
1049 if (sig->header == header && ptr == sig->bheader) {
1050 ptr = osmtpd_ltok_skip_tag_value(
1054 if (dkim_b_digest_update(bctx, ptr, 1) == 0) {
1055 dkim_errx(sig->header->msg,
1056 "dkim_b_digest_update");
1060 if (canon == CANON_HEADER_RELAXED) {
1063 if (dkim_b_digest_update(bctx, " ", 1) == 0) {
1064 dkim_errx(sig->header->msg,
1065 "dkim_b_digest_update");
1069 if (dkim_b_digest_update(bctx, ptr,
1071 dkim_errx(sig->header->msg,
1072 "dkim_b_digest_update");
1080 if (sig->header != header) {
1081 if (dkim_b_digest_update(bctx, "\r\n", 2) == 0) {
1082 dkim_errx(sig->header->msg, "dkim_b_digest_update");
1089 dkim_signature_state(struct signature *sig, enum state state,
1092 if (sig->query != NULL) {
1093 event_asr_abort(sig->query);
1096 switch (sig->state) {
1101 osmtpd_errx(1, "Unexpected transition");
1103 if (state == DKIM_PASS)
1107 if (state == DKIM_PASS)
1109 if (state == DKIM_TEMPERROR || state == DKIM_PERMERROR)
1111 osmtpd_errx(1, "Unexpected transition");
1112 case DKIM_TEMPERROR:
1113 if (state == DKIM_PERMERROR)
1116 case DKIM_PERMERROR:
1120 sig->state_reason = reason;
1124 dkim_state2str(enum state state)
1138 case DKIM_TEMPERROR:
1140 case DKIM_PERMERROR:
1146 dkim_rr_resolve(struct asr_result *ar, void *arg)
1148 struct signature *sig = arg;
1149 char key[UINT16_MAX + 1];
1151 size_t keylen, cstrlen;
1153 struct dns_header h;
1159 if (ar->ar_h_errno == TRY_AGAIN || ar->ar_h_errno == NO_RECOVERY) {
1160 dkim_signature_state(sig, DKIM_TEMPERROR,
1161 hstrerror(ar->ar_h_errno));
1164 if (ar->ar_h_errno != NETDB_SUCCESS) {
1165 dkim_signature_state(sig, DKIM_PERMERROR,
1166 hstrerror(ar->ar_h_errno));
1170 unpack_init(&pack, ar->ar_data, ar->ar_datalen);
1171 if (unpack_header(&pack, &h) != 0 ||
1172 unpack_query(&pack, &q) != 0) {
1173 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid dns/txt");
1176 for (; h.ancount > 0; h.ancount--) {
1177 unpack_rr(&pack, &rr);
1178 if (rr.rr_type != T_TXT)
1182 rr_txt = rr.rr.other.rdata;
1183 while (rr.rr.other.rdlen > 0) {
1184 cstrlen = ((const unsigned char *)rr_txt)[0];
1185 if (cstrlen >= rr.rr.other.rdlen ||
1186 keylen + cstrlen >= sizeof(key))
1189 * RFC 6376 Section 3.6.2.2
1190 * Strings in a TXT RR MUST be concatenated together
1191 * before use with no intervening whitespace.
1193 strlcpy(key + keylen, rr_txt + 1, cstrlen + 1);
1194 rr.rr.other.rdlen -= (cstrlen + 1);
1195 rr_txt += (cstrlen + 1);
1198 if (rr.rr.other.rdlen > 0) /* Invalid TXT RDATA */
1201 if (dkim_key_text_parse(sig, key))
1205 if (h.ancount == 0) {
1206 dkim_signature_state(sig, DKIM_PERMERROR,
1207 "No matching key found");
1209 /* Only verify if all headers have been read */
1210 if (!sig->header->msg->parsing_headers)
1211 dkim_signature_verify(sig);
1215 dkim_message_verify(sig->header->msg);
1219 dkim_key_text_parse(struct signature *sig, const char *key)
1221 char tagname, *hashname;
1222 const char *end, *tagvend;
1223 char pkraw[UINT16_MAX] = "", pkimp[UINT16_MAX];
1224 size_t pkrawlen = 0, pkoff, linelen;
1225 int h = 0, k = 0, n = 0, p = 0, s = 0, t = 0, first = 1;
1232 key = osmtpd_ltok_skip_fws(key, 1);
1233 /* Validate syntax early */
1234 if ((end = osmtpd_ltok_skip_tag_list(key, 0)) == NULL)
1237 while (key[0] != '\0') {
1238 key = osmtpd_ltok_skip_fws(key, 1);
1239 if ((end = osmtpd_ltok_skip_tag_name(key, 0)) == NULL)
1242 if ((size_t)(end - key) != 1)
1246 key = osmtpd_ltok_skip_fws(end, 1);
1250 key = osmtpd_ltok_skip_fws(key + 1, 1);
1251 if ((end = osmtpd_ltok_skip_tag_value(key, 0)) == NULL)
1256 * RFC 6376 section 3.6.1, v=:
1257 * RECOMMENDED...This tag MUST be the first tag in the
1261 osmtpd_ltok_skip_key_v_tag_value(key, 0) != end)
1266 if (h != 0) /* Duplicate tag */
1268 /* Invalid tag value */
1269 if (osmtpd_ltok_skip_key_h_tag_value(key, 0) != end)
1272 if ((tagvend = osmtpd_ltok_skip_key_h_tag_alg(
1275 hashname = strndup(key, tagvend - key);
1276 if (hashname == NULL) {
1277 dkim_err(sig->header->msg, "malloc");
1280 if (EVP_get_digestbyname(hashname) == sig->ah) {
1286 key = osmtpd_ltok_skip_fws(tagvend, 1);
1289 key = osmtpd_ltok_skip_fws(key + 1, 1);
1296 if (k != 0) /* Duplicate tag */
1299 if (strncmp(key, "rsa", end - key) == 0) {
1300 if (sig->ak != EVP_PKEY_RSA)
1303 } else if (strncmp(key, "ed25519", end - key) == 0) {
1304 if (sig->ak != EVP_PKEY_ED25519)
1312 if (n != 0) /* Duplicate tag */
1315 /* semicolon is part of safe-char */
1316 if (osmtpd_ltok_skip_key_n_tag_value(key, 0) < end)
1321 if (p != 0) /* Duplicate tag */
1325 key = osmtpd_ltok_skip_fws(key, 1);
1326 if (osmtpd_ltok_skip_alphadigitps(
1329 pkraw[pkrawlen++] = key++[0];
1330 if (pkrawlen >= sizeof(pkraw))
1333 if (key[0] == '=') {
1334 pkraw[pkrawlen++] = '=';
1335 key = osmtpd_ltok_skip_fws(key + 1, 1);
1336 if (pkrawlen >= sizeof(pkraw))
1338 if (key[0] == '=') {
1339 pkraw[pkrawlen++] = '=';
1341 if (pkrawlen >= sizeof(pkraw))
1345 /* Invalid tag value */
1346 if (pkrawlen % 4 != 0 || key != end)
1350 if (s != 0) /* Duplicate tag */
1352 /* Invalid tag value */
1353 if (osmtpd_ltok_skip_key_s_tag_value(key, 0) != end)
1357 osmtpd_ltok_skip_key_s_tag_type(
1360 if (strncmp(key, "*", tagvend - key) == 0 ||
1361 strncmp(key, "email", tagvend - key) == 0) {
1365 key = osmtpd_ltok_skip_fws(tagvend, 1);
1368 key = osmtpd_ltok_skip_fws(key + 1, 1);
1375 if (t != 0) /* Duplicate tag */
1378 if (osmtpd_ltok_skip_key_t_tag_value(key, 0) != end)
1381 tagvend = osmtpd_ltok_skip_key_t_tag_flag(
1383 if (strncmp(key, "y", tagvend - key) == 0)
1385 else if (strncmp(key, "s", tagvend - key) == 0)
1387 key = osmtpd_ltok_skip_fws(tagvend, 1);
1390 key = osmtpd_ltok_skip_fws(key + 1, 1);
1399 key = osmtpd_ltok_skip_fws(key, 1);
1402 else if (key[0] != '\0')
1406 if (!p) /* Missing tag */
1408 if (k == 0 && sig->ak != EVP_PKEY_RSA) /* Default to RSA */
1411 if (pkraw[0] == '\0') {
1412 dkim_signature_state(sig, DKIM_PERMERROR, "Key is revoked");
1418 pkoff = strlcpy(pkimp, "-----BEGIN PUBLIC KEY-----\n",
1421 for (key = pkraw; key[0] != '\0';) {
1422 if (pkoff + 2 >= sizeof(pkimp))
1424 pkimp[pkoff++] = key++[0];
1425 if (++linelen == 64) {
1426 pkimp[pkoff++] = '\n';
1430 /* Leverage pkoff check in loop */
1432 pkimp[pkoff++] = '\n';
1433 /* PEM_read_bio_PUBKEY will catch truncated keys */
1434 pkoff += strlcpy(pkimp + pkoff, "-----END PUBLIC KEY-----\n",
1435 sizeof(pkimp) - pkoff);
1436 if ((bio = BIO_new_mem_buf(pkimp, pkoff)) == NULL) {
1437 dkim_err(sig->header->msg, "BIO_new_mem_buf");
1440 sig->p = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);
1444 case EVP_PKEY_ED25519:
1445 if ((pkrawlen / 4) * 3 >= sizeof(pkimp))
1447 EVP_DecodeInit(ectx);
1448 if (EVP_DecodeUpdate(ectx, pkimp, &tmp, pkraw, pkrawlen) == -1)
1451 if (EVP_DecodeFinal(ectx, pkimp, &tmp) == -1)
1454 sig->p = EVP_PKEY_new_raw_public_key(sig->ak, NULL, pkimp,
1459 if (sig->p == NULL) {
1461 * XXX No clue how to differentiate between invalid key and
1462 * temporary failure like *alloc.
1463 * Assume invalid key, because it's more likely.
1471 dkim_body_parse(struct message *msg, const char *line)
1473 struct signature *sig;
1474 const char *end = line, *hash, *prev;
1475 size_t hashn, len, i;
1478 if (line[0] == '\0') {
1479 msg->body_whitelines++;
1483 while (msg->body_whitelines-- > 0) {
1484 for (i = 0; i < msg->nheaders; i++) {
1485 if ((sig = msg->header[i].sig) == NULL ||
1486 sig->state != DKIM_UNKNOWN)
1488 hashn = sig->l == -1 ? 2 : MIN(2, sig->l);
1489 sig->l -= sig->l == -1 ? 0 : hashn;
1490 if (EVP_DigestUpdate(sig->bhctx, "\r\n", hashn) == 0) {
1491 dkim_errx(msg, "EVP_DigestUpdate");
1496 msg->body_whitelines = 0;
1499 while (line[0] != '\0') {
1502 if ((end = osmtpd_ltok_skip_wsp(end, 0)) == NULL)
1508 while (osmtpd_ltok_skip_wsp(end, 0) == NULL &&
1512 for (i = 0; i < msg->nheaders; i++) {
1513 sig = msg->header[i].sig;
1514 if (sig == NULL || sig->state != DKIM_UNKNOWN)
1517 (sig->c & CANON_BODY) == CANON_BODY_RELAXED) {
1519 len = end[0] == '\0' ? 0 : 1;
1522 len = (size_t)(end - line);
1524 hashn = sig->l == -1 ? len : MIN(len, (size_t)sig->l);
1525 sig->l -= sig->l == -1 ? 0 : hashn;
1526 ret = EVP_DigestUpdate(sig->bhctx, hash, hashn);
1528 dkim_errx(msg, "EVP_DigestUpdate");
1534 for (i = 0; i < msg->nheaders; i++) {
1535 sig = msg->header[i].sig;
1536 if (sig == NULL || sig->state != DKIM_UNKNOWN)
1538 hashn = sig->l == -1 ? 2 : MIN(2, sig->l);
1539 sig->l -= sig->l == -1 ? 0 : hashn;
1540 ret = EVP_DigestUpdate(sig->bhctx, "\r\n", hashn);
1542 dkim_errx(msg, "EVP_DigestUpdate");
1549 dkim_body_verify(struct signature *sig)
1551 unsigned char digest[EVP_MAX_MD_SIZE];
1552 unsigned int digestsz;
1554 if (sig->state != DKIM_UNKNOWN)
1557 if ((sig->c & CANON_BODY) == CANON_BODY_SIMPLE &&
1558 !sig->header->msg->has_body) {
1559 if (EVP_DigestUpdate(sig->bhctx, "\r\n",
1560 sig->l == -1 ? 2 : MIN(2, sig->l)) <= 0) {
1561 dkim_errx(sig->header->msg,
1562 "Can't update hash context");
1567 dkim_signature_state(sig, DKIM_PERMERROR,
1568 "l tag larger than body");
1572 if (EVP_DigestFinal_ex(sig->bhctx, digest, &digestsz) == 0) {
1573 dkim_errx(sig->header->msg, "EVP_DigestFinal_ex");
1577 if (digestsz != sig->bhsz || memcmp(digest, sig->bh, digestsz) != 0)
1578 dkim_signature_state(sig, DKIM_FAIL, "bh mismatch");
1582 dkim_message_verify(struct message *msg)
1584 struct signature *sig;
1586 ssize_t n, aroff = 0;
1594 for (i = 0; i < msg->nheaders; i++) {
1595 if (msg->header[i].sig == NULL)
1597 if (msg->header[i].sig->query != NULL)
1599 if (msg->header[i].sig->state != DKIM_UNKNOWN)
1601 dkim_signature_state(msg->header[i].sig, DKIM_PASS, NULL);
1604 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1605 "Authentication-Results: %s", authservid)) == -1) {
1606 dkim_err(msg, "malloc");
1609 for (i = 0; i < msg->nheaders; i++) {
1610 sig = msg->header[i].sig;
1614 if ((aroff = dkim_ar_cat(&line, &linelen, aroff, "; dkim=%s",
1615 dkim_state2str(sig->state))) == -1) {
1616 dkim_err(msg, "malloc");
1619 if (sig->state_reason != NULL) {
1620 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1621 " reason=\"%s\"", sig->state_reason)) == -1) {
1622 dkim_err(msg, "malloc");
1626 if (sig->s[0] != '\0') {
1627 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1628 " header.s=%s", sig->s)) == -1) {
1629 dkim_err(msg, "malloc");
1633 if (sig->d[0] != '\0') {
1634 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1635 " header.d=%s", sig->d)) == -1) {
1636 dkim_err(msg, "malloc");
1641 * Don't print i-tag, since localpart can be a quoted-string,
1642 * which can contain FWS and CFWS.
1644 if (sig->a != NULL) {
1645 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1646 " header.a=%.*s", (int)sig->asz, sig->a)) == -1) {
1647 dkim_err(msg, "malloc");
1651 if (sig->bheaderclean[0] != '\0') {
1652 if ((aroff = dkim_ar_cat(&line, &linelen, aroff,
1653 " header.b=%s", sig->bheaderclean)) == -1) {
1654 dkim_err(msg, "malloc");
1660 aroff = dkim_ar_cat(&line, &linelen, aroff, "; dkim=none");
1662 dkim_err(msg, "malloc");
1666 if (dkim_ar_print(msg->ctx, line) != 0) {
1667 dkim_err(msg, "Mallformed AR header");
1672 while ((n = getline(&line, &linelen, msg->origf)) != -1) {
1674 osmtpd_filter_dataline(msg->ctx, "%s", line);
1676 if (ferror(msg->origf))
1677 dkim_err(msg, "getline");
1684 dkim_ar_print(struct osmtpd_ctx *ctx, const char *start)
1686 const char *scan, *checkpoint, *ncheckpoint;
1687 int arlen = 0, first = 1, arid = 1;
1690 ncheckpoint = osmtpd_ltok_skip_hdr_name(start, 0) + 1;
1691 for (scan = start; scan[0] != '\0'; scan++) {
1692 if (scan[0] == '\t')
1693 arlen = (arlen + 8) & ~7;
1696 if (arlen >= AUTHENTICATION_RESULTS_LINELEN) {
1697 arlen = (int)(checkpoint - start);
1699 arlen = (int)(ncheckpoint - start);
1700 checkpoint = ncheckpoint;
1702 osmtpd_filter_dataline(ctx, "%s%.*s", first ? "" : "\t",
1704 start = osmtpd_ltok_skip_cfws(checkpoint, 1);
1707 ncheckpoint = start;
1712 if (scan == ncheckpoint) {
1713 checkpoint = ncheckpoint;
1714 ncheckpoint = osmtpd_ltok_skip_cfws(ncheckpoint, 1);
1717 ncheckpoint = osmtpd_ltok_skip_value(
1721 } else if (strncmp(ncheckpoint, "dkim=",
1722 sizeof("dkim=") - 1) == 0) {
1723 ncheckpoint = osmtpd_ltok_skip_keyword(
1724 ncheckpoint + sizeof("dkim=") - 1, 0);
1726 } else if (strncmp(ncheckpoint, "reason=",
1727 sizeof("reason=") - 1) == 0) {
1728 ncheckpoint = osmtpd_ltok_skip_ar_reasonspec(
1732 ncheckpoint = osmtpd_ltok_skip_ar_propspec(
1736 if (ncheckpoint == NULL)
1739 if (*ncheckpoint == ';')
1743 osmtpd_filter_dataline(ctx, "%s%s", first ? "" : "\t", start);
1748 dkim_ar_cat(char **ar, size_t *n, size_t aroff, const char *fmt, ...)
1756 size = vsnprintf(*ar + aroff, *n - aroff, fmt, ap);
1758 if (size + aroff < *n)
1759 return (ssize_t)size + aroff;
1760 nn = (((aroff + size) / 256) + 1) * 256;
1761 artmp = realloc(*ar, nn);
1767 size = vsnprintf(*ar + aroff, *n - aroff, fmt, ap);
1769 return (ssize_t)size + aroff;
1773 dkim_err(struct message *msg, char *text)
1776 fprintf(stderr, "%s: %s\n", text, strerror(errno));
1780 dkim_errx(struct message *msg, char *text)
1783 fprintf(stderr, "%s\n", text);
1789 fprintf(stderr, "usage: filter-dkimverify\n");