Blob


1 /*
2 * Copyright (c) 2024 Kirill A. Korinsky <kirill@korins.ky>
3 * Copyright (c) 2022 Martijn van Duren <martijn@openbsd.org>
4 * Copyright (c) 2019 Martijn van Duren <martijn@openbsd.org>
5 * Copyright (c) 2017 Gilles Chehade <gilles@poolp.org>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19 #include <sys/types.h>
20 #include <sys/socket.h>
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include <openssl/sha.h>
25 #include <openssl/err.h>
27 #include <arpa/nameser.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <event.h>
32 #include <limits.h>
33 #include <netdb.h>
34 #include <opensmtpd.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <time.h>
41 #include <unistd.h>
42 #include <asr.h>
44 #include "unpack_dns.h"
45 #include "ltok.h"
47 /*
48 * Use RFC8601 (Authentication-Results) codes instead of RFC6376 codes,
49 * since they're more expressive.
50 */
51 enum dkim_state {
52 DKIM_UNKNOWN,
53 DKIM_PASS,
54 DKIM_FAIL,
55 DKIM_POLICY,
56 DKIM_NEUTRAL,
57 DKIM_TEMPERROR,
58 DKIM_PERMERROR
59 };
61 struct dkim_signature {
62 struct header *header;
63 enum dkim_state state;
64 const char *state_reason;
65 int v;
66 const char *a;
67 size_t asz;
68 int ak;
69 int sephash;
70 const EVP_MD *ah;
71 char *b;
72 size_t bsz;
73 const char *bheader;
74 size_t bheadersz;
75 #define HEADER_B_MAX_LEN 8
76 char bheaderclean[HEADER_B_MAX_LEN + 1];
77 /* Make sure padding bits for base64 decoding fit */
78 char bh[EVP_MAX_MD_SIZE + (3 - (EVP_MAX_MD_SIZE % 3))];
79 size_t bhsz;
80 EVP_MD_CTX *bhctx;
81 int c;
82 #define CANON_HEADER_SIMPLE 0
83 #define CANON_HEADER_RELAXED 1
84 #define CANON_HEADER 1
85 #define CANON_BODY_SIMPLE 0
86 #define CANON_BODY_RELAXED 1 << 1
87 #define CANON_BODY 1 << 1
88 #define CANON_DONE 1 << 2
89 char d[HOST_NAME_MAX + 1];
90 char **h;
91 const char *i;
92 size_t isz;
93 ssize_t l;
94 int q;
95 char s[HOST_NAME_MAX + 1];
96 time_t t; /* Signature t=/timestamp */
97 #define KT_Y 1
98 #define KT_S 1 << 1
99 int kt; /* Key t=/Flags */
100 time_t x;
101 int z;
102 struct event_asr *query;
103 EVP_PKEY *p;
104 /* RFC 6376 doesn't care about CNAME, use simalr with SPF limit */
105 #define DKIM_LOOKUP_LOOKUP_LIMIT 11
106 int nqueries;
107 };
109 /*
110 * Use RFC7601 (Authentication-Results), anyway OpenSMTPD reports only pass or fail
111 */
112 enum iprev_state {
113 IPREV_NONE,
114 IPREV_PASS,
115 IPREV_FAIL
116 };
118 /*
119 * Base on RFC7208
120 */
121 enum spf_state {
122 SPF_NONE,
123 SPF_NEUTRAL,
124 SPF_PASS,
125 SPF_FAIL,
126 SPF_SOFTFAIL,
127 SPF_TEMPERROR,
128 SPF_PERMERROR
129 };
131 /*
132 * RFC 5321 doesn't limit record size, enforce some resanable limit
133 */
134 #define SPF_RECORD_MAX 4096
136 struct spf_query {
137 struct spf_record *spf;
138 struct event_asr *eva;
139 int type;
140 enum spf_state q;
141 int include;
142 int exists;
143 char *domain;
144 char *txt;
145 int pos;
146 };
148 struct spf_record {
149 struct osmtpd_ctx *ctx;
150 enum spf_state state;
151 const char *state_reason;
152 char *sender_local;
153 char *sender_domain;
154 int nqueries;
155 int running;
156 int done;
157 /* RFC 7208 Section 4.6.4 limits to 10 DNS lookup,
158 * and one is reserved for the first query.
159 * To prevent of infinity loop I count each CNAME
160 * as dedicated lookup, same as A and AAAA.
161 * So, I use 41 as the limit. */
162 #define SPF_DNS_LOOKUP_LIMIT 41
163 struct spf_query queries[SPF_DNS_LOOKUP_LIMIT];
164 };
166 struct header {
167 struct message *msg;
168 uint8_t readdone;
169 uint8_t parsed;
170 char *buf;
171 size_t buflen;
172 struct dkim_signature *sig;
173 };
175 #define AUTHENTICATION_RESULTS_LINELEN 78
176 #define MIN(a, b) ((a) < (b) ? (a) : (b))
178 struct message {
179 struct osmtpd_ctx *ctx;
180 FILE *origf;
181 int parsing_headers;
182 size_t body_whitelines;
183 int has_body;
184 struct header *header;
185 size_t nheaders;
186 int readdone;
187 int nqueries;
188 };
190 struct session {
191 struct osmtpd_ctx *ctx;
192 enum iprev_state iprev;
193 struct spf_record *spf_helo;
194 struct spf_record *spf_mailfrom;
195 struct sockaddr_storage src;
196 char *identity;
197 char *rdns;
198 };
200 void usage(void);
201 void auth_conf(const char *, const char *);
202 void auth_connect(struct osmtpd_ctx *, const char *, enum osmtpd_status, struct sockaddr_storage *, struct sockaddr_storage *);
203 void spf_identity(struct osmtpd_ctx *, const char *);
204 void spf_mailfrom(struct osmtpd_ctx *, const char *);
205 void auth_dataline(struct osmtpd_ctx *, const char *);
206 void *spf_record_new(struct osmtpd_ctx *, const char *);
207 void spf_record_free(struct spf_record *);
208 void *auth_session_new(struct osmtpd_ctx *);
209 void auth_session_free(struct osmtpd_ctx *, void *);
210 void *auth_message_new(struct osmtpd_ctx *);
211 void auth_message_free(struct osmtpd_ctx *, void *);
212 void dkim_header_add(struct osmtpd_ctx *, const char *);
213 void dkim_signature_parse(struct header *);
214 void dkim_signature_parse_v(struct dkim_signature *, const char *, const char *);
215 void dkim_signature_parse_a(struct dkim_signature *, const char *, const char *);
216 void dkim_signature_parse_b(struct dkim_signature *, const char *, const char *);
217 void dkim_signature_parse_bh(struct dkim_signature *, const char *, const char *);
218 void dkim_signature_parse_c(struct dkim_signature *, const char *, const char *);
219 void dkim_signature_parse_d(struct dkim_signature *, const char *, const char *);
220 void dkim_signature_parse_h(struct dkim_signature *, const char *, const char *);
221 void dkim_signature_parse_i(struct dkim_signature *, const char *, const char *);
222 void dkim_signature_parse_l(struct dkim_signature *, const char *, const char *);
223 void dkim_signature_parse_q(struct dkim_signature *, const char *, const char *);
224 void dkim_signature_parse_s(struct dkim_signature *, const char *, const char *);
225 void dkim_signature_parse_t(struct dkim_signature *, const char *, const char *);
226 void dkim_signature_parse_x(struct dkim_signature *, const char *, const char *);
227 void dkim_signature_parse_z(struct dkim_signature *, const char *, const char *);
228 void dkim_lookup_record(struct dkim_signature *sig, const char *domain);
229 void dkim_signature_verify(struct dkim_signature *);
230 void dkim_signature_header(EVP_MD_CTX *, struct dkim_signature *, struct header *);
231 void dkim_signature_state(struct dkim_signature *, enum dkim_state, const char *);
232 const char *dkim_state2str(enum dkim_state);
233 void dkim_header_cat(struct osmtpd_ctx *, const char *);
234 void dkim_body_parse(struct message *, const char *);
235 void dkim_body_verify(struct dkim_signature *);
236 void dkim_rr_resolve(struct asr_result *, void *);
237 const char *iprev_state2str(enum iprev_state);
238 char *spf_evaluate_domain(struct spf_record *, const char *);
239 void spf_lookup_record(struct spf_record *, const char *, int,
240 enum spf_state, int, int);
241 void spf_done(struct spf_record *, enum spf_state, const char *);
242 void spf_resolve(struct asr_result *, void *);
243 void spf_resolve_txt(struct dns_rr *, struct spf_query *);
244 void spf_resolve_mx(struct dns_rr *, struct spf_query *);
245 void spf_resolve_a(struct dns_rr *, struct spf_query *);
246 void spf_resolve_aaaa(struct dns_rr *, struct spf_query *);
247 void spf_resolve_cname(struct dns_rr *, struct spf_query *);
248 char* spf_parse_txt(const char *, size_t);
249 int spf_check_cidr(struct spf_record *, struct in_addr *, int );
250 int spf_check_cidr6(struct spf_record *, struct in6_addr *, int );
251 int spf_execute_txt(struct spf_query *);
252 const char *spf_state2str(enum spf_state);
253 int spf_ar_cat(const char *, struct spf_record *, char **, size_t *, ssize_t *);
254 void auth_message_verify(struct message *);
255 void auth_ar_create(struct osmtpd_ctx *);
256 ssize_t auth_ar_cat(char **ar, size_t *n, size_t aroff, const char *fmt, ...)
257 __attribute__((__format__ (printf, 4, 5)));
258 int auth_ar_print(struct osmtpd_ctx *, const char *);
259 int dkim_key_text_parse(struct dkim_signature *, const char *);
261 char *authservid;
262 EVP_ENCODE_CTX *ectx = NULL;
264 int
265 main(int argc, char *argv[])
267 if (argc != 1)
268 osmtpd_errx(1, "Invalid argument count");
270 OpenSSL_add_all_digests();
272 if (pledge("tmppath stdio dns", NULL) == -1)
273 osmtpd_err(1, "pledge");
275 if ((ectx = EVP_ENCODE_CTX_new()) == NULL)
276 osmtpd_err(1, "EVP_ENCODE_CTX_new");
278 osmtpd_need(OSMTPD_NEED_SRC|OSMTPD_NEED_FCRDNS|OSMTPD_NEED_IDENTITY|OSMTPD_NEED_GREETING);
279 osmtpd_register_conf(auth_conf);
280 osmtpd_register_filter_dataline(auth_dataline);
281 osmtpd_register_report_connect(1, auth_connect);
282 osmtpd_register_filter_helo(spf_identity);
283 osmtpd_register_filter_ehlo(spf_identity);
284 osmtpd_register_filter_mailfrom(spf_mailfrom);
285 osmtpd_local_session(auth_session_new, auth_session_free);
286 osmtpd_local_message(auth_message_new, auth_message_free);
287 osmtpd_run();
289 return 0;
292 void
293 auth_conf(const char *key, const char *value)
295 const char *end;
297 if (key == NULL) {
298 if (authservid == NULL)
299 osmtpd_errx(1, "Didn't receive admd config option");
300 return;
302 if (strcmp(key, "admd") == 0 && authservid == NULL) {
303 if ((authservid = strdup(value)) == NULL)
304 osmtpd_err(1, "%s: malloc", __func__);
305 end = osmtpd_ltok_skip_value(authservid, 0);
306 if (authservid + strlen(authservid) != end)
307 osmtpd_errx(1, "Invalid authservid");
311 void
312 auth_connect(struct osmtpd_ctx *ctx, const char *rdns, enum osmtpd_status fcrdns,
313 struct sockaddr_storage *src, struct sockaddr_storage *dst)
315 struct session *ses = ctx->local_session;
317 if (fcrdns == OSMTPD_STATUS_OK)
318 ses->iprev = IPREV_PASS;
319 else
320 ses->iprev = IPREV_FAIL;
322 memcpy(&ses->src, src, sizeof(struct sockaddr_storage));
324 if (rdns != NULL) {
325 if ((ses->rdns = strdup(rdns)) == NULL)
326 osmtpd_err(1, "%s: malloc", __func__);
330 void
331 spf_identity(struct osmtpd_ctx *ctx, const char *identity)
333 char from[HOST_NAME_MAX + 12];
335 struct session *ses = ctx->local_session;
337 if (identity == NULL) {
338 osmtpd_filter_proceed(ctx);
339 return;
342 if ((ses->identity = strdup(identity)) == NULL)
343 osmtpd_err(1, "%s: strdup", __func__);
345 if (strlen(identity) == 0) {
346 osmtpd_filter_proceed(ctx);
347 return;
350 snprintf(from, sizeof(from), "postmaster@%s", identity);
352 if ((ses->spf_helo = spf_record_new(ctx, from)) == NULL)
353 osmtpd_filter_proceed(ctx);
356 void
357 spf_mailfrom(struct osmtpd_ctx *ctx, const char *from)
359 struct session *ses = ctx->local_session;
361 if (from == NULL || !strlen(from)) {
362 osmtpd_filter_proceed(ctx);
363 return;
366 if (ses->spf_mailfrom)
367 spf_record_free(ses->spf_mailfrom);
369 if ((ses->spf_mailfrom = spf_record_new(ctx, from)) == NULL)
370 osmtpd_filter_proceed(ctx);
373 void
374 auth_dataline(struct osmtpd_ctx *ctx, const char *line)
376 struct message *msg = ctx->local_message;
377 size_t i;
379 if (fprintf(msg->origf, "%s\n", line) < 0)
380 osmtpd_err(1, "Couldn't write to tempfile");
382 if (line[0] == '.') {
383 line++;
384 if (line[0] == '\0') {
385 msg->readdone = 1;
386 for (i = 0; i < msg->nheaders; i++) {
387 if (msg->header[i].sig == NULL)
388 continue;
389 dkim_body_verify(msg->header[i].sig);
391 auth_message_verify(msg);
392 return;
395 if (msg->parsing_headers) {
396 dkim_header_add(ctx, line);
397 if (line[0] == '\0') {
398 msg->parsing_headers = 0;
399 for (i = 0; i < msg->nheaders; i++) {
400 if (msg->header[i].sig == NULL)
401 continue;
402 if (msg->header[i].sig->query == NULL)
403 dkim_signature_verify(
404 msg->header[i].sig);
407 return;
408 } else {
409 dkim_body_parse(msg, line);
413 void *
414 spf_record_new(struct osmtpd_ctx *ctx, const char *from)
416 int i;
417 const char *at;
418 struct spf_record *spf;
420 if ((spf = malloc(sizeof(*spf))) == NULL)
421 osmtpd_err(1, "%s: malloc", __func__);
423 spf->ctx = ctx;
424 spf->state = SPF_NONE;
425 spf->state_reason = NULL;
426 spf->nqueries = 0;
427 spf->running = 0;
428 spf->done = 0;
430 for (i = 0; i < SPF_DNS_LOOKUP_LIMIT; i++) {
431 spf->queries[i].domain = NULL;
432 spf->queries[i].txt = NULL;
433 spf->queries[i].eva = NULL;
436 from = osmtpd_ltok_skip_cfws(from, 1);
438 if ((at = osmtpd_ltok_skip_local_part(from, 0)) == NULL)
439 goto fail;
441 if ((spf->sender_local = strndup(from, at - from)) == NULL)
442 osmtpd_err(1, "%s: malloc", __func__);
444 if (*at != '@')
445 goto fail_local;
446 at++;
448 if ((from = osmtpd_ltok_skip_domain(at, 0)) == NULL)
449 goto fail_local;
452 if ((spf->sender_domain = strndup(at, from - at)) == NULL)
453 osmtpd_err(1, "%s: malloc", __func__);
455 spf_lookup_record(
456 spf, spf->sender_domain, T_TXT, SPF_PASS, 0, 0);
458 return spf;
460 fail_local:
461 free(spf->sender_local);
463 fail:
464 free(spf);
465 return NULL;
468 void
469 spf_record_free(struct spf_record *spf)
471 int i;
473 for (i = 0; i < SPF_DNS_LOOKUP_LIMIT; i++) {
474 if (spf->queries[i].domain)
475 free(spf->queries[i].domain);
476 if (spf->queries[i].txt)
477 free(spf->queries[i].txt);
478 if (spf->queries[i].eva)
479 event_asr_abort(spf->queries[i].eva);
482 free(spf->sender_local);
483 free(spf->sender_domain);
485 free(spf);
488 void *
489 auth_session_new(struct osmtpd_ctx *ctx)
491 struct session *ses;
493 if ((ses = malloc(sizeof(*ses))) == NULL)
494 osmtpd_err(1, "%s: malloc", __func__);
496 ses->ctx = ctx;
497 ses->iprev = IPREV_NONE;
499 ses->spf_helo = NULL;
500 ses->spf_mailfrom = NULL;
502 ses->identity = NULL;
503 ses->rdns = NULL;
505 return ses;
508 void
509 auth_session_free(struct osmtpd_ctx *ctx, void *data)
511 struct session *ses = data;
513 if (ses->spf_helo)
514 spf_record_free(ses->spf_helo);
515 if (ses->spf_mailfrom)
516 spf_record_free(ses->spf_mailfrom);
517 if (ses->identity)
518 free(ses->identity);
519 if (ses->rdns)
520 free(ses->rdns);
522 free(ses);
525 void *
526 auth_message_new(struct osmtpd_ctx *ctx)
528 struct message *msg;
530 if ((msg = malloc(sizeof(*msg))) == NULL)
531 osmtpd_err(1, "%s: malloc", __func__);
533 if ((msg->origf = tmpfile()) == NULL) {
534 osmtpd_warn(NULL, "Can't open tempfile");
535 free(msg);
536 return NULL;
538 msg->ctx = ctx;
539 msg->parsing_headers = 1;
540 msg->body_whitelines = 0;
541 msg->has_body = 0;
542 msg->header = NULL;
543 msg->nheaders = 0;
544 msg->readdone = 0;
545 msg->nqueries = 0;
547 return msg;
550 void
551 auth_message_free(struct osmtpd_ctx *ctx, void *data)
553 struct message *msg = data;
554 size_t i, j;
556 fclose(msg->origf);
557 for (i = 0; i < msg->nheaders; i++) {
558 if (msg->header[i].sig != NULL) {
559 free(msg->header[i].sig->b);
560 EVP_MD_CTX_free(msg->header[i].sig->bhctx);
561 for (j = 0; msg->header[i].sig->h != NULL &&
562 msg->header[i].sig->h[j] != NULL; j++)
563 free(msg->header[i].sig->h[j]);
564 free(msg->header[i].sig->h);
565 EVP_PKEY_free(msg->header[i].sig->p);
566 if (msg->header[i].sig->query)
567 event_asr_abort(msg->header[i].sig->query);
569 free(msg->header[i].buf);
570 free(msg->header[i].sig);
572 free(msg->header);
573 free(msg);
576 void
577 dkim_header_add(struct osmtpd_ctx *ctx, const char *line)
579 struct message *msg = ctx->local_message;
580 const char *start, *end, *verify;
581 struct header *headers;
582 size_t i;
584 if (msg->nheaders > 0 &&
585 msg->header[msg->nheaders - 1].readdone == 0) {
586 if (line[0] != ' ' && line[0] != '\t') {
587 msg->header[msg->nheaders - 1].readdone = 1;
588 start = msg->header[msg->nheaders - 1].buf;
589 end = osmtpd_ltok_skip_field_name(start, 0);
590 /* In case someone uses an obs-optional */
591 if (end != NULL)
592 verify = osmtpd_ltok_skip_wsp(end, 1);
593 if (end != NULL &&
594 strncasecmp(
595 start, "DKIM-Signature", end - start) == 0 &&
596 verify[0] == ':')
597 dkim_signature_parse(
598 &msg->header[msg->nheaders - 1]);
599 if (line[0] == '\0')
600 return;
601 } else {
602 dkim_header_cat(ctx, line);
603 return;
606 if (msg->nheaders % 10 == 0) {
607 if ((headers = recallocarray(msg->header, msg->nheaders,
608 msg->nheaders + 10, sizeof(*msg->header))) == NULL)
609 osmtpd_err(1, "%s: malloc", __func__);
610 msg->header = headers;
611 for (i = 0; i < msg->nheaders; i++) {
612 if (msg->header[i].sig == NULL)
613 continue;
614 msg->header[i].sig->header = &msg->header[i];
617 msg->header[msg->nheaders].msg = msg;
618 msg->nheaders++;
619 dkim_header_cat(ctx, line);
622 void
623 dkim_header_cat(struct osmtpd_ctx *ctx, const char *line)
625 struct message *msg = ctx->local_message;
626 struct header *header = &msg->header[msg->nheaders - 1];
627 char *buf;
629 size_t needed = header->buflen + strlen(line) + 2;
631 if (needed > (header->buflen / 1024) + 1) {
632 buf = reallocarray(header->buf, (needed / 1024) + 1, 1024);
633 if (buf == NULL)
634 osmtpd_err(1, "%s: malloc", __func__);
635 header->buf = buf;
637 header->buflen += snprintf(header->buf + header->buflen,
638 (((needed / 1024) + 1) * 1024) - header->buflen, "%s%s",
639 header->buflen == 0 ? "" : "\r\n", line);
642 void
643 dkim_signature_parse(struct header *header)
645 struct dkim_signature *sig;
646 const char *buf, *i, *end;
647 char tagname[3];
648 char subdomain[HOST_NAME_MAX + 1];
649 size_t ilen, dlen;
651 /* Format checked by dkim_header_add */
652 buf = osmtpd_ltok_skip_field_name(header->buf, 0);
653 buf = osmtpd_ltok_skip_wsp(buf, 1) + 1;
655 if ((header->sig = calloc(1, sizeof(*header->sig))) == NULL)
656 osmtpd_err(1, "%s: malloc", __func__);
657 sig = header->sig;
658 sig->header = header;
659 sig->l = -1;
660 sig->t = -1;
661 sig->x = -1;
663 end = osmtpd_ltok_skip_tag_list(buf, 0);
664 if (end == NULL || end[0] != '\0') {
665 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid tag-list");
666 return;
669 while (buf[0] != '\0') {
670 buf = osmtpd_ltok_skip_fws(buf, 1);
671 end = osmtpd_ltok_skip_tag_name(buf, 0);
673 /* Unknown tag-name */
674 if ((size_t)(end - buf) >= sizeof(tagname))
675 tagname[0] = '\0';
676 else
677 strlcpy(tagname, buf, (end - buf) + 1);
678 buf = osmtpd_ltok_skip_fws(end, 1);
679 /* '=' */
680 buf = osmtpd_ltok_skip_fws(buf + 1, 1);
681 end = osmtpd_ltok_skip_tag_value(buf, 1);
682 if (strcmp(tagname, "v") == 0)
683 dkim_signature_parse_v(sig, buf, end);
684 else if (strcmp(tagname, "a") == 0)
685 dkim_signature_parse_a(sig, buf, end);
686 else if (strcmp(tagname, "b") == 0)
687 dkim_signature_parse_b(sig, buf, end);
688 else if (strcmp(tagname, "bh") == 0)
689 dkim_signature_parse_bh(sig, buf, end);
690 else if (strcmp(tagname, "c") == 0)
691 dkim_signature_parse_c(sig, buf, end);
692 else if (strcmp(tagname, "d") == 0)
693 dkim_signature_parse_d(sig, buf, end);
694 else if (strcmp(tagname, "h") == 0)
695 dkim_signature_parse_h(sig, buf, end);
696 else if (strcmp(tagname, "i") == 0)
697 dkim_signature_parse_i(sig, buf, end);
698 else if (strcmp(tagname, "l") == 0)
699 dkim_signature_parse_l(sig, buf, end);
700 else if (strcmp(tagname, "q") == 0)
701 dkim_signature_parse_q(sig, buf, end);
702 else if (strcmp(tagname, "s") == 0)
703 dkim_signature_parse_s(sig, buf, end);
704 else if (strcmp(tagname, "t") == 0)
705 dkim_signature_parse_t(sig, buf, end);
706 else if (strcmp(tagname, "x") == 0)
707 dkim_signature_parse_x(sig, buf, end);
708 else if (strcmp(tagname, "z") == 0)
709 dkim_signature_parse_z(sig, buf, end);
711 buf = osmtpd_ltok_skip_fws(end, 1);
712 if (buf[0] == ';')
713 buf++;
714 else if (buf[0] != '\0') {
715 dkim_signature_state(sig, DKIM_PERMERROR,
716 "Invalid tag-list");
717 return;
720 if (sig->state != DKIM_UNKNOWN)
721 return;
723 if (sig->v != 1)
724 dkim_signature_state(sig, DKIM_PERMERROR, "Missing v tag");
725 else if (sig->ah == NULL)
726 dkim_signature_state(sig, DKIM_PERMERROR, "Missing a tag");
727 else if (sig->b == NULL)
728 dkim_signature_state(sig, DKIM_PERMERROR, "Missing b tag");
729 else if (sig->bhsz == 0)
730 dkim_signature_state(sig, DKIM_PERMERROR, "Missing bh tag");
731 else if (sig->d[0] == '\0')
732 dkim_signature_state(sig, DKIM_PERMERROR, "Missing d tag");
733 else if (sig->h == NULL)
734 dkim_signature_state(sig, DKIM_PERMERROR, "Missing h tag");
735 else if (sig->s[0] == '\0')
736 dkim_signature_state(sig, DKIM_PERMERROR, "Missing s tag");
737 if (sig->state != DKIM_UNKNOWN)
738 return;
740 if (sig->i != NULL) {
741 i = osmtpd_ltok_skip_local_part(sig->i, 1) + 1;
742 ilen = sig->isz - (size_t)(i - sig->i);
743 dlen = strlen(sig->d);
744 if (ilen < dlen) {
745 dkim_signature_state(sig, DKIM_PERMERROR,
746 "i tag not subdomain of d");
747 return;
749 i += ilen - dlen;
750 if ((i[-1] != '.' && i[-1] != '@') ||
751 strncasecmp(i, sig->d, dlen) != 0) {
752 dkim_signature_state(sig, DKIM_PERMERROR,
753 "i tag not subdomain of d");
754 return;
757 if (sig->t != -1 && sig->x != -1 && sig->t > sig->x) {
758 dkim_signature_state(sig, DKIM_PERMERROR, "t tag after x tag");
759 return;
762 if ((size_t)snprintf(subdomain, sizeof(subdomain), "%s._domainkey.%s",
763 sig->s, sig->d) >= sizeof(subdomain)) {
764 dkim_signature_state(sig, DKIM_PERMERROR,
765 "dns/txt query too long");
766 return;
769 dkim_lookup_record(sig, subdomain);
772 void
773 dkim_lookup_record(struct dkim_signature *sig, const char *domain)
775 struct asr_query *query;
777 if (sig->state != DKIM_UNKNOWN)
778 return;
780 sig->nqueries++;
782 if (sig->query != NULL) {
783 event_asr_abort(sig->query);
784 sig->query = NULL;
785 sig->header->msg->nqueries--;
787 if ((query = res_query_async(domain, C_IN, T_TXT, NULL)) == NULL)
788 osmtpd_err(1, "res_query_async");
790 if ((sig->query = event_asr_run(query, dkim_rr_resolve, sig)) == NULL)
791 osmtpd_err(1, "res_query_async");
793 sig->header->msg->nqueries++;
796 void
797 dkim_signature_parse_v(struct dkim_signature *sig, const char *start, const char *end)
799 if (sig->v != 0) { /* Duplicate tag */
800 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate v tag");
801 return;
803 /* Unsupported version */
804 if (start[0] != '1' || start + 1 != end)
805 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsupported v tag");
806 else
807 sig->v = 1;
810 void
811 dkim_signature_parse_a(struct dkim_signature *sig, const char *start, const char *end)
813 char ah[sizeof("sha256")];
815 if (sig->ah != NULL) {
816 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate a tag");
817 return;
820 if (osmtpd_ltok_skip_sig_a_tag_alg(start, 0) != end) {
821 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid a tag");
822 return;
824 sig->a = start;
825 sig->asz = (size_t)(end - start);
826 if (strncmp(start, "rsa-", 4) == 0) {
827 start += 4;
828 sig->ak = EVP_PKEY_RSA;
829 sig->sephash = 0;
830 #if HAVE_ED25519
831 } else if (strncmp(start, "ed25519-", 8) == 0) {
832 start += 8;
833 sig->ak = EVP_PKEY_ED25519;
834 sig->sephash = 1;
835 #endif
836 } else {
837 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag k");
838 return;
840 if ((size_t)(end - start) >= sizeof(ah)) {
841 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag h");
842 return;
844 strlcpy(ah, start, sizeof(ah));
845 ah[end - start] = '\0';
846 if ((sig->ah = EVP_get_digestbyname(ah)) == NULL) {
847 dkim_signature_state(sig, DKIM_NEUTRAL, "Unsuppored a tag h");
848 return;
850 if ((sig->bhctx = EVP_MD_CTX_new()) == NULL)
851 osmtpd_err(1, "EVP_MD_CTX_new");
853 if (EVP_DigestInit_ex(sig->bhctx, sig->ah, NULL) <= 0) {
854 dkim_signature_state(sig, DKIM_FAIL, "Unsuppored a tag ah");
855 return;
859 void
860 dkim_signature_parse_b(struct dkim_signature *sig, const char *start, const char *end)
862 int decodesz;
863 size_t i, j;
865 if (sig->b != NULL) {
866 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate b tag");
867 return;
869 sig->bheader = start;
870 sig->bheadersz = end - start;
871 if ((sig->b = malloc(((sig->bheadersz / 4) + 1) * 3)) == NULL)
872 osmtpd_err(1, "%s: malloc", __func__);
873 /* EVP_DecodeBlock doesn't handle internal whitespace */
874 EVP_DecodeInit(ectx);
875 if (EVP_DecodeUpdate(ectx, sig->b, &decodesz, sig->bheader,
876 (int) sig->bheadersz) == -1) {
877 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid b tag");
878 return;
880 sig->bsz = decodesz;
881 if (EVP_DecodeFinal(ectx, sig->b + sig->bsz,
882 &decodesz) == -1) {
883 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid b tag");
884 return;
886 sig->bsz += decodesz;
887 for (i = 0, j = 0;
888 i < sig->bheadersz && j < HEADER_B_MAX_LEN; i++) {
889 if (isalnum(sig->bheader[i]) || sig->bheader[i] == '/'
890 || sig->bheader[i] == '+' || sig->bheader[i] == '=')
891 sig->bheaderclean[j++] = sig->bheader[i];
893 sig->bheaderclean[j] = '\0';
896 void
897 dkim_signature_parse_bh(struct dkim_signature *sig, const char *start, const char *end)
899 const char *b64;
900 size_t n;
901 int decodesz;
903 if (sig->bhsz != 0) {
904 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate bh tag");
905 return;
907 /*
908 * EVP_Decode* expects sig->bh to be large enough,
909 * so count the actual b64 characters.
910 */
911 b64 = start;
912 n = 0;
913 while (1) {
914 b64 = osmtpd_ltok_skip_fws(b64, 1);
915 if (osmtpd_ltok_skip_alphadigitps(b64, 0) == NULL)
916 break;
917 n++;
918 b64++;
920 if (b64[0] == '=') {
921 n++;
922 b64 = osmtpd_ltok_skip_fws(b64 + 1, 1);
923 if (b64[0] == '=') {
924 n++;
925 b64++;
928 /* Invalid tag value */
929 if (b64 != end || n % 4 != 0 || (n / 4) * 3 > sizeof(sig->bh)) {
930 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
931 return;
933 /* EVP_DecodeBlock doesn't handle internal whitespace */
934 EVP_DecodeInit(ectx);
935 if (EVP_DecodeUpdate(ectx, sig->bh, &decodesz, start,
936 (int)(end - start)) == -1) {
937 /* Paranoia check */
938 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
939 return;
941 sig->bhsz = decodesz;
942 if (EVP_DecodeFinal(ectx, sig->bh + sig->bhsz, &decodesz) == -1) {
943 /* Paranoia check */
944 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid bh tag");
945 return;
947 sig->bhsz += decodesz;
950 void
951 dkim_signature_parse_c(struct dkim_signature *sig, const char *start, const char *end)
953 if (sig->c != 0) {
954 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate c tag");
955 return;
957 if (strncmp(start, "simple", 6) == 0) {
958 sig->c = CANON_HEADER_SIMPLE;
959 start += 6;
960 } else if (strncmp(start, "relaxed", 7) == 0) {
961 sig->c = CANON_HEADER_RELAXED;
962 start += 7;
963 } else {
964 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid c tag");
965 return;
967 if (start[0] == '/') {
968 start++;
969 if (strncmp(start, "simple", 6) == 0) {
970 sig->c |= CANON_BODY_SIMPLE;
971 start += 6;
972 } else if (strncmp(start, "relaxed", 7) == 0) {
973 sig->c |= CANON_BODY_RELAXED;
974 start += 7;
975 } else {
976 dkim_signature_state(sig, DKIM_PERMERROR,
977 "Invalid c tag");
978 return;
982 if (start != end) {
983 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid c tag");
984 return;
986 sig->c |= CANON_DONE;
989 void
990 dkim_signature_parse_d(struct dkim_signature *sig, const char *start, const char *end)
992 if (sig->d[0] != '\0') {
993 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate d tag");
994 return;
996 if (osmtpd_ltok_skip_sig_d_tag_value(start, 0) != end ||
997 (size_t)(end - start) >= sizeof(sig->d)) {
998 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid d tag");
999 return;
1001 strlcpy(sig->d, start, end - start + 1);
1004 void
1005 dkim_signature_parse_h(struct dkim_signature *sig, const char *start, const char *end)
1007 const char *h;
1008 size_t n = 0;
1010 if (sig->h != NULL) {
1011 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate h tag");
1012 return;
1014 if (osmtpd_ltok_skip_sig_h_tag_value(start, 0) < end) {
1015 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid h tag");
1016 return;
1018 h = start;
1019 while (1) {
1020 if ((h = osmtpd_ltok_skip_hdr_name(h, 0)) == NULL) {
1021 dkim_signature_state(sig, DKIM_PERMERROR,
1022 "Invalid h tag");
1023 return;
1025 n++;
1026 /* ';' is part of hdr-name */
1027 if (h > end) {
1028 h = end;
1029 break;
1031 h = osmtpd_ltok_skip_fws(h, 1);
1032 if (h[0] != ':')
1033 break;
1034 h = osmtpd_ltok_skip_fws(h + 1, 1);
1036 if ((sig->h = calloc(n + 1, sizeof(*sig->h))) == NULL)
1037 osmtpd_err(1, "%s: malloc", __func__);
1038 n = 0;
1039 h = start;
1040 while (1) {
1041 h = osmtpd_ltok_skip_hdr_name(start, 0);
1042 /* ';' is part of hdr-name */
1043 if (h > end) {
1044 sig->h[n] = strndup(start, end - start);
1045 break;
1047 if ((sig->h[n++] = strndup(start, h - start)) == NULL)
1048 osmtpd_err(1, "%s: malloc", __func__);
1049 start = osmtpd_ltok_skip_fws(h, 1);
1050 if (start[0] != ':')
1051 break;
1052 start = osmtpd_ltok_skip_fws(start + 1, 1);
1056 void
1057 dkim_signature_parse_i(struct dkim_signature *sig, const char *start, const char *end)
1059 if (sig->i != NULL) {
1060 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate i tag");
1061 return;
1063 if (osmtpd_ltok_skip_sig_i_tag_value(start, 0) != end) {
1064 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid i tag");
1065 return;
1067 sig->i = start;
1068 sig->isz = (size_t)(end - start);
1071 void
1072 dkim_signature_parse_l(struct dkim_signature *sig, const char *start, const char *end)
1074 long long l;
1075 char *lend;
1077 if (sig->l != -1) { /* Duplicate tag */
1078 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate l tag");
1079 return;
1081 errno = 0;
1082 l = strtoll(start, &lend, 10);
1083 /* > 76 digits in stroll is an overflow */
1084 if (osmtpd_ltok_skip_digit(start, 0) == NULL ||
1085 lend != end || errno != 0) {
1086 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid l tag");
1087 return;
1089 if (l > SSIZE_MAX) {
1090 dkim_signature_state(sig, DKIM_PERMERROR, "l tag too large");
1091 return;
1093 sig->l = (ssize_t)l;
1096 void
1097 dkim_signature_parse_q(struct dkim_signature *sig, const char *start, const char *end)
1099 const char *qend;
1101 if (sig->q != 0) {
1102 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate q tag");
1103 return;
1106 while (1) {
1107 start = osmtpd_ltok_skip_fws(start, 1);
1108 qend = osmtpd_ltok_skip_sig_q_tag_method(start, 0);
1109 if (qend == NULL) {
1110 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid q tag");
1111 return;
1113 if (strncmp(start, "dns/txt", qend - start) == 0)
1114 sig->q = 1;
1115 start = osmtpd_ltok_skip_fws(qend, 1);
1116 if (start[0] != ':')
1117 break;
1119 if (start != end) {
1120 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid q tag");
1121 return;
1123 if (sig->q != 1) {
1124 sig->q = 1;
1125 dkim_signature_state(sig, DKIM_NEUTRAL, "No useable q found");
1126 return;
1130 void
1131 dkim_signature_parse_s(struct dkim_signature *sig, const char *start, const char *end)
1133 if (sig->s[0] != '\0') {
1134 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate s tag");
1135 return;
1137 if (osmtpd_ltok_skip_selector(start, 0) != end) {
1138 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid s tag");
1139 return;
1141 strlcpy(sig->s, start, end - start + 1);
1144 void
1145 dkim_signature_parse_t(struct dkim_signature *sig, const char *start, const char *end)
1147 char *tend;
1149 if (sig->t != -1) {
1150 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate t tag");
1151 return;
1153 errno = 0;
1154 sig->t = strtoll(start, &tend, 10);
1155 if (osmtpd_ltok_skip_digit(start, 0) == NULL || tend != end ||
1156 tend - start > 12 || errno != 0) {
1157 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid t tag");
1158 return;
1162 void
1163 dkim_signature_parse_x(struct dkim_signature *sig, const char *start, const char *end)
1165 char *xend;
1167 if (sig->x != -1) {
1168 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate x tag");
1169 return;
1171 errno = 0;
1172 sig->x = strtoll(start, &xend, 10);
1173 if (osmtpd_ltok_skip_digit(start, 0) == NULL || xend != end ||
1174 xend - start > 12 || errno != 0) {
1175 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid x tag");
1176 return;
1180 void
1181 dkim_signature_parse_z(struct dkim_signature *sig, const char *start, const char *end)
1183 if (sig->z != 0) {
1184 dkim_signature_state(sig, DKIM_PERMERROR, "Duplicate z tag");
1185 return;
1188 sig->z = 1;
1189 if (osmtpd_ltok_skip_sig_z_tag_value(start, 0) != end) {
1190 dkim_signature_state(sig, DKIM_PERMERROR, "Invalid z tag");
1191 return;
1195 void
1196 dkim_signature_verify(struct dkim_signature *sig)
1198 struct message *msg = sig->header->msg;
1199 static EVP_MD_CTX *bctx = NULL;
1200 char digest[EVP_MAX_MD_SIZE];
1201 unsigned int digestsz;
1202 const char *end;
1203 size_t i, header;
1205 if (sig->state != DKIM_UNKNOWN)
1206 return;
1208 if (bctx == NULL) {
1209 if ((bctx = EVP_MD_CTX_new()) == NULL)
1210 osmtpd_err(1, "EVP_MD_CTX_new");
1212 EVP_MD_CTX_reset(bctx);
1213 if (!sig->sephash) {
1214 if (EVP_DigestVerifyInit(bctx, NULL, sig->ah, NULL,
1215 sig->p) != 1) {
1216 dkim_signature_state(sig, DKIM_FAIL, "ah tag");
1217 return;
1219 } else {
1220 if (EVP_DigestInit_ex(bctx, sig->ah, NULL) != 1) {
1221 dkim_signature_state(sig, DKIM_FAIL, "ah tag");
1222 return;
1226 for (i = 0; i < msg->nheaders; i++)
1227 msg->header[i].parsed = 0;
1229 for (header = 0; sig->h[header] != NULL; header++) {
1230 for (i = msg->nheaders; i > 0; ) {
1231 i--;
1232 if (msg->header[i].parsed ||
1233 strncasecmp(msg->header[i].buf, sig->h[header],
1234 strlen(sig->h[header])) != 0 ||
1235 msg->header[i].sig == sig)
1236 continue;
1237 end = osmtpd_ltok_skip_fws(
1238 msg->header[i].buf + strlen(sig->h[header]), 1);
1239 if (end[0] != ':')
1240 continue;
1241 dkim_signature_header(bctx, sig, &(msg->header[i]));
1242 msg->header[i].parsed = 1;
1243 break;
1246 dkim_signature_header(bctx, sig, sig->header);
1247 if (!sig->sephash) {
1248 if (EVP_DigestVerifyFinal(bctx, sig->b, sig->bsz) != 1)
1249 dkim_signature_state(sig, DKIM_FAIL, "b mismatch");
1250 } else {
1251 if (EVP_DigestFinal_ex(bctx, digest, &digestsz) == 0)
1252 osmtpd_err(1, "EVP_DigestFinal_ex");
1254 if (EVP_DigestVerifyInit(bctx, NULL, NULL, NULL, sig->p) != 1)
1255 osmtpd_err(1, "EVP_DigestVerifyInit");
1257 switch (EVP_DigestVerify(bctx, sig->b, sig->bsz, digest,
1258 digestsz)) {
1259 case 1:
1260 break;
1261 case 0:
1262 dkim_signature_state(sig, DKIM_FAIL, "b mismatch");
1263 break;
1264 default:
1265 osmtpd_err(1, "EVP_DigestVerify");
1270 /* EVP_DigestVerifyUpdate is a macro, so we can't alias this on a variable */
1271 #define dkim_b_digest_update(a, b, c) \
1272 (sig->sephash ? EVP_DigestUpdate((a), (b), (c)) :\
1273 EVP_DigestVerifyUpdate((a), (b), (c)))
1275 void
1276 dkim_signature_header(EVP_MD_CTX *bctx, struct dkim_signature *sig,
1277 struct header *header)
1279 char c;
1280 const char *ptr = header->buf, *end;
1281 int inhdrname = 1;
1282 int canon = sig->c & CANON_HEADER;
1284 for (ptr = header->buf; ptr[0] != '\0'; ptr++) {
1285 if (inhdrname) {
1286 if (canon == CANON_HEADER_RELAXED) {
1287 ptr = osmtpd_ltok_skip_fws(ptr, 1);
1288 c = tolower(ptr[0]);
1289 } else
1290 c = ptr[0];
1291 if (c == ':') {
1292 inhdrname = 0;
1293 if (canon == CANON_HEADER_RELAXED)
1294 ptr = osmtpd_ltok_skip_fws(
1295 ptr + 1, 1) - 1;
1297 if (dkim_b_digest_update(bctx, &c, 1) == 0)
1298 osmtpd_errx(1, "dkim_b_digest_update");
1299 continue;
1301 end = osmtpd_ltok_skip_fws(ptr, 1);
1302 if (end == ptr) {
1303 if (sig->header == header && ptr == sig->bheader) {
1304 ptr = osmtpd_ltok_skip_tag_value(
1305 ptr, 0) - 1;
1306 continue;
1308 if (dkim_b_digest_update(bctx, ptr, 1) == 0)
1309 osmtpd_errx(1, "dkim_b_digest_update");
1310 } else {
1311 if (canon == CANON_HEADER_RELAXED) {
1312 if (end[0] == '\0')
1313 continue;
1314 if (dkim_b_digest_update(bctx, " ", 1) == 0)
1315 osmtpd_errx(1, "dkim_b_digest_update");
1316 } else {
1317 if (dkim_b_digest_update(bctx, ptr,
1318 end - ptr) == 0)
1319 osmtpd_errx(1, "dkim_b_digest_update");
1321 ptr = end - 1;
1325 if (sig->header != header) {
1326 if (dkim_b_digest_update(bctx, "\r\n", 2) == 0)
1327 osmtpd_errx(1, "dkim_b_digest_update");
1331 void
1332 dkim_signature_state(struct dkim_signature *sig, enum dkim_state state,
1333 const char *reason)
1335 if (sig->query != NULL) {
1336 event_asr_abort(sig->query);
1337 sig->query = NULL;
1338 sig->header->msg->nqueries--;
1340 switch (sig->state) {
1341 case DKIM_UNKNOWN:
1342 break;
1343 case DKIM_PASS:
1344 case DKIM_FAIL:
1345 osmtpd_errx(1, "Unexpected transition");
1346 case DKIM_POLICY:
1347 if (state == DKIM_PASS)
1348 return;
1349 break;
1350 case DKIM_NEUTRAL:
1351 if (state == DKIM_PASS)
1352 return;
1353 if (state == DKIM_TEMPERROR || state == DKIM_PERMERROR)
1354 break;
1355 osmtpd_errx(1, "Unexpected transition");
1356 case DKIM_TEMPERROR:
1357 if (state == DKIM_PERMERROR)
1358 break;
1359 return;
1360 case DKIM_PERMERROR:
1361 return;
1363 sig->state = state;
1364 sig->state_reason = reason;
1367 const char *
1368 dkim_state2str(enum dkim_state state)
1370 switch (state)
1372 case DKIM_UNKNOWN:
1373 return "unknown";
1374 case DKIM_PASS:
1375 return "pass";
1376 case DKIM_FAIL:
1377 return "fail";
1378 case DKIM_POLICY:
1379 return "policy";
1380 case DKIM_NEUTRAL:
1381 return "neutral";
1382 case DKIM_TEMPERROR:
1383 return "temperror";
1384 case DKIM_PERMERROR:
1385 return "permerror";
1389 void
1390 dkim_rr_resolve(struct asr_result *ar, void *arg)
1392 struct dkim_signature *sig = arg;
1393 char key[UINT16_MAX + 1];
1394 const char *rr_txt;
1395 size_t keylen, cstrlen;
1396 struct unpack pack;
1397 struct dns_header h;
1398 struct dns_query q;
1399 struct dns_rr rr;
1400 char buf[HOST_NAME_MAX + 1];
1402 sig->query = NULL;
1403 sig->header->msg->nqueries--;
1405 if (sig->state != DKIM_UNKNOWN)
1406 goto verify;
1408 if (ar->ar_h_errno == TRY_AGAIN || ar->ar_h_errno == NO_RECOVERY) {
1409 dkim_signature_state(sig, DKIM_TEMPERROR,
1410 hstrerror(ar->ar_h_errno));
1411 goto verify;
1413 if (ar->ar_h_errno == HOST_NOT_FOUND) {
1414 dkim_signature_state(sig, DKIM_PERMERROR,
1415 hstrerror(ar->ar_h_errno));
1416 goto verify;
1419 unpack_init(&pack, ar->ar_data, ar->ar_datalen);
1420 if (unpack_header(&pack, &h) != 0 ||
1421 unpack_query(&pack, &q) != 0) {
1422 osmtpd_warn(sig->header->msg->ctx,
1423 "Mallformed DKIM DNS response for domain %s: %s",
1424 print_dname(q.q_dname, buf, sizeof(buf)),
1425 pack.err);
1426 dkim_signature_state(sig, DKIM_PERMERROR, pack.err);
1427 goto verify;
1430 for (; h.ancount > 0; h.ancount--) {
1431 if (unpack_rr(&pack, &rr) != 0) {
1432 osmtpd_warn(sig->header->msg->ctx,
1433 "Mallformed DKIM DNS record for domain %s: %s",
1434 print_dname(q.q_dname, buf, sizeof(buf)),
1435 pack.err);
1436 continue;
1439 /* If we below limit, follow CNAME*/
1440 if (rr.rr_type == T_CNAME &&
1441 sig->nqueries < DKIM_LOOKUP_LOOKUP_LIMIT ) {
1442 print_dname(rr.rr.cname.cname, buf, sizeof(buf));
1443 dkim_lookup_record(sig, buf);
1444 free(ar->ar_data);
1445 return;
1448 if (rr.rr_type != T_TXT) {
1449 osmtpd_warn(sig->header->msg->ctx,
1450 "Unexpected DKIM DNS record: %d for domain %s",
1451 rr.rr_type,
1452 print_dname(q.q_dname, buf, sizeof(buf)));
1453 continue;
1456 keylen = 0;
1457 rr_txt = rr.rr.other.rdata;
1458 while (rr.rr.other.rdlen > 0) {
1459 cstrlen = ((const unsigned char *)rr_txt)[0];
1460 if (cstrlen >= rr.rr.other.rdlen ||
1461 keylen + cstrlen >= sizeof(key))
1462 break;
1464 * RFC 6376 Section 3.6.2.2
1465 * Strings in a TXT RR MUST be concatenated together
1466 * before use with no intervening whitespace.
1468 strlcpy(key + keylen, rr_txt + 1, cstrlen + 1);
1469 rr.rr.other.rdlen -= (cstrlen + 1);
1470 rr_txt += (cstrlen + 1);
1471 keylen += cstrlen;
1473 if (rr.rr.other.rdlen > 0) /* Invalid TXT RDATA */
1474 continue;
1476 if (dkim_key_text_parse(sig, key))
1477 break;
1480 if (h.ancount == 0) {
1481 dkim_signature_state(sig, DKIM_PERMERROR,
1482 "No matching key found");
1483 } else {
1484 /* Only verify if all headers have been read */
1485 if (!sig->header->msg->parsing_headers)
1486 dkim_signature_verify(sig);
1488 verify:
1489 free(ar->ar_data);
1490 auth_message_verify(sig->header->msg);
1493 int
1494 dkim_key_text_parse(struct dkim_signature *sig, const char *key)
1496 char tagname, *hashname;
1497 const char *end, *tagvend;
1498 char pkraw[UINT16_MAX] = "", pkimp[UINT16_MAX];
1499 size_t pkrawlen = 0, pkoff, linelen;
1500 int h = 0, k = 0, n = 0, p = 0, s = 0, t = 0, first = 1;
1501 BIO *bio;
1502 #ifdef HAVE_ED25519
1503 size_t pklen;
1504 int tmp;
1505 #endif
1507 key = osmtpd_ltok_skip_fws(key, 1);
1508 /* Validate syntax early */
1509 if ((end = osmtpd_ltok_skip_tag_list(key, 0)) == NULL)
1510 return 0;
1512 while (key[0] != '\0') {
1513 key = osmtpd_ltok_skip_fws(key, 1);
1514 if ((end = osmtpd_ltok_skip_tag_name(key, 0)) == NULL)
1515 return 0;
1517 if ((size_t)(end - key) != 1)
1518 tagname = '\0';
1519 else
1520 tagname = key[0];
1521 key = osmtpd_ltok_skip_fws(end, 1);
1522 /* '=' */
1523 if (key[0] != '=')
1524 return 0;
1525 key = osmtpd_ltok_skip_fws(key + 1, 1);
1526 if ((end = osmtpd_ltok_skip_tag_value(key, 0)) == NULL)
1527 return 0;
1528 switch (tagname) {
1529 case 'v':
1531 * RFC 6376 section 3.6.1, v=:
1532 * RECOMMENDED...This tag MUST be the first tag in the
1533 * record.
1535 if (!first ||
1536 osmtpd_ltok_skip_key_v_tag_value(key, 0) != end)
1537 return 0;
1538 key = end;
1539 break;
1540 case 'h':
1541 if (h != 0) /* Duplicate tag */
1542 return 0;
1543 /* Invalid tag value */
1544 if (osmtpd_ltok_skip_key_h_tag_value(key, 0) != end)
1545 return 0;
1546 while (1) {
1547 if ((tagvend = osmtpd_ltok_skip_key_h_tag_alg(
1548 key, 0)) == NULL)
1549 break;
1550 hashname = strndup(key, tagvend - key);
1551 if (hashname == NULL)
1552 osmtpd_err(1, "strndup");
1553 if (EVP_get_digestbyname(hashname) == sig->ah) {
1554 free(hashname);
1555 h = 1;
1556 break;
1558 free(hashname);
1559 key = osmtpd_ltok_skip_fws(tagvend, 1);
1560 if (key[0] != ':')
1561 break;
1562 key = osmtpd_ltok_skip_fws(key + 1, 1);
1564 if (h != 1)
1565 return 0;
1566 key = end;
1567 break;
1568 case 'k':
1569 if (k != 0) /* Duplicate tag */
1570 return 0;
1571 k = 1;
1572 if (strncmp(key, "rsa", end - key) == 0) {
1573 if (sig->ak != EVP_PKEY_RSA)
1574 return 0;
1575 #if HAVE_ED25519
1576 } else if (strncmp(key, "ed25519", end - key) == 0) {
1577 if (sig->ak != EVP_PKEY_ED25519)
1578 return 0;
1579 #endif
1580 } else
1581 return 0;
1582 key = end;
1583 break;
1584 case 'n':
1585 if (n != 0) /* Duplicate tag */
1586 return 0;
1587 n = 1;
1588 /* semicolon is part of safe-char */
1589 if (osmtpd_ltok_skip_key_n_tag_value(key, 0) < end)
1590 return 0;
1591 key = end;
1592 break;
1593 case 'p':
1594 if (p != 0) /* Duplicate tag */
1595 return 0;
1596 p = 1;
1597 while (1) {
1598 key = osmtpd_ltok_skip_fws(key, 1);
1599 if (osmtpd_ltok_skip_alphadigitps(
1600 key, 0) == NULL)
1601 break;
1602 pkraw[pkrawlen++] = key++[0];
1603 if (pkrawlen >= sizeof(pkraw))
1604 return 0;
1606 if (key[0] == '=') {
1607 pkraw[pkrawlen++] = '=';
1608 key = osmtpd_ltok_skip_fws(key + 1, 1);
1609 if (pkrawlen >= sizeof(pkraw))
1610 return 0;
1611 if (key[0] == '=') {
1612 pkraw[pkrawlen++] = '=';
1613 key++;
1614 if (pkrawlen >= sizeof(pkraw))
1615 return 0;
1618 /* Invalid tag value */
1619 if (pkrawlen % 4 != 0 || key != end)
1620 return 0;
1621 break;
1622 case 's':
1623 if (s != 0) /* Duplicate tag */
1624 return 0;
1625 /* Invalid tag value */
1626 if (osmtpd_ltok_skip_key_s_tag_value(key, 0) != end)
1627 return 0;
1628 while (1) {
1629 if ((tagvend =
1630 osmtpd_ltok_skip_key_s_tag_type(
1631 key, 0)) == NULL)
1632 break;
1633 if (strncmp(key, "*", tagvend - key) == 0 ||
1634 strncmp(key, "email", tagvend - key) == 0) {
1635 s = 1;
1636 break;
1638 key = osmtpd_ltok_skip_fws(tagvend, 1);
1639 if (key[0] != ':')
1640 break;
1641 key = osmtpd_ltok_skip_fws(key + 1, 1);
1643 if (s != 1)
1644 return 0;
1645 key = end;
1646 break;
1647 case 't':
1648 if (t != 0) /* Duplicate tag */
1649 return 0;
1650 t = 1;
1651 if (osmtpd_ltok_skip_key_t_tag_value(key, 0) != end)
1652 return 0;
1653 while (1) {
1654 tagvend = osmtpd_ltok_skip_key_t_tag_flag(
1655 key, 0);
1656 if (strncmp(key, "y", tagvend - key) == 0)
1657 sig->kt |= KT_Y;
1658 else if (strncmp(key, "s", tagvend - key) == 0)
1659 sig->kt |= KT_S;
1660 key = osmtpd_ltok_skip_fws(tagvend, 1);
1661 if (key[0] != ':')
1662 break;
1663 key = osmtpd_ltok_skip_fws(key + 1, 1);
1665 break;
1666 default:
1667 key = end;
1668 break;
1671 first = 0;
1672 key = osmtpd_ltok_skip_fws(key, 1);
1673 if (key[0] == ';')
1674 key++;
1675 else if (key[0] != '\0')
1676 return 0;
1679 if (!p) /* Missing tag */
1680 return 0;
1681 if (k == 0 && sig->ak != EVP_PKEY_RSA) /* Default to RSA */
1682 return 0;
1684 if (pkraw[0] == '\0') {
1685 dkim_signature_state(sig, DKIM_PERMERROR, "Key is revoked");
1686 return 1;
1689 switch (sig->ak) {
1690 case EVP_PKEY_RSA:
1691 pkoff = strlcpy(pkimp, "-----BEGIN PUBLIC KEY-----\n",
1692 sizeof(pkimp));
1693 linelen = 0;
1694 for (key = pkraw; key[0] != '\0';) {
1695 if (pkoff + 2 >= sizeof(pkimp))
1696 return 0;
1697 pkimp[pkoff++] = key++[0];
1698 if (++linelen == 64) {
1699 pkimp[pkoff++] = '\n';
1700 linelen = 0;
1703 /* Leverage pkoff check in loop */
1704 if (linelen != 0)
1705 pkimp[pkoff++] = '\n';
1706 /* PEM_read_bio_PUBKEY will catch truncated keys */
1707 pkoff += strlcpy(pkimp + pkoff, "-----END PUBLIC KEY-----\n",
1708 sizeof(pkimp) - pkoff);
1709 if ((bio = BIO_new_mem_buf(pkimp, pkoff)) == NULL)
1710 osmtpd_err(1, "BIO_new_mem_buf");
1711 sig->p = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL);
1712 BIO_free(bio);
1713 break;
1714 #if HAVE_ED25519
1715 case EVP_PKEY_ED25519:
1716 if ((pkrawlen / 4) * 3 >= sizeof(pkimp))
1717 return 0;
1718 EVP_DecodeInit(ectx);
1719 if (EVP_DecodeUpdate(ectx, pkimp, &tmp, pkraw, pkrawlen) == -1)
1720 return 0;
1721 pklen = tmp;
1722 if (EVP_DecodeFinal(ectx, pkimp, &tmp) == -1)
1723 return 0;
1724 pklen += tmp;
1725 sig->p = EVP_PKEY_new_raw_public_key(sig->ak, NULL, pkimp,
1726 pklen);
1727 break;
1728 #endif
1730 if (sig->p == NULL) {
1732 * XXX No clue how to differentiate between invalid key and
1733 * temporary failure like *alloc.
1734 * Assume invalid key, because it's more likely.
1736 return 0;
1738 return 1;
1741 void
1742 dkim_body_parse(struct message *msg, const char *line)
1744 struct dkim_signature *sig;
1745 const char *end = line, *hash, *prev;
1746 size_t hashn, len, i;
1747 int wsp, ret;
1749 if (line[0] == '\0') {
1750 msg->body_whitelines++;
1751 return;
1754 while (msg->body_whitelines-- > 0) {
1755 for (i = 0; i < msg->nheaders; i++) {
1756 if ((sig = msg->header[i].sig) == NULL ||
1757 sig->state != DKIM_UNKNOWN)
1758 continue;
1759 hashn = sig->l == -1 ? 2 : MIN(2, sig->l);
1760 sig->l -= sig->l == -1 ? 0 : hashn;
1761 if (EVP_DigestUpdate(sig->bhctx, "\r\n", hashn) == 0)
1762 osmtpd_errx(1, "EVP_DigestUpdate");
1765 msg->body_whitelines = 0;
1766 msg->has_body = 1;
1768 while (line[0] != '\0') {
1769 while (1) {
1770 prev = end;
1771 if ((end = osmtpd_ltok_skip_wsp(end, 0)) == NULL)
1772 break;
1774 end = prev;
1775 wsp = end != line;
1776 if (!wsp) {
1777 while (osmtpd_ltok_skip_wsp(end, 0) == NULL &&
1778 end[0] != '\0')
1779 end++;
1781 for (i = 0; i < msg->nheaders; i++) {
1782 sig = msg->header[i].sig;
1783 if (sig == NULL || sig->state != DKIM_UNKNOWN)
1784 continue;
1785 if (wsp &&
1786 (sig->c & CANON_BODY) == CANON_BODY_RELAXED) {
1787 hash = " ";
1788 len = end[0] == '\0' ? 0 : 1;
1789 } else {
1790 hash = line;
1791 len = (size_t)(end - line);
1793 hashn = sig->l == -1 ? len : MIN(len, (size_t)sig->l);
1794 sig->l -= sig->l == -1 ? 0 : hashn;
1795 ret = EVP_DigestUpdate(sig->bhctx, hash, hashn);
1796 if (ret == 0)
1797 osmtpd_err(1, "EVP_DigestUpdate");
1799 line = end;
1801 for (i = 0; i < msg->nheaders; i++) {
1802 sig = msg->header[i].sig;
1803 if (sig == NULL || sig->state != DKIM_UNKNOWN)
1804 continue;
1805 hashn = sig->l == -1 ? 2 : MIN(2, sig->l);
1806 sig->l -= sig->l == -1 ? 0 : hashn;
1807 ret = EVP_DigestUpdate(sig->bhctx, "\r\n", hashn);
1808 if (ret == 0)
1809 osmtpd_err(1, "EVP_DigestUpdate");
1813 void
1814 dkim_body_verify(struct dkim_signature *sig)
1816 unsigned char digest[EVP_MAX_MD_SIZE];
1817 unsigned int digestsz;
1819 if (sig->state != DKIM_UNKNOWN)
1820 return;
1822 if ((sig->c & CANON_BODY) == CANON_BODY_SIMPLE &&
1823 !sig->header->msg->has_body) {
1824 if (EVP_DigestUpdate(sig->bhctx, "\r\n",
1825 sig->l == -1 ? 2 : MIN(2, sig->l)) <= 0)
1826 osmtpd_errx(1, "EVP_DigestUpdate");
1828 if (sig->l > 0) {
1829 dkim_signature_state(sig, DKIM_PERMERROR,
1830 "l tag larger than body");
1831 return;
1834 if (EVP_DigestFinal_ex(sig->bhctx, digest, &digestsz) == 0)
1835 osmtpd_err(1, "EVP_DigestFinal_ex");
1837 if (digestsz != sig->bhsz || memcmp(digest, sig->bh, digestsz) != 0)
1838 dkim_signature_state(sig, DKIM_FAIL, "bh mismatch");
1841 const char *
1842 iprev_state2str(enum iprev_state state)
1844 switch (state)
1846 case IPREV_NONE:
1847 return "none";
1848 case IPREV_PASS:
1849 return "pass";
1850 case IPREV_FAIL:
1851 return "fail";
1855 char *
1856 spf_evaluate_domain(struct spf_record *spf, const char *domain)
1858 struct session *ses = spf->ctx->local_session;
1860 char spec[HOST_NAME_MAX + 1];
1861 char macro[HOST_NAME_MAX + 1], smacro[sizeof(macro)];
1862 char delimiters[sizeof(".-+,/_=")];
1863 char *endptr, *tmp;
1864 const u_char *addr;
1865 size_t i, mlen;
1866 long digits;
1867 int reverse;
1869 if (domain == NULL || domain[0] == '\0') {
1870 spf_done(spf, SPF_PERMERROR, "Empty domain");
1871 return NULL;
1874 for (i = 0;
1875 domain[0] != ' ' && domain[0] != '\0' && i < sizeof(spec);
1876 domain++) {
1878 if (domain[0] < 0x21 || domain[0] > 0x7e) {
1879 spf_done(
1880 spf, SPF_PERMERROR, "Invalid character in domain-spec");
1881 return NULL;
1884 if (domain[0] != '%') {
1885 spec[i++] = domain[0];
1886 continue;
1888 domain++;
1890 switch (domain[0]) {
1891 case '%':
1892 spec[i++] = '%';
1893 break;
1894 case '_':
1895 spec[i++] = ' ';
1896 break;
1897 case '-':
1898 if (i + 3 >= sizeof(spec)) {
1899 spf_done(
1900 spf, SPF_PERMERROR, "domain-spec too large");
1901 return NULL;
1904 spec[i++] = '%';
1905 spec[i++] = '2';
1906 spec[i++] = '0';
1907 break;
1908 case '{':
1909 domain++;
1910 digits = -1;
1911 reverse = 0;
1912 delimiters[0] = '\0';
1914 switch (domain[0]) {
1915 case 'S':
1916 case 's':
1917 mlen = (size_t) snprintf(macro, sizeof(macro),
1918 "%s@%s", spf->sender_local,
1919 spf->sender_domain);
1920 break;
1921 case 'L':
1922 case 'l':
1923 mlen = strlcpy(macro,
1924 spf->sender_local, sizeof(macro));
1925 break;
1926 case 'O':
1927 case 'o':
1928 mlen = strlcpy(macro,
1929 spf->sender_domain,
1930 sizeof(macro));
1931 break;
1932 case 'D':
1933 case 'd':
1934 if (spf->nqueries < 1) {
1935 spf_done(spf, SPF_PERMERROR,
1936 "no domain for d macro");
1937 return NULL;
1939 mlen = strlcpy(macro,
1940 spf->queries[spf->nqueries - 1].domain,
1941 sizeof(macro));
1942 break;
1943 case 'I':
1944 case 'i':
1945 if (ses->src.ss_family == AF_INET) {
1946 addr = (u_char *)(&((struct sockaddr_in *)
1947 &(ses->src))->sin_addr);
1948 mlen = snprintf(macro, sizeof(macro),
1949 "%u.%u.%u.%u",
1950 (addr[0] & 0xff), (addr[1] & 0xff),
1951 (addr[2] & 0xff), (addr[3] & 0xff));
1952 } else if (ses->src.ss_family == AF_INET6) {
1953 addr = (u_char *)(&((struct sockaddr_in6 *)
1954 &(ses->src))->sin6_addr);
1955 mlen = snprintf(macro, sizeof(macro),
1956 "%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx."
1957 "%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx."
1958 "%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx."
1959 "%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx.%hhx",
1960 (u_char) ((addr[0] >> 4) & 0x0f), (u_char) (addr[0] & 0x0f),
1961 (u_char) ((addr[1] >> 4) & 0x0f), (u_char) (addr[1] & 0x0f),
1962 (u_char) ((addr[2] >> 4) & 0x0f), (u_char) (addr[2] & 0x0f),
1963 (u_char) ((addr[3] >> 4) & 0x0f), (u_char) (addr[3] & 0x0f),
1964 (u_char) ((addr[4] >> 4) & 0x0f), (u_char) (addr[4] & 0x0f),
1965 (u_char) ((addr[5] >> 4) & 0x0f), (u_char) (addr[5] & 0x0f),
1966 (u_char) ((addr[6] >> 4) & 0x0f), (u_char) (addr[6] & 0x0f),
1967 (u_char) ((addr[7] >> 4) & 0x0f), (u_char) (addr[7] & 0x0f),
1968 (u_char) ((addr[8] >> 4) & 0x0f), (u_char) (addr[8] & 0x0f),
1969 (u_char) ((addr[9] >> 4) & 0x0f), (u_char) (addr[9] & 0x0f),
1970 (u_char) ((addr[10] >> 4) & 0x0f), (u_char) (addr[10] & 0x0f),
1971 (u_char) ((addr[11] >> 4) & 0x0f), (u_char) (addr[11] & 0x0f),
1972 (u_char) ((addr[12] >> 4) & 0x0f), (u_char) (addr[12] & 0x0f),
1973 (u_char) ((addr[13] >> 4) & 0x0f), (u_char) (addr[13] & 0x0f),
1974 (u_char) ((addr[14] >> 4) & 0x0f), (u_char) (addr[14] & 0x0f),
1975 (u_char) ((addr[15] >> 4) & 0x0f), (u_char) (addr[15] & 0x0f));
1976 } else {
1977 spf_done(spf, SPF_PERMERROR,
1978 "unsupported type of address");
1979 return NULL;
1981 break;
1982 case 'P':
1983 case 'p':
1984 mlen = strlcpy(macro, ses->rdns, sizeof(macro));
1985 break;
1986 case 'V':
1987 case 'v':
1988 if (ses->src.ss_family == AF_INET)
1989 mlen = strlcpy(macro, "in-addr",
1990 sizeof(macro));
1991 else if (ses->src.ss_family == AF_INET6)
1992 mlen = strlcpy(macro, "ip6",
1993 sizeof(macro));
1994 else {
1995 spf_done(spf, SPF_PERMERROR,
1996 "unsupported type of address");
1997 return NULL;
1999 break;
2000 case 'H':
2001 case 'h':
2002 mlen = strlcpy(macro, ses->identity,
2003 sizeof(macro));
2004 break;
2005 default:
2006 spf_done(spf, SPF_PERMERROR,
2007 "Unexpected macro in domain-spec");
2008 return NULL;
2011 if (mlen >= sizeof(macro)) {
2012 spf_done(spf, SPF_PERMERROR,
2013 "Macro expansions too large");
2014 return NULL;
2017 domain++;
2018 if (isdigit(domain[0])) {
2019 digits = strtol(domain, &endptr, 10);
2020 if (digits < 1) {
2021 spf_done(spf, SPF_PERMERROR,
2022 "digits in macro can't be 0");
2023 return NULL;
2025 domain = endptr;
2028 if (domain[0] == 'r') {
2029 domain++;
2030 reverse = 1;
2033 for (; strchr(".-+,/_=", domain[0]) != NULL; domain++) {
2034 if (strchr(delimiters, domain[0]) == NULL) {
2035 delimiters[strlen(delimiters) + 1] = '\0';
2036 delimiters[strlen(delimiters)] = domain[0];
2040 if (delimiters[0] == '\0') {
2041 delimiters[0] = '.';
2042 delimiters[1] = '\0';
2045 if (domain[0] != '}') {
2046 spf_done(spf, SPF_PERMERROR,
2047 "Mallformed macro, expected end");
2048 return NULL;
2051 if (reverse) {
2052 smacro[0] = '\0';
2053 tmp = macro + strlen(macro) - 1;
2055 * DIGIT rightmost elements after reversal is DIGIT
2056 * lefmost elements before reversal
2058 while (1) {
2059 while (tmp > macro &&
2060 strchr(delimiters, tmp[0]) == NULL)
2061 tmp--;
2062 if (tmp == macro)
2063 break;
2064 if (digits == 0)
2065 break;
2066 if (digits > 0)
2067 digits--;
2069 tmp[0] = '\0';
2070 if (smacro[0] != '\0')
2071 strlcat(smacro, ".", sizeof(smacro));
2072 strlcat(smacro, tmp + 1, sizeof(smacro));
2073 tmp--;
2075 if (digits != 0) {
2076 if (smacro[0] != '\0')
2077 strlcat(smacro, ".", sizeof(smacro));
2078 strlcat(smacro, macro, sizeof(smacro));
2080 } else {
2081 if (digits != -1) {
2082 tmp = macro;
2083 endptr = macro + strlen(macro);
2084 while (digits > 0) {
2085 while (tmp < endptr &&
2086 strchr(delimiters, tmp[0]) == NULL)
2087 tmp++;
2088 if (tmp == endptr)
2089 break;
2090 if (digits == 1) {
2091 tmp[0] = '\0';
2092 break;
2094 digits--;
2095 tmp++;
2098 strlcpy(smacro, macro, sizeof(smacro));
2101 spec[i] = '\0';
2102 i = strlcat(spec, smacro, sizeof(spec));
2103 if (i >= sizeof(spec)) {
2104 spf_done(
2105 spf, SPF_PERMERROR, "domain-spec too large");
2106 return NULL;
2108 break;
2110 default:
2111 spf_done(spf, SPF_PERMERROR,
2112 "Mallformed macro, unexpected character after %");
2113 return NULL;
2117 if ((tmp = strndup(spec, i)) == NULL)
2118 osmtpd_err(1, "%s: strndup", __func__);
2120 return tmp;
2123 void
2124 spf_lookup_record(struct spf_record *spf, const char *domain, int type,
2125 enum spf_state qualifier, int include, int exists)
2127 struct asr_query *aq;
2128 struct spf_query *query;
2130 if (spf->done)
2131 return;
2133 if (spf->nqueries >= SPF_DNS_LOOKUP_LIMIT) {
2134 spf_done(spf, SPF_PERMERROR, "To many DNS queries");
2135 return;
2138 query = &spf->queries[spf->nqueries];
2139 query->spf = spf;
2140 query->type = type;
2141 query->q = qualifier;
2142 query->include = include;
2143 query->exists = exists;
2144 query->txt = NULL;
2145 query->eva = NULL;
2147 if ((query->domain = spf_evaluate_domain(spf, domain)) == NULL)
2148 return;
2150 if (domain == NULL || !strlen(domain)) {
2151 spf_done(spf, SPF_PERMERROR, "Empty domain");
2152 return;
2155 if ((aq = res_query_async(query->domain, C_IN, type, NULL)) == NULL)
2156 osmtpd_err(1, "res_query_async");
2158 if ((query->eva = event_asr_run(aq, spf_resolve, query)) == NULL)
2159 osmtpd_err(1, "event_asr_run");
2161 spf->running++;
2162 spf->nqueries++;
2165 void
2166 spf_resolve(struct asr_result *ar, void *arg)
2168 int i;
2170 struct spf_query *query = arg;
2171 struct spf_record *spf = query->spf;
2172 struct unpack pack;
2173 struct dns_header h;
2174 struct dns_query q;
2175 struct dns_rr rr;
2176 char buf[HOST_NAME_MAX + 1];
2178 query->eva = NULL;
2179 query->spf->running--;
2181 if (ar->ar_h_errno == TRY_AGAIN
2182 || ar->ar_h_errno == NO_RECOVERY) {
2183 spf_done(query->spf, SPF_TEMPERROR, hstrerror(ar->ar_h_errno));
2184 goto end;
2187 if (ar->ar_h_errno == HOST_NOT_FOUND) {
2188 if (query->include && !query->exists)
2189 spf_done(query->spf,
2190 SPF_PERMERROR, hstrerror(ar->ar_h_errno));
2191 goto consume;
2194 unpack_init(&pack, ar->ar_data, ar->ar_datalen);
2195 if (unpack_header(&pack, &h) != 0 ||
2196 unpack_query(&pack, &q) != 0) {
2197 osmtpd_warn(query->spf->ctx,
2198 "Mallformed SPF DNS response for domain %s: %s",
2199 print_dname(q.q_dname, buf, sizeof(buf)),
2200 pack.err);
2201 spf_done(query->spf, SPF_TEMPERROR, pack.err);
2202 goto end;
2205 for (; h.ancount; h.ancount--) {
2206 if (unpack_rr(&pack, &rr) != 0) {
2207 osmtpd_warn(query->spf->ctx,
2208 "Mallformed SPF DNS record for domain %s: %s",
2209 print_dname(q.q_dname, buf, sizeof(buf)),
2210 pack.err);
2211 continue;
2214 switch (rr.rr_type)
2216 case T_TXT:
2217 spf_resolve_txt(&rr, query);
2218 break;
2220 case T_MX:
2221 spf_resolve_mx(&rr, query);
2222 break;
2224 case T_A:
2225 spf_resolve_a(&rr, query);
2226 break;
2228 case T_AAAA:
2229 spf_resolve_aaaa(&rr, query);
2230 break;
2232 case T_CNAME:
2233 spf_resolve_cname(&rr, query);
2234 break;
2236 default:
2237 osmtpd_warn(spf->ctx,
2238 "Unexpected SPF DNS record: %d for domain %s",
2239 rr.rr_type, query->domain);
2240 spf_done(query->spf, SPF_TEMPERROR, "Unexpected record");
2241 break;
2244 if (spf->done)
2245 goto end;
2248 consume:
2249 if (spf->running > 0)
2250 goto end;
2252 for (i = spf->nqueries - 1; i >= 0; i--) {
2253 if (spf->queries[i].txt != NULL) {
2254 if (spf_execute_txt(&spf->queries[i]) != 0)
2255 break;
2259 end:
2260 free(ar->ar_data);
2261 if (!spf->done && spf->running == 0)
2262 spf_done(spf, SPF_NONE, NULL);
2265 void
2266 spf_resolve_txt(struct dns_rr *rr, struct spf_query *query)
2268 char *txt;
2269 txt = spf_parse_txt(rr->rr.other.rdata, rr->rr.other.rdlen);
2270 if (txt == NULL) {
2271 osmtpd_warn(NULL, "spf_parse_txt");
2272 return;
2275 if (strncasecmp("v=spf1 ", txt, 7)) {
2276 free(txt);
2277 return;
2280 if (query->txt != NULL) {
2281 free(txt);
2282 spf_done(query->spf, SPF_PERMERROR, "Duplicated SPF record");
2283 return;
2286 query->txt = txt;
2287 query->pos = 0;
2288 spf_execute_txt(query);
2291 void
2292 spf_resolve_mx(struct dns_rr *rr, struct spf_query *query)
2294 char buf[HOST_NAME_MAX + 1];
2296 char *domain = print_dname(rr->rr.mx.exchange, buf, sizeof(buf));
2298 spf_lookup_record(query->spf, domain, T_A,
2299 query->q, query->include, 0);
2300 spf_lookup_record(query->spf, domain, T_AAAA,
2301 query->q, query->include, 0);
2304 void
2305 spf_resolve_a(struct dns_rr *rr, struct spf_query *query)
2307 if (query->exists ||
2308 spf_check_cidr(query->spf, &rr->rr.in_a.addr, 32) == 0) {
2309 spf_done(query->spf, query->q, NULL);
2313 void
2314 spf_resolve_aaaa(struct dns_rr *rr, struct spf_query *query)
2316 if (spf_check_cidr6(query->spf, &rr->rr.in_aaaa.addr6, 128) == 0) {
2317 spf_done(query->spf, query->q, NULL);
2321 void
2322 spf_resolve_cname(struct dns_rr *rr, struct spf_query *query)
2324 char buf[HOST_NAME_MAX + 1];
2326 char *domain = print_dname(rr->rr.cname.cname, buf, sizeof(buf));
2328 spf_lookup_record(query->spf, domain, query->type,
2329 query->q, query->include, 0);
2332 char *
2333 spf_parse_txt(const char *rdata, size_t rdatalen)
2335 size_t len, dstsz = SPF_RECORD_MAX - 1;
2336 ssize_t r = 0;
2337 char *dst, *odst;
2339 if (rdatalen >= dstsz) {
2340 errno = EOVERFLOW;
2341 return NULL;
2344 odst = dst = malloc(dstsz);
2345 if (dst == NULL)
2346 osmtpd_err(1, "%s: malloc", __func__);
2348 while (rdatalen) {
2349 len = *(const unsigned char *)rdata;
2350 if (len >= rdatalen) {
2351 errno = EINVAL;
2352 return NULL;
2355 rdata++;
2356 rdatalen--;
2358 if (len == 0)
2359 continue;
2361 if (len >= dstsz) {
2362 errno = EOVERFLOW;
2363 return NULL;
2365 memmove(dst, rdata, len);
2366 dst += len;
2367 dstsz -= len;
2369 rdata += len;
2370 rdatalen -= len;
2371 r += len;
2374 odst[r] = '\0';
2376 return odst;
2379 int
2380 spf_check_cidr(struct spf_record *spf, struct in_addr *net, int bits)
2382 struct in_addr *addr;
2383 struct session *ses = spf->ctx->local_session;
2385 if (ses->src.ss_family != AF_INET)
2386 return -1;
2388 if (bits == 0)
2389 return 0;
2391 addr = &(((struct sockaddr_in *)(&ses->src))->sin_addr);
2393 return ((addr->s_addr ^ net->s_addr) & htonl(0xFFFFFFFFu << (32 - bits)));
2396 int
2397 spf_check_cidr6(struct spf_record *spf, struct in6_addr *net, int bits)
2399 int rc;
2400 uint32_t *a, *n, whole, incomplete;
2401 struct in6_addr *addr;
2402 struct session *ses = spf->ctx->local_session;
2404 if (ses->src.ss_family != AF_INET6)
2405 return -1;
2407 if (bits == 0)
2408 return 0;
2410 addr = &(((struct sockaddr_in6 *)(&ses->src))->sin6_addr);
2412 a = addr->__u6_addr.__u6_addr32;
2413 n = net->__u6_addr.__u6_addr32;
2415 whole = bits >> 5;
2416 incomplete = bits & 0x1f;
2417 if (whole) {
2418 rc = memcmp(a, n, whole << 2);
2419 if (rc)
2420 return rc;
2422 if (incomplete)
2423 return (a[whole] ^ n[whole]) & htonl((0xffffffffu) << (32 - incomplete));
2425 return 0;
2428 int
2429 spf_execute_txt(struct spf_query *query)
2431 struct in_addr ina;
2432 struct in6_addr in6a;
2433 char *ap = NULL;
2434 char *in = query->txt + query->pos;
2435 char *end;
2436 int bits;
2438 enum spf_state q = query->q;
2440 while ((ap = strsep(&in, " ")) != NULL) {
2441 if (strcasecmp(ap, "v=spf1") == 0)
2442 continue;
2444 end = ap + strlen(ap)-1;
2445 if (*end == '.')
2446 *end = '\0';
2448 if (*ap == '+') {
2449 q = SPF_PASS;
2450 ap++;
2451 } else if (*ap == '-') {
2452 q = SPF_FAIL;
2453 ap++;
2454 } else if (*ap == '~') {
2455 q = SPF_SOFTFAIL;
2456 ap++;
2457 } else if (*ap == '?') {
2458 q = SPF_NEUTRAL;
2459 ap++;
2462 if (q != SPF_PASS && query->include)
2463 continue;
2465 if (strncasecmp("all", ap, 3) == 0) {
2466 spf_done(query->spf, q, NULL);
2467 return 0;
2469 if (strncasecmp("ip4:", ap, 4) == 0) {
2470 if ((bits = inet_net_pton(AF_INET, ap + 4, &ina, sizeof(ina))) == -1)
2471 continue;
2473 if (spf_check_cidr(query->spf, &ina, bits) == 0) {
2474 spf_done(query->spf, q, NULL);
2475 return 0;
2477 continue;
2479 if (strncasecmp("ip6:", ap, 4) == 0) {
2480 if ((bits = inet_net_pton(AF_INET6, ap + 4, &ina, sizeof(ina))) == -1)
2481 continue;
2483 if (spf_check_cidr6(query->spf, &in6a, bits) == 0) {
2484 spf_done(query->spf, q, NULL);
2485 return 0;
2487 continue;
2489 if (strcasecmp("a", ap) == 0) {
2490 spf_lookup_record(query->spf, query->domain, T_A,
2491 q, query->include, 0);
2492 spf_lookup_record(query->spf, query->domain, T_AAAA,
2493 q, query->include, 0);
2494 break;
2496 if (strncasecmp("a:", ap, 2) == 0) {
2497 spf_lookup_record(query->spf, ap + 2, T_A,
2498 q, query->include, 0);
2499 spf_lookup_record(query->spf, ap + 2, T_AAAA,
2500 q, query->include, 0);
2501 break;
2503 if (strncasecmp("exists:", ap, 7) == 0) {
2504 spf_lookup_record(query->spf, ap + 7, T_A,
2505 q, query->include, 1);
2506 break;
2508 if (strncasecmp("include:", ap, 8) == 0) {
2509 spf_lookup_record(query->spf, ap + 8, T_TXT, q, 1, 0);
2510 break;
2512 if (strncasecmp("redirect=", ap, 9) == 0) {
2513 if (in != NULL)
2514 continue;
2515 spf_lookup_record(query->spf, ap + 9, T_TXT,
2516 q, query->include, 0);
2517 return 0;
2519 if (strcasecmp("mx", ap) == 0) {
2520 spf_lookup_record(query->spf, query->domain, T_MX,
2521 q, query->include, 0);
2522 break;
2524 if (strncasecmp("mx:", ap, 3) == 0) {
2525 spf_lookup_record(query->spf, ap + 3, T_MX,
2526 q, query->include, 0);
2527 break;
2531 if (in == NULL)
2532 return 0;
2534 query->pos = in - query->txt;
2536 return query->pos;
2539 void
2540 spf_done(struct spf_record *spf, enum spf_state state, const char *reason)
2542 int i;
2544 if (spf->done)
2545 return;
2547 for (i = 0; i < spf->nqueries; i++) {
2548 if (spf->queries[i].eva) {
2549 event_asr_abort(spf->queries[i].eva);
2550 spf->queries[i].eva = NULL;
2554 spf->nqueries = 0;
2555 spf->running = 0;
2556 spf->state = state;
2557 spf->state_reason = reason;
2558 spf->done = 1;
2560 osmtpd_filter_proceed(spf->ctx);
2563 const char *
2564 spf_state2str(enum spf_state state)
2566 switch (state)
2568 case SPF_NONE:
2569 return "none";
2570 case SPF_NEUTRAL:
2571 return "neutral";
2572 case SPF_PASS:
2573 return "pass";
2574 case SPF_FAIL:
2575 return "fail";
2576 case SPF_SOFTFAIL:
2577 return "softfail";
2578 case SPF_TEMPERROR:
2579 return "temperror";
2580 case SPF_PERMERROR:
2581 return "permerror";
2585 int
2586 spf_ar_cat(const char *type, struct spf_record *spf, char **line, size_t *linelen, ssize_t *aroff)
2588 if (spf == NULL) {
2589 if ((*aroff =
2590 auth_ar_cat(line, linelen, *aroff,
2591 "; spf=none %s=none", type)
2592 ) == -1) {
2593 return -1;
2595 return 0;
2598 if ((*aroff =
2599 auth_ar_cat(line, linelen, *aroff,
2600 "; spf=%s", spf_state2str(spf->state))
2601 ) == -1) {
2602 return -1;
2605 if ((*aroff =
2606 auth_ar_cat(line, linelen, *aroff,
2607 " %s=%s@%s",
2608 type,
2609 spf->sender_local,
2610 spf->sender_domain)
2611 ) == -1) {
2612 return -1;
2615 if (spf->state_reason != NULL) {
2616 if ((*aroff =
2617 auth_ar_cat(line, linelen, *aroff,
2618 " reason=\"%s\"", spf->state_reason)
2619 ) == -1) {
2620 return -1;
2624 return 0;
2627 void
2628 auth_message_verify(struct message *msg)
2630 size_t i;
2632 if (!msg->readdone || msg->nqueries > 0)
2633 return;
2635 for (i = 0; i < msg->nheaders; i++) {
2636 if (msg->header[i].sig == NULL)
2637 continue;
2638 if (msg->header[i].sig->query != NULL)
2639 return;
2640 if (msg->header[i].sig->state != DKIM_UNKNOWN)
2641 continue;
2642 dkim_signature_state(msg->header[i].sig, DKIM_PASS, NULL);
2645 auth_ar_create(msg->ctx);
2648 void
2649 auth_ar_create(struct osmtpd_ctx *ctx)
2651 struct dkim_signature *sig;
2652 size_t i;
2653 ssize_t n, aroff = 0;
2654 int found = 0;
2655 char *line = NULL;
2656 size_t linelen = 0;
2657 struct session *ses = ctx->local_session;
2658 struct message *msg = ctx->local_message;
2660 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2661 "Authentication-Results: %s", authservid)) == -1)
2662 osmtpd_err(1, "%s: malloc", __func__);
2663 for (i = 0; i < msg->nheaders; i++) {
2664 sig = msg->header[i].sig;
2665 if (sig == NULL)
2666 continue;
2667 found = 1;
2668 if ((aroff = auth_ar_cat(&line, &linelen, aroff, "; dkim=%s",
2669 dkim_state2str(sig->state))) == -1)
2670 osmtpd_err(1, "%s: malloc", __func__);
2671 if (sig->state_reason != NULL) {
2672 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2673 " reason=\"%s\"", sig->state_reason)) == -1)
2674 osmtpd_err(1, "%s: malloc", __func__);
2676 if (sig->s[0] != '\0') {
2677 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2678 " header.s=%s", sig->s)) == -1)
2679 osmtpd_err(1, "%s: malloc", __func__);
2681 if (sig->d[0] != '\0') {
2682 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2683 " header.d=%s", sig->d)) == -1)
2684 osmtpd_err(1, "%s: malloc", __func__);
2687 * Don't print i-tag, since localpart can be a quoted-string,
2688 * which can contain FWS and CFWS.
2690 if (sig->a != NULL) {
2691 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2692 " header.a=%.*s", (int)sig->asz, sig->a)) == -1)
2693 osmtpd_err(1, "%s: malloc", __func__);
2695 if (sig->bheaderclean[0] != '\0') {
2696 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2697 " header.b=%s", sig->bheaderclean)) == -1)
2698 osmtpd_err(1, "%s: malloc", __func__);
2701 if (!found) {
2702 aroff = auth_ar_cat(&line, &linelen, aroff, "; dkim=none");
2703 if (aroff == -1)
2704 osmtpd_err(1, "%s: malloc", __func__);
2707 if ((aroff = auth_ar_cat(&line, &linelen, aroff,
2708 "; iprev=%s", iprev_state2str(ses->iprev))) == -1)
2709 osmtpd_err(1, "%s: malloc", __func__);
2711 if (spf_ar_cat("smtp.helo", ses->spf_helo,
2712 &line, &linelen, &aroff) != 0)
2713 osmtpd_err(1, "%s: malloc", __func__);
2715 if (ses->spf_mailfrom != NULL) {
2716 if (spf_ar_cat("smtp.mailfrom", ses->spf_mailfrom,
2717 &line, &linelen, &aroff) != 0)
2718 osmtpd_err(1, "%s: malloc", __func__);
2719 } else {
2720 if (spf_ar_cat("smtp.mailfrom", ses->spf_helo,
2721 &line, &linelen, &aroff) != 0)
2722 osmtpd_err(1, "%s: malloc", __func__);
2725 if (aroff == -1)
2726 osmtpd_err(1, "%s: malloc", __func__);
2728 if (auth_ar_print(msg->ctx, line) != 0)
2729 osmtpd_warn(msg->ctx, "Invalid AR line: %s", line);
2731 rewind(msg->origf);
2732 while ((n = getline(&line, &linelen, msg->origf)) != -1) {
2733 line[n - 1] = '\0';
2734 osmtpd_filter_dataline(msg->ctx, "%s", line);
2736 if (ferror(msg->origf))
2737 osmtpd_err(1, "%s: ferror", __func__);
2738 free(line);
2739 return;
2742 int
2743 auth_ar_print(struct osmtpd_ctx *ctx, const char *start)
2745 const char *scan, *checkpoint, *ncheckpoint;
2746 int arlen = 0, first = 1, arid = 1;
2748 checkpoint = start;
2749 ncheckpoint = osmtpd_ltok_skip_hdr_name(start, 0) + 1;
2750 for (scan = start; scan[0] != '\0'; scan++) {
2751 if (scan[0] == '\t')
2752 arlen = (arlen + 8) & ~7;
2753 else
2754 arlen++;
2755 if (arlen >= AUTHENTICATION_RESULTS_LINELEN) {
2756 arlen = (int)(checkpoint - start);
2757 if (arlen <= 0) {
2758 arlen = (int)(ncheckpoint - start);
2759 checkpoint = ncheckpoint;
2761 osmtpd_filter_dataline(ctx, "%s%.*s", first ? "" : "\t",
2762 arlen, start);
2763 start = osmtpd_ltok_skip_cfws(checkpoint, 1);
2764 if (*start == '\0')
2765 return 0;
2766 ncheckpoint = start;
2767 scan = start;
2768 arlen = 8;
2769 first = 0;
2771 if (scan == ncheckpoint) {
2772 checkpoint = ncheckpoint;
2773 ncheckpoint = osmtpd_ltok_skip_cfws(ncheckpoint, 1);
2774 /* authserv-id */
2775 if (arid) {
2776 ncheckpoint = osmtpd_ltok_skip_value(
2777 ncheckpoint, 0);
2778 arid = 0;
2779 /* methodspec */
2780 } else if (strncmp(ncheckpoint, "dkim=",
2781 sizeof("dkim=") - 1) == 0) {
2782 ncheckpoint = osmtpd_ltok_skip_keyword(
2783 ncheckpoint + sizeof("dkim=") - 1, 0);
2784 } else if (strncmp(ncheckpoint, "iprev=",
2785 sizeof("iprev=") - 1) == 0) {
2786 ncheckpoint = osmtpd_ltok_skip_keyword(
2787 ncheckpoint + sizeof("iprev=") - 1, 0);
2788 } else if (strncmp(ncheckpoint, "spf=",
2789 sizeof("spf=") - 1) == 0) {
2790 ncheckpoint = osmtpd_ltok_skip_keyword(
2791 ncheckpoint + sizeof("spf=") - 1, 0);
2792 /* reasonspec */
2793 } else if (strncmp(ncheckpoint, "reason=",
2794 sizeof("reason=") - 1) == 0) {
2795 ncheckpoint = osmtpd_ltok_skip_ar_reasonspec(
2796 ncheckpoint, 0);
2797 /* propspec */
2798 } else {
2799 ncheckpoint = osmtpd_ltok_skip_ar_propspec(
2800 ncheckpoint, 0);
2803 if (ncheckpoint == NULL)
2804 return -1;
2806 if (*ncheckpoint == ';')
2807 ncheckpoint++;
2810 osmtpd_filter_dataline(ctx, "%s%s", first ? "" : "\t", start);
2811 return 0;
2814 ssize_t
2815 auth_ar_cat(char **ar, size_t *n, size_t aroff, const char *fmt, ...)
2817 va_list ap;
2818 char *artmp;
2819 int size;
2820 size_t nn;
2822 va_start(ap, fmt);
2823 size = vsnprintf(*ar + aroff, *n - aroff, fmt, ap);
2824 va_end(ap);
2825 if (size + aroff < *n)
2826 return (ssize_t)size + aroff;
2827 nn = (((aroff + size) / 256) + 1) * 256;
2828 artmp = realloc(*ar, nn);
2829 if (artmp == NULL)
2830 return -1;
2831 *ar = artmp;
2832 *n = nn;
2833 va_start(ap, fmt);
2834 size = vsnprintf(*ar + aroff, *n - aroff, fmt, ap);
2835 va_end(ap);
2836 return (ssize_t)size + aroff;
2839 __dead void
2840 usage(void)
2842 fprintf(stderr, "usage: filter-auth\n");
2843 exit(1);