xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_dane.c (revision c48c605c14fd8622b523d1d6a3f0c0bad133ea89)
1 /*	$NetBSD: tls_dane.c,v 1.5 2023/12/23 20:30:45 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	tls_dane 3
6 /* SUMMARY
7 /*	Support for RFC 6698, 7671, 7672 (DANE) certificate matching
8 /* SYNOPSIS
9 /*	#include <tls.h>
10 /*
11 /*	void tls_dane_loglevel(log_param, log_level);
12 /*	const char *log_param;
13 /*	const char *log_level;
14 /*
15 /*	int	tls_dane_avail()
16 /*
17 /*	void	tls_dane_flush()
18 /*
19 /*	TLS_DANE *tls_dane_alloc()
20 /*
21 /*      void    tls_tlsa_free(tlsa)
22 /*      TLS_TLSA *tlsa;
23 /*
24 /*	void	tls_dane_free(dane)
25 /*	TLS_DANE *dane;
26 /*
27 /*	void	tls_dane_add_fpt_digests(dane, digest, delim, smtp_mode)
28 /*	TLS_DANE *dane;
29 /*	const char *digest;
30 /*	const char *delim;
31 /*	int     smtp_mode;
32 /*
33 /*	TLS_TLSA *tlsa_prepend(tlsa, usage, selector, mtype, data, len)
34 /*	TLS_TLSA *tlsa;
35 /*	uint8_t usage;
36 /*	uint8_t selector;
37 /*	uint8_t mtype;
38 /*	const unsigned char *data;
39 /*	uint16_t length;
40 /*
41 /*	int	tls_dane_load_trustfile(dane, tafile)
42 /*	TLS_DANE *dane;
43 /*	const char *tafile;
44 /*
45 /*	TLS_DANE *tls_dane_resolve(port, proto, hostrr, forcetlsa)
46 /*	unsigned port;
47 /*	const char *proto;
48 /*	DNS_RR *hostrr;
49 /*	int	forcetlsa;
50 /*
51 /*	void	tls_dane_digest_init(ctx, fpt_alg)
52 /*	SSL_CTX *ctx;
53 /*	const EVP_MD *fpt_alg;
54 /*
55 /*	void	tls_dane_enable(TLScontext)
56 /*	TLS_SESS_STATE *TLScontext;
57 /*
58 /*	void    tls_dane_log(TLScontext)
59 /*	TLS_SESS_STATE *TLScontext;
60 /*
61 /*	int	tls_dane_unusable(dane)
62 /*	const TLS_DANE *dane;
63 /*
64 /*	int	tls_dane_notfound(dane)
65 /*	const TLS_DANE *dane;
66 /* DESCRIPTION
67 /*	tls_dane_loglevel() allows the policy lookup functions in the DANE
68 /*	library to examine the application's TLS loglevel in and possibly
69 /*	produce a more detailed activity log.
70 /*
71 /*	tls_dane_avail() returns true if the features required to support DANE
72 /*	are present in libresolv.
73 /*
74 /*	tls_dane_flush() flushes all entries from the cache, and deletes
75 /*	the cache.
76 /*
77 /*	tls_dane_alloc() returns a pointer to a newly allocated TLS_DANE
78 /*	structure with null ta and ee digest sublists.
79 /*
80 /*	tls_tlsa_free() frees a TLSA record linked list.
81 /*
82 /*	tls_dane_free() frees the structure allocated by tls_dane_alloc().
83 /*
84 /*	tls_dane_digest_init() configures OpenSSL to support the configured
85 /*	DANE TLSA digests and private-use fingerprint digest.
86 /*
87 /*	tlsa_prepend() prepends a TLSA record to the head of a linked list
88 /*	which may be null when the list is empty. The result value is the
89 /*	new list head.
90 /*
91 /*	tls_dane_add_fpt_digests() splits "digest" using the characters in
92 /*	"delim" as delimiters and generates corresponding synthetic DANE TLSA
93 /*	records with matching type 255 (private-use), which we associated with
94 /*	the configured fingerprint digest algorithm.  This is an incremental
95 /*	interface, that builds a TLS_DANE structure outside the cache by
96 /*	manually adding entries.
97 /*
98 /*	tls_dane_load_trustfile() imports trust-anchor certificates and
99 /*	public keys from a file (rather than DNS TLSA records).
100 /*
101 /*	tls_dane_resolve() maps a (port, protocol, hostrr) tuple to a
102 /*	corresponding TLS_DANE policy structure found in the DNS.  The port
103 /*	argument is in network byte order.  A null pointer is returned when
104 /*	the DNS query for the TLSA record tempfailed.  In all other cases the
105 /*	return value is a pointer to the corresponding TLS_DANE structure.
106 /*	The caller must free the structure via tls_dane_free().
107 /*
108 /*	tls_dane_enable() enables DANE-style certificate checks for connections
109 /*	that are configured with TLSA records.  The TLSA records may be from
110 /*	DNS (at the "dane", "dane-only" and "half-dane" security levels), or be
111 /*	synthetic in support of either the "fingerprint" level or local trust
112 /*	anchor based validation with the "secure" and "verify" levels.  The
113 /*	return value is the number of "usable" TLSA records loaded, or negative
114 /*	if a record failed to load due to an internal OpenSSL problems, rather
115 /*	than an issue with the record making that record "unusable".
116 /*
117 /*	tls_dane_log() logs successful verification via DNS-based or
118 /*	synthetic DANE TLSA RRs (fingerprint or "tafile").
119 /*
120 /*	tls_dane_unusable() checks whether a cached TLS_DANE record is
121 /*	the result of a validated RRset, with no usable elements.  In
122 /*	this case, TLS is mandatory, but certificate verification is
123 /*	not DANE-based.
124 /*
125 /*	tls_dane_notfound() checks whether a cached TLS_DANE record is
126 /*	the result of a validated DNS lookup returning NODATA. In
127 /*	this case, TLS is not required by RFC, though users may elect
128 /*	a mandatory TLS fallback policy.
129 /*
130 /*	Arguments:
131 /* .IP  ctx
132 /*	SSL context to be configured with the chosen digest algorithms.
133 /* .IP  fpt_alg
134 /*	The OpenSSL EVP digest algorithm handle for the fingerprint digest.
135 /* .IP  tlsa
136 /*	TLSA record linked list head, initially NULL.
137 /* .IP  usage
138 /*	DANE TLSA certificate usage field.
139 /* .IP  selector
140 /*	DANE TLSA selector field.
141 /* .IP  mtype
142 /*	DANE TLSA matching type field
143 /* .IP  data
144 /*	DANE TLSA associated data field (raw binary form), copied for internal
145 /*	use.  The caller is responsible for freeing his own copy.
146 /* .IP  length
147 /*	Length of DANE TLSA associated DATA field.
148 /* .IP dane
149 /*	Pointer to a TLS_DANE structure that lists the valid trust-anchor
150 /*	and end-entity full-certificate and/or public-key digests.
151 /* .IP port
152 /*	The TCP port in network byte order.
153 /* .IP proto
154 /*	Almost certainly "tcp".
155 /* .IP hostrr
156 /*	DNS_RR pointer to TLSA base domain data.
157 /* .IP forcetlsa
158 /*	When true, TLSA lookups are performed even when the qname and rname
159 /*	are insecure.  This is only useful in the unlikely case that DLV is
160 /*	used to secure the TLSA RRset in an otherwise insecure zone.
161 /* .IP log_param
162 /*	The TLS log level parameter name whose value is the log_level argument.
163 /* .IP log_level
164 /*	The application TLS log level, which may affect dane lookup verbosity.
165 /* .IP digest
166 /*	The digest (or list of digests concatenated with characters from
167 /*	"delim") to be added to the TLS_DANE record.
168 /* .IP delim
169 /*	The set of delimiter characters used above.
170 /* .IP smtp_mode
171 /*	Is the caller an SMTP client or an LMTP client?
172 /* .IP tafile;
173 /*	A file with trust anchor certificates or public keys in PEM format.
174 /* LICENSE
175 /* .ad
176 /* .fi
177 /*	This software is free. You can do with it whatever you want.
178 /*	The original author kindly requests that you acknowledge
179 /*	the use of his software.
180 /* AUTHOR(S)
181 /*	Wietse Venema
182 /*	IBM T.J. Watson Research
183 /*	P.O. Box 704
184 /*	Yorktown Heights, NY 10598, USA
185 /*
186 /*	Wietse Venema
187 /*	Google, Inc.
188 /*	111 8th Avenue
189 /*	New York, NY 10011, USA
190 /*
191 /*	Viktor Dukhovni
192 /*--*/
193 
194 /* System library. */
195 
196 #include <sys_defs.h>
197 #include <ctype.h>
198 
199 #ifdef STRCASECMP_IN_STRINGS_H
200 #include <strings.h>
201 #endif
202 
203 #ifdef USE_TLS
204 #include <string.h>
205 
206 /* Utility library. */
207 
208 #include <msg.h>
209 #include <mymalloc.h>
210 #include <stringops.h>
211 #include <midna_domain.h>
212 #include <vstring.h>
213 #include <events.h>			/* event_time() */
214 #include <timecmp.h>
215 #include <ctable.h>
216 #include <hex_code.h>
217 #include <safe_ultostr.h>
218 #include <split_at.h>
219 #include <name_code.h>
220 
221 #define STR(x)	vstring_str(x)
222 
223 /* Global library */
224 
225 #include <mail_params.h>
226 
227 /* DNS library. */
228 
229 #include <dns.h>
230 
231 /* TLS library. */
232 
233 #define TLS_INTERNAL
234 #include <tls.h>
235 
236 /* Application-specific. */
237 
238 #undef DANE_TLSA_SUPPORT
239 
240 #if RES_USE_DNSSEC && RES_USE_EDNS0
241 #define DANE_TLSA_SUPPORT
242 static int dane_tlsa_support = 1;
243 
244 #else
245 static int dane_tlsa_support = 0;
246 
247 #endif
248 
249 /*
250  * A NULL alg field disables the algorithm at the codepoint passed to the
251  * SSL_CTX_dane_mtype_set(3) function.  The ordinals are used for digest
252  * agility, higher is "better" (presumed stronger).
253  */
254 typedef struct dane_mtype {
255     const EVP_MD *alg;
256     uint8_t ord;
257 } dane_mtype;
258 
259 /*
260  * This is not intended to be a long-term cache of pre-parsed TLSA data,
261  * rather we primarily want to avoid fetching and parsing the TLSA records
262  * for a single multi-homed MX host more than once per delivery. Therefore,
263  * we keep the table reasonably small.
264  */
265 #define CACHE_SIZE 20
266 static CTABLE *dane_cache;
267 
268 static int log_mask;
269 
270 /* tls_dane_logmask - configure policy lookup logging */
271 
tls_dane_loglevel(const char * log_param,const char * log_level)272 void    tls_dane_loglevel(const char *log_param, const char *log_level)
273 {
274     log_mask = tls_log_mask(log_param, log_level);
275 }
276 
277 /* tls_dane_avail - check for availability of dane required digests */
278 
tls_dane_avail(void)279 int     tls_dane_avail(void)
280 {
281     return (dane_tlsa_support);
282 }
283 
284 /* tls_dane_alloc - allocate a TLS_DANE structure */
285 
tls_dane_alloc(void)286 TLS_DANE *tls_dane_alloc(void)
287 {
288     TLS_DANE *dane = (TLS_DANE *) mymalloc(sizeof(*dane));
289 
290     dane->tlsa = 0;
291     dane->base_domain = 0;
292     dane->flags = 0;
293     dane->expires = 0;
294     dane->refs = 1;
295     return (dane);
296 }
297 
298 /* tls_tlsa_free - free a TLSA RR linked list */
299 
tls_tlsa_free(TLS_TLSA * tlsa)300 void    tls_tlsa_free(TLS_TLSA *tlsa)
301 {
302     TLS_TLSA *next;
303 
304     for (; tlsa; tlsa = next) {
305 	next = tlsa->next;
306 	myfree(tlsa->data);
307 	myfree(tlsa);
308     }
309 }
310 
311 /* tls_dane_free - free a TLS_DANE structure */
312 
tls_dane_free(TLS_DANE * dane)313 void    tls_dane_free(TLS_DANE *dane)
314 {
315     if (--dane->refs > 0)
316 	return;
317     if (dane->base_domain)
318 	myfree(dane->base_domain);
319     if (dane->tlsa)
320 	tls_tlsa_free(dane->tlsa);
321     myfree((void *) dane);
322 }
323 
324 /* tlsa_prepend - Prepend internal-form TLSA record to the RRset linked list */
325 
tlsa_prepend(TLS_TLSA * tlsa,uint8_t usage,uint8_t selector,uint8_t mtype,const unsigned char * data,uint16_t data_len)326 TLS_TLSA *tlsa_prepend(TLS_TLSA *tlsa, uint8_t usage, uint8_t selector,
327 		               uint8_t mtype, const unsigned char *data,
328 		               uint16_t data_len)
329 {
330     TLS_TLSA *head;
331 
332     head = (TLS_TLSA *) mymalloc(sizeof(*head));
333     head->usage = usage;
334     head->selector = selector;
335     head->mtype = mtype;
336     head->length = data_len;
337     head->data = (unsigned char *) mymemdup(data, data_len);
338     head->next = tlsa;
339     return (head);
340 }
341 
342 #define MAX_HEAD_BYTES 32
343 #define MAX_TAIL_BYTES 32
344 #define MAX_DUMP_BYTES (MAX_HEAD_BYTES + MAX_TAIL_BYTES)
345 
346 /* tlsa_info - log import of a particular TLSA record */
347 
tlsa_info(const char * tag,const char * msg,uint8_t u,uint8_t s,uint8_t m,const unsigned char * data,ssize_t dlen)348 static void tlsa_info(const char *tag, const char *msg,
349 		              uint8_t u, uint8_t s, uint8_t m,
350 		              const unsigned char *data, ssize_t dlen)
351 {
352     static VSTRING *top;
353     static VSTRING *bot;
354 
355     if (top == 0)
356 	top = vstring_alloc(2 * MAX_HEAD_BYTES);
357     if (bot == 0)
358 	bot = vstring_alloc(2 * MAX_TAIL_BYTES);
359 
360     if (dlen > MAX_DUMP_BYTES) {
361 	hex_encode(top, (char *) data, MAX_HEAD_BYTES);
362 	hex_encode(bot, (char *) data + dlen - MAX_TAIL_BYTES, MAX_TAIL_BYTES);
363     } else if (dlen > 0) {
364 	hex_encode(top, (char *) data, dlen);
365     } else {
366 	vstring_sprintf(top, "...");
367     }
368 
369     msg_info("%s: %s: %u %u %u %s%s%s", tag, msg, u, s, m, STR(top),
370 	     dlen > MAX_DUMP_BYTES ? "..." : "",
371 	     dlen > MAX_DUMP_BYTES ? STR(bot) : "");
372 }
373 
374 /* tlsa_carp - carp about a particular TLSA record */
375 
tlsa_carp(const char * s1,const char * s2,const char * s3,const char * s4,uint8_t u,uint8_t s,uint8_t m,const unsigned char * data,ssize_t dlen)376 static void tlsa_carp(const char *s1, const char *s2, const char *s3,
377 		            const char *s4, uint8_t u, uint8_t s, uint8_t m,
378 		              const unsigned char *data, ssize_t dlen)
379 {
380     static VSTRING *top;
381     static VSTRING *bot;
382 
383     if (top == 0)
384 	top = vstring_alloc(2 * MAX_HEAD_BYTES);
385     if (bot == 0)
386 	bot = vstring_alloc(2 * MAX_TAIL_BYTES);
387 
388     if (dlen > MAX_DUMP_BYTES) {
389 	hex_encode(top, (char *) data, MAX_HEAD_BYTES);
390 	hex_encode(bot, (char *) data + dlen - MAX_TAIL_BYTES, MAX_TAIL_BYTES);
391     } else if (dlen > 0) {
392 	hex_encode(top, (char *) data, dlen);
393     } else {
394 	vstring_sprintf(top, "...");
395     }
396 
397     msg_warn("%s%s%s %s: %u %u %u %s%s%s", s1, s2, s3, s4, u, s, m, STR(top),
398 	     dlen > MAX_DUMP_BYTES ? "..." : "",
399 	     dlen > MAX_DUMP_BYTES ? STR(bot) : "");
400 }
401 
402 /* tls_dane_flush - flush the cache */
403 
tls_dane_flush(void)404 void    tls_dane_flush(void)
405 {
406     if (dane_cache)
407 	ctable_free(dane_cache);
408     dane_cache = 0;
409 }
410 
411 /* dane_free - ctable style */
412 
dane_free(void * dane,void * unused_context)413 static void dane_free(void *dane, void *unused_context)
414 {
415     tls_dane_free((TLS_DANE *) dane);
416 }
417 
418 /* tls_dane_add_fpt_digests - map fingerprint list to DANE TLSA RRset */
419 
tls_dane_add_fpt_digests(TLS_DANE * dane,const char * digest,const char * delim,int smtp_mode)420 void    tls_dane_add_fpt_digests(TLS_DANE *dane, const char *digest,
421 				         const char *delim, int smtp_mode)
422 {
423     ARGV   *values = argv_split(digest, delim);
424     ssize_t i;
425 
426     if (smtp_mode) {
427 	if (warn_compat_break_smtp_tls_fpt_dgst)
428 	    msg_info("using backwards-compatible default setting "
429 		     VAR_SMTP_TLS_FPT_DGST "=md5 to compute certificate "
430 		     "fingerprints");
431     } else {
432 	if (warn_compat_break_lmtp_tls_fpt_dgst)
433 	    msg_info("using backwards-compatible default setting "
434 		     VAR_LMTP_TLS_FPT_DGST "=md5 to compute certificate "
435 		     "fingerprints");
436     }
437 
438     for (i = 0; i < values->argc; ++i) {
439 	const char *cp = values->argv[i];
440 	size_t  ilen = strlen(cp);
441 	VSTRING *raw;
442 
443 	/*
444 	 * Decode optionally colon-separated hex-encoded string, the input
445 	 * value requires at most 3 bytes per byte of payload, which must not
446 	 * exceed the size of the widest supported hash function.
447 	 */
448 	if (ilen > 3 * EVP_MAX_MD_SIZE) {
449 	    msg_warn("malformed fingerprint value: %.100s...",
450 		     values->argv[i]);
451 	    continue;
452 	}
453 	raw = vstring_alloc(ilen / 2);
454 	if (hex_decode_opt(raw, cp, ilen, HEX_DECODE_FLAG_ALLOW_COLON) == 0) {
455 	    myfree(raw);
456 	    msg_warn("malformed fingerprint value: %.384s", values->argv[i]);
457 	    continue;
458 	}
459 
460 	/*
461 	 * At the "fingerprint" security level certificate digests and public
462 	 * key digests are interchangeable.  Each leaf certificate is matched
463 	 * via either the public key digest or full certificate digest.  The
464 	 * DER encoding of a certificate is not a valid public key, and
465 	 * conversely, the DER encoding of a public key is not a valid
466 	 * certificate.  An attacker would need a 2nd-preimage that is
467 	 * feasible across types (given cert digest == some pkey digest) and
468 	 * yet presumably difficult within a type (e.g. given cert digest ==
469 	 * some other cert digest).  No such attacks are known at this time,
470 	 * and it is expected that if any are found they would work within as
471 	 * well as across the cert/pkey data types.
472 	 *
473 	 * The private-use matching type "255" is mapped to the configured
474 	 * fingerprint digest, which may (harmlessly) coincide with one of
475 	 * the standard DANE digest algorithms.  The private code point is
476 	 * however unconditionally enabled.
477 	 */
478 	if (log_mask & (TLS_LOG_VERBOSE | TLS_LOG_DANE))
479 	    tlsa_info("fingerprint", "digest as private-use TLSA record",
480 		   3, 0, 255, (unsigned char *) STR(raw), VSTRING_LEN(raw));
481 	dane->tlsa = tlsa_prepend(dane->tlsa, 3, 0, 255,
482 			      (unsigned char *) STR(raw), VSTRING_LEN(raw));
483 	dane->tlsa = tlsa_prepend(dane->tlsa, 3, 1, 255,
484 			      (unsigned char *) STR(raw), VSTRING_LEN(raw));
485 	vstring_free(raw);
486     }
487     argv_free(values);
488 }
489 
490 /* parse_tlsa_rr - parse a validated TLSA RRset */
491 
parse_tlsa_rr(TLS_DANE * dane,DNS_RR * rr)492 static int parse_tlsa_rr(TLS_DANE *dane, DNS_RR *rr)
493 {
494     const uint8_t *ip;
495     uint8_t usage;
496     uint8_t selector;
497     uint8_t mtype;
498     ssize_t dlen;
499     unsigned const char *data;
500     int     iscname = strcasecmp(rr->rname, rr->qname);
501     const char *q = iscname ? rr->qname : "";
502     const char *a = iscname ? " -> " : "";
503     const char *r = rr->rname;
504 
505     if (rr->type != T_TLSA)
506 	msg_panic("%s%s%s: unexpected non-TLSA RR type: %u",
507 		  q, a, r, rr->type);
508 
509     /* Drop truncated records */
510     if ((dlen = rr->data_len - 3) < 0) {
511 	msg_warn("%s%s%s: truncated TLSA RR length == %u",
512 		 q, a, r, (unsigned) rr->data_len);
513 	return (0);
514     }
515     ip = (const uint8_t *) rr->data;
516     usage = *ip++;
517     selector = *ip++;
518     mtype = *ip++;
519     data = (const unsigned char *) ip;
520 
521     /*-
522      * Drop unsupported usages.
523      * Note: NO SUPPORT for usages 0/1 which do not apply to SMTP.
524      */
525     switch (usage) {
526     case DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION:
527     case DNS_TLSA_USAGE_DOMAIN_ISSUED_CERTIFICATE:
528 	break;
529     default:
530 	tlsa_carp(q, a, r, "unsupported TLSA certificate usage",
531 		  usage, selector, mtype, data, dlen);
532 	return (0);
533     }
534 
535     /*
536      * Drop private-use matching type, reserved for fingerprint matching.
537      */
538     if (mtype == 255) {
539 	tlsa_carp(q, a, r, "reserved private-use matching type",
540 		  usage, selector, mtype, data, dlen);
541 	return (0);
542     }
543     if (log_mask & (TLS_LOG_VERBOSE | TLS_LOG_DANE))
544 	tlsa_info("DNSSEC-signed TLSA record", r,
545 		  usage, selector, mtype, data, dlen);
546     dane->tlsa = tlsa_prepend(dane->tlsa, usage, selector, mtype, data, dlen);
547     return (1);
548 }
549 
550 /* dane_lookup - TLSA record lookup, ctable style */
551 
dane_lookup(const char * tlsa_fqdn,void * unused_ctx)552 static void *dane_lookup(const char *tlsa_fqdn, void *unused_ctx)
553 {
554     static VSTRING *why = 0;
555     DNS_RR *rrs = 0;
556     DNS_RR *rr;
557     TLS_DANE *dane = tls_dane_alloc();
558     int     ret;
559 
560     if (why == 0)
561 	why = vstring_alloc(10);
562 
563     ret = dns_lookup(tlsa_fqdn, T_TLSA, RES_USE_DNSSEC, &rrs, 0, why);
564 
565     switch (ret) {
566     case DNS_OK:
567 	if (TLS_DANE_CACHE_TTL_MIN && rrs->ttl < TLS_DANE_CACHE_TTL_MIN)
568 	    rrs->ttl = TLS_DANE_CACHE_TTL_MIN;
569 	if (TLS_DANE_CACHE_TTL_MAX && rrs->ttl > TLS_DANE_CACHE_TTL_MAX)
570 	    rrs->ttl = TLS_DANE_CACHE_TTL_MAX;
571 
572 	/* One more second to account for discrete time */
573 	dane->expires = 1 + event_time() + rrs->ttl;
574 
575 	if (rrs->dnssec_valid) {
576 	    int     n = 0;
577 
578 	    for (rr = rrs; rr != 0; rr = rr->next)
579 		n += parse_tlsa_rr(dane, rr);
580 	    if (n == 0)
581 		dane->flags |= TLS_DANE_FLAG_EMPTY;
582 	} else
583 	    dane->flags |= TLS_DANE_FLAG_NORRS;
584 
585 	if (rrs)
586 	    dns_rr_free(rrs);
587 	break;
588 
589     case DNS_NOTFOUND:
590 	dane->flags |= TLS_DANE_FLAG_NORRS;
591 	dane->expires = 1 + event_time() + TLS_DANE_CACHE_TTL_MIN;
592 	break;
593 
594     default:
595 	msg_warn("DANE TLSA lookup problem: %s", STR(why));
596 	dane->flags |= TLS_DANE_FLAG_ERROR;
597 	break;
598     }
599 
600     return (void *) dane;
601 }
602 
603 /* resolve_host - resolve TLSA RRs for hostname (rname or qname) */
604 
resolve_host(const char * host,const char * proto,unsigned port)605 static TLS_DANE *resolve_host(const char *host, const char *proto,
606 			              unsigned port)
607 {
608     static VSTRING *query_domain;
609     TLS_DANE *dane;
610 
611     if (query_domain == 0)
612 	query_domain = vstring_alloc(64);
613 
614     vstring_sprintf(query_domain, "_%u._%s.%s", ntohs(port), proto, host);
615     dane = (TLS_DANE *) ctable_locate(dane_cache, STR(query_domain));
616     if (timecmp(event_time(), dane->expires) > 0)
617 	dane = (TLS_DANE *) ctable_refresh(dane_cache, STR(query_domain));
618     if (dane->base_domain == 0)
619 	dane->base_domain = mystrdup(host);
620     /* Increment ref-count of cached entry */
621     ++dane->refs;
622     return (dane);
623 }
624 
625 /* qname_secure - Lookup qname DNSSEC status */
626 
qname_secure(const char * qname)627 static int qname_secure(const char *qname)
628 {
629     static VSTRING *why;
630     int     ret = 0;
631     DNS_RR *rrs;
632 
633     if (!why)
634 	why = vstring_alloc(10);
635 
636     /*
637      * We assume that qname is already an fqdn, and does not need any
638      * suffixes from RES_DEFNAME or RES_DNSRCH.  This is typically the name
639      * of an MX host, and must be a complete DNS name.  DANE initialization
640      * code in the SMTP client is responsible for checking that the default
641      * resolver flags do not include RES_DEFNAME and RES_DNSRCH.
642      */
643     ret = dns_lookup(qname, T_CNAME, RES_USE_DNSSEC, &rrs, 0, why);
644     if (ret == DNS_OK) {
645 	ret = rrs->dnssec_valid;
646 	dns_rr_free(rrs);
647 	return (ret);
648     }
649     if (ret == DNS_NOTFOUND)
650 	vstring_sprintf(why, "no longer a CNAME");
651     msg_warn("DNSSEC status lookup error for %s: %s", qname, STR(why));
652     return (-1);
653 }
654 
655 /* tls_dane_resolve - cached map: (name, proto, port) -> TLS_DANE */
656 
tls_dane_resolve(unsigned port,const char * proto,DNS_RR * hostrr,int forcetlsa)657 TLS_DANE *tls_dane_resolve(unsigned port, const char *proto, DNS_RR *hostrr,
658 			           int forcetlsa)
659 {
660     TLS_DANE *dane = 0;
661     int     iscname = strcasecmp(hostrr->rname, hostrr->qname);
662     int     isvalid = 1;
663 
664     if (!tls_dane_avail())
665 	return (0);				/* Error */
666 
667     /*
668      * By default suppress TLSA lookups for hosts in non-DNSSEC zones.  If
669      * the host zone is not DNSSEC validated, the TLSA qname sub-domain is
670      * safely assumed to not be in a DNSSEC Look-aside Validation child zone.
671      */
672     if (!forcetlsa && !hostrr->dnssec_valid) {
673 	isvalid = iscname ? qname_secure(hostrr->qname) : 0;
674 	if (isvalid < 0)
675 	    return (0);				/* Error */
676     }
677     if (!isvalid) {
678 	dane = tls_dane_alloc();
679 	dane->flags = TLS_DANE_FLAG_NORRS;
680     } else {
681 	if (!dane_cache)
682 	    dane_cache = ctable_create(CACHE_SIZE, dane_lookup, dane_free, 0);
683 
684 	/*
685 	 * Try the rname first if secure, if nothing there, try the qname if
686 	 * different.  Note, lookup errors are distinct from success with
687 	 * nothing found.  If the rname lookup fails we don't try the qname.
688 	 */
689 	if (hostrr->dnssec_valid) {
690 	    dane = resolve_host(hostrr->rname, proto, port);
691 	    if (tls_dane_notfound(dane) && iscname) {
692 		tls_dane_free(dane);
693 		dane = 0;
694 	    }
695 	}
696 	if (!dane)
697 	    dane = resolve_host(hostrr->qname, proto, port);
698 	if (dane->flags & TLS_DANE_FLAG_ERROR) {
699 	    /* We don't return this object. */
700 	    tls_dane_free(dane);
701 	    dane = 0;
702 	}
703     }
704 
705     return (dane);
706 }
707 
708 /* tls_dane_load_trustfile - load trust anchor certs or keys from file */
709 
tls_dane_load_trustfile(TLS_DANE * dane,const char * tafile)710 int     tls_dane_load_trustfile(TLS_DANE *dane, const char *tafile)
711 {
712     BIO    *bp;
713     char   *name = 0;
714     char   *header = 0;
715     unsigned char *data = 0;
716     long    len;
717     int     tacount;
718     char   *errtype = 0;		/* if error: cert or pkey? */
719 
720     /* nop */
721     if (tafile == 0 || *tafile == 0)
722 	return (1);
723 
724     /*
725      * On each call, PEM_read() wraps a stdio file in a BIO_NOCLOSE bio,
726      * calls PEM_read_bio() and then frees the bio.  It is just as easy to
727      * open a BIO as a stdio file, so we use BIOs and call PEM_read_bio()
728      * directly.
729      */
730     if ((bp = BIO_new_file(tafile, "r")) == NULL) {
731 	msg_warn("error opening trust anchor file: %s: %m", tafile);
732 	return (0);
733     }
734     /* Don't report old news */
735     ERR_clear_error();
736 
737     /*
738      * OpenSSL implements DANE strictly, with DANE-TA(2) only matching issuer
739      * certificates, and never the leaf cert.  We also allow the
740      * trust-anchors to directly match the leaf certificate or public key.
741      */
742     for (tacount = 0;
743 	 errtype == 0 && PEM_read_bio(bp, &name, &header, &data, &len);
744 	 ++tacount) {
745 	uint8_t daneta = DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION;
746 	uint8_t daneee = DNS_TLSA_USAGE_DOMAIN_ISSUED_CERTIFICATE;
747 	uint8_t mtype = DNS_TLSA_MATCHING_TYPE_NO_HASH_USED;
748 
749 	if (strcmp(name, PEM_STRING_X509) == 0
750 	    || strcmp(name, PEM_STRING_X509_OLD) == 0) {
751 	    uint8_t selector = DNS_TLSA_SELECTOR_FULL_CERTIFICATE;
752 
753 	    if (log_mask & (TLS_LOG_VERBOSE | TLS_LOG_DANE))
754 		tlsa_info("TA cert as TLSA record", tafile,
755 			  daneta, selector, mtype, data, len);
756 	    dane->tlsa =
757 		tlsa_prepend(dane->tlsa, daneta, selector, mtype, data, len);
758 	    dane->tlsa =
759 		tlsa_prepend(dane->tlsa, daneee, selector, mtype, data, len);
760 	} else if (strcmp(name, PEM_STRING_PUBLIC) == 0) {
761 	    uint8_t selector = DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO;
762 
763 	    if (log_mask & (TLS_LOG_VERBOSE | TLS_LOG_DANE))
764 		tlsa_info("TA pkey as TLSA record", tafile,
765 			  daneta, selector, mtype, data, len);
766 	    dane->tlsa =
767 		tlsa_prepend(dane->tlsa, daneta, selector, mtype, data, len);
768 	    dane->tlsa = tlsa_prepend(dane->tlsa, daneee, selector, mtype, data, len);
769 	}
770 
771 	/*
772 	 * If any of these were null, PEM_read() would have failed.
773 	 */
774 	OPENSSL_free(name);
775 	OPENSSL_free(header);
776 	OPENSSL_free(data);
777     }
778     BIO_free(bp);
779 
780     if (errtype) {
781 	tls_print_errors();
782 	msg_warn("error reading: %s: malformed trust-anchor %s",
783 		 tafile, errtype);
784 	return (0);
785     }
786     if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) {
787 	/* Reached end of PEM file */
788 	ERR_clear_error();
789 	return (tacount > 0);
790     }
791     /* Some other PEM read error */
792     tls_print_errors();
793     return (0);
794 }
795 
tls_dane_enable(TLS_SESS_STATE * TLScontext)796 int     tls_dane_enable(TLS_SESS_STATE *TLScontext)
797 {
798     const TLS_DANE *dane = TLScontext->dane;
799     TLS_TLSA *tp;
800     SSL    *ssl = TLScontext->con;
801     int     usable = 0;
802     int     ret;
803 
804     for (tp = dane->tlsa; tp != 0; tp = tp->next) {
805 	ret = SSL_dane_tlsa_add(ssl, tp->usage, tp->selector,
806 				tp->mtype, tp->data, tp->length);
807 	if (ret > 0) {
808 	    ++usable;
809 	    continue;
810 	}
811 	if (ret == 0) {
812 	    tlsa_carp(TLScontext->namaddr, ":", "", "unusable TLSA RR",
813 		      tp->usage, tp->selector, tp->mtype, tp->data,
814 		      tp->length);
815 	    continue;
816 	}
817 	/* Internal problem in OpenSSL */
818 	tlsa_carp(TLScontext->namaddr, ":", "", "error loading trust settings",
819 		  tp->usage, tp->selector, tp->mtype, tp->data, tp->length);
820 	tls_print_errors();
821 	return (-1);
822     }
823     return (usable);
824 }
825 
826 /* tls_dane_digest_init - configure supported DANE digests */
827 
tls_dane_digest_init(SSL_CTX * ctx,const EVP_MD * fpt_alg)828 void    tls_dane_digest_init(SSL_CTX *ctx, const EVP_MD *fpt_alg)
829 {
830     dane_mtype mtypes[256];
831     char   *cp;
832     char   *save;
833     char   *algname;
834     uint8_t m;
835     uint8_t ord = 0;
836     uint8_t maxtype;
837 
838     memset((char *) mtypes, 0, sizeof(mtypes));
839 
840     /*
841      * The DANE SHA2-256(1) and SHA2-512(2) algorithms are disabled, unless
842      * explicitly enabled.  Other codepoints can be disabled explicitly by
843      * giving them an empty digest name, which also implicitly disables all
844      * smaller codepoints that are not explicitly assigned.
845      *
846      * We reserve the private-use code point (255) for use with fingerprint
847      * matching.  It MUST NOT be accepted in DNS replies.
848      */
849     mtypes[1].alg = NULL;
850     mtypes[2].alg = NULL;
851     mtypes[255].alg = fpt_alg;
852     maxtype = 2;
853 
854     save = cp = mystrdup(var_tls_dane_digests);
855     while ((algname = mystrtok(&cp, CHARS_COMMA_SP)) != 0) {
856 	char   *algcode = split_at(algname, '=');
857 	int     codepoint = -1;
858 
859 	if (algcode && *algcode) {
860 	    unsigned long l;
861 	    char   *endcp;
862 
863 	    /*
864 	     * XXX: safe_strtoul() does not flag empty or white-space only
865 	     * input.  Since we get algcode by splitting white-space/comma
866 	     * delimited tokens, this is not a problem here.
867 	     */
868 	    l = safe_strtoul(algcode, &endcp, 10);
869 	    if ((l == 0 && (errno == EINVAL || endcp == algcode))
870 		|| l >= 255 || *endcp) {
871 		msg_warn("Invalid matching type number in %s: %s=%s",
872 			 VAR_TLS_DANE_DIGESTS, algname, algcode);
873 		continue;
874 	    }
875 	    if (l == 0 || l == 255) {
876 		msg_warn("Reserved matching type number in %s: %s=%s",
877 			 VAR_TLS_DANE_DIGESTS, algname, algcode);
878 		continue;
879 	    }
880 	    codepoint = l;
881 	}
882 	/* Disable any codepoint gaps */
883 	if (codepoint > maxtype) {
884 	    while (++maxtype < codepoint)
885 		mtypes[codepoint].alg = NULL;
886 	    maxtype = codepoint;
887 	}
888 	/* Handle explicitly disabled codepoints */
889 	if (*algname == 0) {
890 	    /* Skip empty specifiers */
891 	    if (codepoint < 0)
892 		continue;
893 	    mtypes[codepoint].alg = NULL;
894 	    continue;
895 	}
896 	switch (codepoint) {
897 	case -1:
898 	    if (strcasecmp(algname, LN_sha256) == 0)
899 		codepoint = 1;			/* SHA2-256(1) */
900 	    else if (strcasecmp(algname, LN_sha512) == 0)
901 		codepoint = 2;			/* SHA2-512(2) */
902 	    else {
903 		msg_warn("%s: digest algorithm %s needs an explicit number",
904 			 VAR_TLS_DANE_DIGESTS, algname);
905 		continue;
906 	    }
907 	    break;
908 	case 1:
909 	    if (strcasecmp(algname, LN_sha256) != 0) {
910 		msg_warn("%s: matching type 1 can only be %s",
911 			 VAR_TLS_DANE_DIGESTS, LN_sha256);
912 		continue;
913 	    }
914 	    algname = LN_sha256;
915 	    break;
916 	case 2:
917 	    if (strcasecmp(algname, LN_sha512) != 0) {
918 		msg_warn("%s: matching type 2 can only be %s",
919 			 VAR_TLS_DANE_DIGESTS, LN_sha512);
920 		continue;
921 	    }
922 	    algname = LN_sha512;
923 	    break;
924 	default:
925 	    break;
926 	}
927 
928 	if (mtypes[codepoint].ord != 0) {
929 	    msg_warn("%s: matching type %d specified more than once",
930 		     VAR_TLS_DANE_DIGESTS, codepoint);
931 	    continue;
932 	}
933 	mtypes[codepoint].ord = ++ord;
934 
935 	if ((mtypes[codepoint].alg = tls_digest_byname(algname, NULL)) == 0) {
936 	    msg_warn("%s: digest algorithm \"%s\"(%d) unknown",
937 		     VAR_TLS_DANE_DIGESTS, algname, codepoint);
938 	    continue;
939 	}
940     }
941     myfree(save);
942 
943     for (m = 1; m != 0; m = m != maxtype ? m + 1 : 255) {
944 
945 	/*
946 	 * In OpenSSL higher order ordinals are preferred, but we list the
947 	 * most preferred algorithms first, so the last ordinal becomes 1,
948 	 * next-to-last, 2, ...
949 	 *
950 	 * The ordinals of non-disabled algorithms are always positive, and the
951 	 * computed value cannot overflow 254 (the largest possible value of
952 	 * 'ord' after loading each valid codepoint at most once).
953 	 */
954 	if (SSL_CTX_dane_mtype_set(ctx, mtypes[m].alg, m,
955 				   ord - mtypes[m].ord + 1) <= 0) {
956 	    msg_warn("%s: error configuring matching type %d",
957 		     VAR_TLS_DANE_DIGESTS, m);
958 	    tls_print_errors();
959 	}
960     }
961 }
962 
963 /* tls_dane_log - log DANE-based verification success */
964 
tls_dane_log(TLS_SESS_STATE * TLScontext)965 void    tls_dane_log(TLS_SESS_STATE *TLScontext)
966 {
967     static VSTRING *top;
968     static VSTRING *bot;
969     EVP_PKEY *mspki = 0;
970     int     depth = SSL_get0_dane_authority(TLScontext->con, NULL, &mspki);
971     uint8_t u, s, m;
972     unsigned const char *data;
973     size_t  dlen;
974 
975     if (depth < 0)
976 	return;					/* No DANE auth */
977 
978     switch (TLScontext->level) {
979     case TLS_LEV_SECURE:
980     case TLS_LEV_VERIFY:
981 	msg_info("%s: Matched trust anchor at depth %d",
982 		 TLScontext->namaddr, depth);
983 	return;
984     }
985 
986     if (top == 0)
987 	top = vstring_alloc(2 * MAX_HEAD_BYTES);
988     if (bot == 0)
989 	bot = vstring_alloc(2 * MAX_TAIL_BYTES);
990 
991     (void) SSL_get0_dane_tlsa(TLScontext->con, &u, &s, &m, &data, &dlen);
992     if (dlen > MAX_DUMP_BYTES) {
993 	hex_encode(top, (char *) data, MAX_HEAD_BYTES);
994 	hex_encode(bot, (char *) data + dlen - MAX_TAIL_BYTES, MAX_TAIL_BYTES);
995     } else {
996 	hex_encode(top, (char *) data, dlen);
997     }
998 
999     switch (TLScontext->level) {
1000     case TLS_LEV_FPRINT:
1001 	msg_info("%s: Matched fingerprint: %s%s%s", TLScontext->namaddr,
1002 		 STR(top), dlen > MAX_DUMP_BYTES ? "..." : "",
1003 		 dlen > MAX_DUMP_BYTES ? STR(bot) : "");
1004 	return;
1005 
1006     default:
1007 	msg_info("%s: Matched DANE %s at depth %d: %u %u %u %s%s%s",
1008 		 TLScontext->namaddr, mspki ?
1009 		 "TA public key verified certificate" : depth ?
1010 		 "TA certificate" : "EE certificate", depth, u, s, m,
1011 		 STR(top), dlen > MAX_DUMP_BYTES ? "..." : "",
1012 		 dlen > MAX_DUMP_BYTES ? STR(bot) : "");
1013 	return;
1014     }
1015 }
1016 
1017 #ifdef TEST
1018 
1019 #include <unistd.h>
1020 #include <stdarg.h>
1021 
1022 #include <mail_params.h>
1023 #include <mail_conf.h>
1024 #include <msg_vstream.h>
1025 
verify_chain(SSL * ssl,x509_stack_t * chain,TLS_SESS_STATE * tctx)1026 static int verify_chain(SSL *ssl, x509_stack_t *chain, TLS_SESS_STATE *tctx)
1027 {
1028     int     ret;
1029     X509   *cert;
1030     X509_STORE_CTX *store_ctx;
1031     SSL_CTX *ssl_ctx = SSL_get_SSL_CTX(ssl);
1032     X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
1033     int     store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1034 
1035     cert = sk_X509_value(chain, 0);
1036     if ((store_ctx = X509_STORE_CTX_new()) == NULL) {
1037 	SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
1038 	return 0;
1039     }
1040     if (!X509_STORE_CTX_init(store_ctx, store, cert, chain)) {
1041 	X509_STORE_CTX_free(store_ctx);
1042 	return 0;
1043     }
1044     X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx, ssl);
1045 
1046     /* We're *verifying* a server chain */
1047     X509_STORE_CTX_set_default(store_ctx, "ssl_server");
1048     X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
1049 			   SSL_get0_param(ssl));
1050     X509_STORE_CTX_set0_dane(store_ctx, SSL_get0_dane(ssl));
1051 
1052     ret = X509_verify_cert(store_ctx);
1053 
1054     SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
1055     X509_STORE_CTX_free(store_ctx);
1056 
1057     return (ret);
1058 }
1059 
load_tlsa_args(SSL * ssl,char * argv[])1060 static void load_tlsa_args(SSL *ssl, char *argv[])
1061 {
1062     const EVP_MD *md = 0;
1063     X509   *cert = 0;
1064     BIO    *bp;
1065     unsigned char *buf;
1066     unsigned char *buf2;
1067     int     len;
1068     uint8_t u = atoi(argv[1]);
1069     uint8_t s = atoi(argv[2]);
1070     uint8_t m = atoi(argv[3]);
1071     EVP_PKEY *pkey;
1072 
1073     /* Unsupported usages are fatal */
1074     switch (u) {
1075     case DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION:
1076     case DNS_TLSA_USAGE_DOMAIN_ISSUED_CERTIFICATE:
1077 	break;
1078     default:
1079 	msg_fatal("unsupported certificate usage %u", u);
1080     }
1081 
1082     /* Unsupported selectors are fatal */
1083     switch (s) {
1084     case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
1085     case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
1086 	break;
1087     default:
1088 	msg_fatal("unsupported selector %u", s);
1089     }
1090 
1091     /* Unsupported selectors are fatal */
1092     switch (m) {
1093     case DNS_TLSA_MATCHING_TYPE_NO_HASH_USED:
1094     case DNS_TLSA_MATCHING_TYPE_SHA256:
1095     case DNS_TLSA_MATCHING_TYPE_SHA512:
1096 	break;
1097     default:
1098 	msg_fatal("unsupported matching type %u", m);
1099     }
1100 
1101     if ((bp = BIO_new_file(argv[4], "r")) == NULL)
1102 	msg_fatal("error opening %s: %m", argv[4]);
1103     if (!PEM_read_bio_X509(bp, &cert, 0, 0)) {
1104 	tls_print_errors();
1105 	msg_fatal("error loading certificate from %s: %m", argv[4]);
1106     }
1107     BIO_free(bp);
1108 
1109     /*
1110      * Extract ASN.1 DER form of certificate or public key.
1111      */
1112     switch (s) {
1113     case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
1114 	len = i2d_X509(cert, NULL);
1115 	if (len > 0xffff)
1116 	    msg_fatal("certificate too long: %d", len);
1117 	buf2 = buf = (unsigned char *) mymalloc(len);
1118 	i2d_X509(cert, &buf2);
1119 	break;
1120     case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
1121 	pkey = X509_get_pubkey(cert);
1122 	len = i2d_PUBKEY(pkey, NULL);
1123 	if (len > 0xffff)
1124 	    msg_fatal("public key too long: %d", len);
1125 	buf2 = buf = (unsigned char *) mymalloc(len);
1126 	i2d_PUBKEY(pkey, &buf2);
1127 	EVP_PKEY_free(pkey);
1128 	break;
1129     }
1130     X509_free(cert);
1131     OPENSSL_assert(buf2 - buf == len);
1132 
1133     switch (m) {
1134     case 0:
1135 	break;
1136     case 1:
1137 	if ((md = tls_digest_byname(LN_sha256, NULL)) == 0)
1138 	    msg_fatal("Digest %s not found", LN_sha256);
1139 	break;
1140     case 2:
1141 	if ((md = tls_digest_byname(LN_sha512, NULL)) == 0)
1142 	    msg_fatal("Digest %s not found", LN_sha512);
1143 	break;
1144     default:
1145 	msg_fatal("Unsupported DANE mtype: %d", m);
1146     }
1147 
1148     if (md != 0) {
1149 	unsigned char mdbuf[EVP_MAX_MD_SIZE];
1150 	unsigned int mdlen = sizeof(mdbuf);
1151 
1152 	if (!EVP_Digest(buf, len, mdbuf, &mdlen, md, 0))
1153 	    msg_fatal("Digest failure for mtype: %d", m);
1154 	myfree(buf);
1155 	buf = (unsigned char *) mymemdup(mdbuf, len = mdlen);
1156     }
1157     SSL_dane_tlsa_add(ssl, u, s, m, buf, len);
1158     myfree((void *) buf);
1159 }
1160 
load_chain(const char * chainfile)1161 static x509_stack_t *load_chain(const char *chainfile)
1162 {
1163     BIO    *bp;
1164     char   *name = 0;
1165     char   *header = 0;
1166     unsigned char *data = 0;
1167     long    len;
1168     int     count;
1169     char   *errtype = 0;		/* if error: cert or pkey? */
1170     x509_stack_t *chain;
1171     typedef X509 *(*d2i_X509_t) (X509 **, const unsigned char **, long);
1172 
1173     if ((chain = sk_X509_new_null()) == 0) {
1174 	perror("malloc");
1175 	exit(1);
1176     }
1177 
1178     /*
1179      * On each call, PEM_read() wraps a stdio file in a BIO_NOCLOSE bio,
1180      * calls PEM_read_bio() and then frees the bio.  It is just as easy to
1181      * open a BIO as a stdio file, so we use BIOs and call PEM_read_bio()
1182      * directly.
1183      */
1184     if ((bp = BIO_new_file(chainfile, "r")) == NULL) {
1185 	fprintf(stderr, "error opening chainfile: %s: %m\n", chainfile);
1186 	exit(1);
1187     }
1188     /* Don't report old news */
1189     ERR_clear_error();
1190 
1191     for (count = 0;
1192 	 errtype == 0 && PEM_read_bio(bp, &name, &header, &data, &len);
1193 	 ++count) {
1194 	const unsigned char *p = data;
1195 
1196 	if (strcmp(name, PEM_STRING_X509) == 0
1197 	    || strcmp(name, PEM_STRING_X509_TRUSTED) == 0
1198 	    || strcmp(name, PEM_STRING_X509_OLD) == 0) {
1199 	    d2i_X509_t d;
1200 	    X509   *cert;
1201 
1202 	    d = strcmp(name, PEM_STRING_X509_TRUSTED) ? d2i_X509_AUX : d2i_X509;
1203 	    if ((cert = d(0, &p, len)) == 0 || (p - data) != len)
1204 		errtype = "certificate";
1205 	    else if (sk_X509_push(chain, cert) == 0) {
1206 		perror("malloc");
1207 		exit(1);
1208 	    }
1209 	} else {
1210 	    fprintf(stderr, "unexpected chain file object: %s\n", name);
1211 	    exit(1);
1212 	}
1213 
1214 	/*
1215 	 * If any of these were null, PEM_read() would have failed.
1216 	 */
1217 	OPENSSL_free(name);
1218 	OPENSSL_free(header);
1219 	OPENSSL_free(data);
1220     }
1221     BIO_free(bp);
1222 
1223     if (errtype) {
1224 	tls_print_errors();
1225 	fprintf(stderr, "error reading: %s: malformed %s", chainfile, errtype);
1226 	exit(1);
1227     }
1228     if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) {
1229 	/* Reached end of PEM file */
1230 	ERR_clear_error();
1231 	if (count > 0)
1232 	    return chain;
1233 	fprintf(stderr, "no certificates found in: %s\n", chainfile);
1234 	exit(1);
1235     }
1236     /* Some other PEM read error */
1237     tls_print_errors();
1238     fprintf(stderr, "error reading: %s\n", chainfile);
1239     exit(1);
1240 }
1241 
usage(const char * progname)1242 static void usage(const char *progname)
1243 {
1244     fprintf(stderr, "Usage: %s certificate-usage selector matching-type"
1245 	    " certfile \\\n\t\tCAfile chainfile hostname [certname ...]\n",
1246 	    progname);
1247     fprintf(stderr, "  where, certificate-usage = TLSA certificate usage,\n");
1248     fprintf(stderr, "\t selector = TLSA selector,\n");
1249     fprintf(stderr, "\t matching-type = empty string or OpenSSL digest algorithm name,\n");
1250     fprintf(stderr, "\t PEM certfile provides certificate association data,\n");
1251     fprintf(stderr, "\t PEM CAfile contains any usage 0/1 trusted roots,\n");
1252     fprintf(stderr, "\t PEM chainfile = server chain file to verify\n");
1253     fprintf(stderr, "\t hostname = destination hostname,\n");
1254     fprintf(stderr, "\t each certname augments the hostname for name checks.\n");
1255     exit(1);
1256 }
1257 
ctx_init(const char * CAfile)1258 static SSL_CTX *ctx_init(const char *CAfile)
1259 {
1260     SSL_CTX *client_ctx;
1261 
1262     tls_param_init();
1263     tls_check_version();
1264 
1265     if (!tls_validate_digest(LN_sha1))
1266 	msg_fatal("%s digest algorithm not available", LN_sha1);
1267 
1268     if (TLScontext_index < 0)
1269 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0)
1270 	    msg_fatal("Cannot allocate SSL application data index");
1271 
1272     ERR_clear_error();
1273     if ((client_ctx = SSL_CTX_new(TLS_client_method())) == 0)
1274 	msg_fatal("cannot allocate client SSL_CTX");
1275     SSL_CTX_set_verify_depth(client_ctx, 5);
1276 
1277     /* Enable DANE support in OpenSSL */
1278     if (SSL_CTX_dane_enable(client_ctx) <= 0) {
1279 	tls_print_errors();
1280 	msg_fatal("OpenSSL DANE initialization failed");
1281     }
1282     if (tls_set_ca_certificate_info(client_ctx, CAfile, "") < 0) {
1283 	tls_print_errors();
1284 	msg_fatal("cannot load CAfile: %s", CAfile);
1285     }
1286     SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE,
1287 		       tls_verify_certificate_callback);
1288     return (client_ctx);
1289 }
1290 
main(int argc,char * argv[])1291 int     main(int argc, char *argv[])
1292 {
1293     SSL_CTX *ssl_ctx;
1294     const EVP_MD *fpt_alg;
1295     TLS_SESS_STATE *tctx;
1296     x509_stack_t *chain;
1297     int     i;
1298 
1299     var_procname = mystrdup(basename(argv[0]));
1300     set_mail_conf_str(VAR_PROCNAME, var_procname);
1301     msg_vstream_init(var_procname, VSTREAM_OUT);
1302 
1303     if (argc < 8)
1304 	usage(argv[0]);
1305 
1306     ssl_ctx = ctx_init(argv[5]);
1307     if (!tls_dane_avail())
1308 	msg_fatal("DANE TLSA support not available");
1309 
1310     tctx = tls_alloc_sess_context(TLS_LOG_NONE, argv[7]);
1311     tctx->namaddr = argv[7];
1312     tctx->mdalg = LN_sha256;
1313     tctx->dane = tls_dane_alloc();
1314 
1315     if ((fpt_alg = tls_validate_digest(tctx->mdalg)) == 0)
1316 	msg_fatal("fingerprint digest algorithm %s not found",
1317 		  tctx->mdalg);
1318     tls_dane_digest_init(ssl_ctx, fpt_alg);
1319 
1320     if ((tctx->con = SSL_new(ssl_ctx)) == 0
1321 	|| !SSL_set_ex_data(tctx->con, TLScontext_index, tctx)) {
1322 	tls_print_errors();
1323 	msg_fatal("Error allocating SSL connection");
1324     }
1325     if (SSL_dane_enable(tctx->con, 0) <= 0) {
1326 	tls_print_errors();
1327 	msg_fatal("Error enabling DANE for SSL handle");
1328     }
1329     SSL_dane_set_flags(tctx->con, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
1330     SSL_dane_set_flags(tctx->con, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
1331     for (i = 7; i < argc; ++i)
1332 	if (!SSL_add1_host(tctx->con, argv[i]))
1333 	    msg_fatal("error adding hostname: %s", argv[i]);
1334     load_tlsa_args(tctx->con, argv);
1335     SSL_set_connect_state(tctx->con);
1336 
1337     /* Verify saved server chain */
1338     chain = load_chain(argv[6]);
1339     i = verify_chain(tctx->con, chain, tctx);
1340     tls_print_errors();
1341 
1342     if (i > 0) {
1343 	const char *peername = SSL_get0_peername(tctx->con);
1344 
1345 	if (peername == 0)
1346 	    peername = argv[7];
1347 	msg_info("Verified %s", peername);
1348     } else {
1349 	i = SSL_get_verify_result(tctx->con);
1350 	msg_info("certificate verification failed for %s:%s: num=%d:%s",
1351 		 argv[6], argv[7], i, X509_verify_cert_error_string(i));
1352     }
1353 
1354     return (i <= 0);
1355 }
1356 
1357 #endif					/* TEST */
1358 
1359 #endif					/* USE_TLS */
1360