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