xref: /netbsd-src/external/ibm-public/postfix/dist/src/tls/tls_dane.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: tls_dane.c,v 1.2 2017/02/14 01:16:48 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	tls_dane 3
6 /* SUMMARY
7 /*	Support for RFC 6698 (DANE) certificate matching
8 /* SYNOPSIS
9 /*	#include <tls.h>
10 /*
11 /*	int	tls_dane_avail()
12 /*
13 /*	void	tls_dane_flush()
14 /*
15 /*	void	tls_dane_verbose(on)
16 /*	int	on;
17 /*
18 /*	TLS_DANE *tls_dane_alloc()
19 /*
20 /*	void	tls_dane_free(dane)
21 /*	TLS_DANE *dane;
22 /*
23 /*	void	tls_dane_add_ee_digests(dane, mdalg, digest, delim)
24 /*	TLS_DANE *dane;
25 /*	const char *mdalg;
26 /*	const char *digest;
27 /*	const char *delim;
28 /*
29 /*	int	tls_dane_load_trustfile(dane, tafile)
30 /*	TLS_DANE *dane;
31 /*	const char *tafile;
32 /*
33 /*	int	tls_dane_match(TLSContext, usage, cert, depth)
34 /*	TLS_SESS_STATE *TLScontext;
35 /*	int	usage;
36 /*	X509	*cert;
37 /*	int	depth;
38 /*
39 /*	void	tls_dane_set_callback(ssl_ctx, TLScontext)
40 /*	SSL_CTX *ssl_ctx;
41 /*	TLS_SESS_STATE *TLScontext;
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 /*	int	tls_dane_unusable(dane)
50 /*	const TLS_DANE *dane;
51 /*
52 /*	int	tls_dane_notfound(dane)
53 /*	const TLS_DANE *dane;
54 /* DESCRIPTION
55 /*	tls_dane_avail() returns true if the features required to support DANE
56 /*	are present in OpenSSL's libcrypto and in libresolv.  Since OpenSSL's
57 /*	libcrypto is not initialized until we call tls_client_init(), calls
58 /*	to tls_dane_avail() must be deferred until this initialization is
59 /*	completed successufully.
60 /*
61 /*	tls_dane_flush() flushes all entries from the cache, and deletes
62 /*	the cache.
63 /*
64 /*	tls_dane_verbose() turns on verbose logging of TLSA record lookups.
65 /*
66 /*	tls_dane_alloc() returns a pointer to a newly allocated TLS_DANE
67 /*	structure with null ta and ee digest sublists.
68 /*
69 /*	tls_dane_free() frees the structure allocated by tls_dane_alloc().
70 /*
71 /*	tls_dane_add_ee_digests() splits "digest" using the characters in
72 /*	"delim" as delimiters and stores the results on the EE match list
73 /*	to match either a certificate or a public key.  This is an incremental
74 /*	interface, that builds a TLS_DANE structure outside the cache by
75 /*	manually adding entries.
76 /*
77 /*	tls_dane_load_trustfile() imports trust-anchor certificates and
78 /*	public keys from a file (rather than DNS TLSA records).
79 /*
80 /*	tls_dane_match() matches the full and/or public key digest of
81 /*	"cert" against each candidate digest in TLScontext->dane. If usage
82 /*	is TLS_DANE_EE, the match is against end-entity digests, otherwise
83 /*	it is against trust-anchor digests.  Returns true if a match is found,
84 /*	false otherwise.
85 /*
86 /*	tls_dane_set_callback() wraps the SSL certificate verification logic
87 /*	in a function that modifies the input trust chain and trusted
88 /*	certificate store to map DANE TA validation onto the existing PKI
89 /*	verification model.  When TLScontext is NULL the callback is
90 /*	cleared, otherwise it is set.  This callback should only be set
91 /*	when out-of-band trust-anchors (via DNSSEC DANE TLSA records or
92 /*	per-destination local configuration) are provided.  Such trust
93 /*	anchors always override the legacy public CA PKI.  Otherwise, the
94 /*	callback MUST be cleared.
95 /*
96 /*	tls_dane_resolve() maps a (port, protocol, hostrr) tuple to a
97 /*	corresponding TLS_DANE policy structure found in the DNS.  The port
98 /*	argument is in network byte order.  A null pointer is returned when
99 /*	the DNS query for the TLSA record tempfailed.  In all other cases the
100 /*	return value is a pointer to the corresponding TLS_DANE structure.
101 /*	The caller must free the structure via tls_dane_free().
102 /*
103 /*	tls_dane_unusable() checks whether a cached TLS_DANE record is
104 /*	the result of a validated RRset, with no usable elements.  In
105 /*	this case, TLS is mandatory, but certificate verification is
106 /*	not DANE-based.
107 /*
108 /*	tls_dane_notfound() checks whether a cached TLS_DANE record is
109 /*	the result of a validated DNS lookup returning NODATA. In
110 /*	this case, TLS is not required by RFC, though users may elect
111 /*	a mandatory TLS fallback policy.
112 /*
113 /*	Arguments:
114 /* .IP dane
115 /*	Pointer to a TLS_DANE structure that lists the valid trust-anchor
116 /*	and end-entity full-certificate and/or public-key digests.
117 /* .IP port
118 /*	The TCP port in network byte order.
119 /* .IP proto
120 /*	Almost certainly "tcp".
121 /* .IP hostrr
122 /*	DNS_RR pointer to TLSA base domain data.
123 /* .IP forcetlsa
124 /*	When true, TLSA lookups are performed even when the qname and rname
125 /*	are insecure.  This is only useful in the unlikely case that DLV is
126 /*	used to secure the TLSA RRset in an otherwise insecure zone.
127 /* .IP TLScontext
128 /*	Client context with TA/EE matching data and related state.
129 /* .IP usage
130 /*	Trust anchor (TLS_DANE_TA) or end-entity (TLS_DANE_EE) digests?
131 /* .IP cert
132 /*	Certificate from peer trust chain (CA or leaf server).
133 /* .IP depth
134 /*	The certificate depth for logging.
135 /* .IP ssl_ctx
136 /*	The global SSL_CTX structure used to initialize child SSL
137 /*	conenctions.
138 /* .IP mdalg
139 /*	Name of a message digest algorithm suitable for computing secure
140 /*	(1st pre-image resistant) message digests of certificates. For now,
141 /*	md5, sha1, or member of SHA-2 family if supported by OpenSSL.
142 /* .IP digest
143 /*	The digest (or list of digests concatenated with characters from
144 /*	"delim") to be added to the TLS_DANE record.
145 /* .IP delim
146 /*	The set of delimiter characters used above.
147 /* LICENSE
148 /* .ad
149 /* .fi
150 /*	This software is free. You can do with it whatever you want.
151 /*	The original author kindly requests that you acknowledge
152 /*	the use of his software.
153 /* AUTHOR(S)
154 /*	Wietse Venema
155 /*	IBM T.J. Watson Research
156 /*	P.O. Box 704
157 /*	Yorktown Heights, NY 10598, USA
158 /*
159 /*	Viktor Dukhovni
160 /*--*/
161 
162 /* System library. */
163 
164 #include <sys_defs.h>
165 #include <ctype.h>
166 
167 #ifdef STRCASECMP_IN_STRINGS_H
168 #include <strings.h>
169 #endif
170 
171 #ifdef USE_TLS
172 #include <string.h>
173 
174 /* Utility library. */
175 
176 #include <msg.h>
177 #include <mymalloc.h>
178 #include <stringops.h>
179 #include <vstring.h>
180 #include <events.h>			/* event_time() */
181 #include <timecmp.h>
182 #include <ctable.h>
183 #include <hex_code.h>
184 #include <safe_ultostr.h>
185 #include <split_at.h>
186 #include <name_code.h>
187 
188 #define STR(x)	vstring_str(x)
189 
190 /* Global library */
191 
192 #include <mail_params.h>
193 
194 /* DNS library. */
195 
196 #include <dns.h>
197 
198 /* TLS library. */
199 
200 #define TLS_INTERNAL
201 #include <tls.h>
202 
203 /* Application-specific. */
204 
205 #undef TRUST_ANCHOR_SUPPORT
206 #undef DANE_TLSA_SUPPORT
207 #undef WRAP_SIGNED
208 
209 #if OPENSSL_VERSION_NUMBER >= 0x1000000fL && \
210 	(defined(X509_V_FLAG_PARTIAL_CHAIN) || !defined(OPENSSL_NO_ECDH))
211 #define TRUST_ANCHOR_SUPPORT
212 
213 #ifndef X509_V_FLAG_PARTIAL_CHAIN
214 #define WRAP_SIGNED
215 #endif
216 
217 #if defined(TLSEXT_MAXLEN_host_name) && RES_USE_DNSSEC && RES_USE_EDNS0
218 #define DANE_TLSA_SUPPORT
219 #endif
220 
221 #endif					/* OPENSSL_VERSION_NUMBER ... */
222 
223 #ifdef TRUST_ANCHOR_SUPPORT
224 static int ta_support = 1;
225 
226 #else
227 static int ta_support = 0;
228 
229 #endif
230 
231 #ifdef WRAP_SIGNED
232 static int wrap_signed = 1;
233 
234 #else
235 static int wrap_signed = 0;
236 
237 #endif
238 
239 #ifdef 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 static EVP_PKEY *signkey;
248 static const EVP_MD *signmd;
249 static const char *signalg;
250 static ASN1_OBJECT *serverAuth;
251 
252 /*
253  * https://www.iana.org/assignments/dane-parameters/dane-parameters.xhtml
254  */
255 typedef struct {
256     const char *mdalg;
257     uint8_t dane_id;
258 } iana_digest;
259 
260 static iana_digest iana_table[] = {
261     {"", DNS_TLSA_MATCHING_TYPE_NO_HASH_USED},
262     {"sha256", DNS_TLSA_MATCHING_TYPE_SHA256},
263     {"sha512", DNS_TLSA_MATCHING_TYPE_SHA512},
264     {0, 0}
265 };
266 
267 typedef struct dane_digest {
268     struct dane_digest *next;		/* linkage */
269     const char *mdalg;			/* OpenSSL name */
270     const EVP_MD *md;			/* OpenSSL EVP handle */
271     int     len;			/* digest octet length */
272     int     pref;			/* tls_dane_digests index or -1 */
273     uint8_t dane_id;			/* IANA id */
274 } dane_digest;
275 
276 #define MAXDIGESTS 256			/* RFC limit */
277 static dane_digest *digest_list;
278 static int digest_agility = -1;
279 
280 #define AGILITY_OFF	0
281 #define AGILITY_ON	1
282 #define AGILITY_MAYBE	2
283 
284 static NAME_CODE agility[] = {
285     {TLS_DANE_AGILITY_OFF, AGILITY_OFF},
286     {TLS_DANE_AGILITY_ON, AGILITY_ON},
287     {TLS_DANE_AGILITY_MAYBE, AGILITY_MAYBE},
288     {0, -1}
289 };
290 
291 /*
292  * This is not intended to be a long-term cache of pre-parsed TLSA data,
293  * rather we primarily want to avoid fetching and parsing the TLSA records
294  * for a single multi-homed MX host more than once per delivery. Therefore,
295  * we keep the table reasonably small.
296  */
297 #define CACHE_SIZE 20
298 static CTABLE *dane_cache;
299 
300 static int dane_initialized;
301 static int dane_verbose;
302 
303 /* tls_dane_verbose - enable/disable verbose logging */
304 
305 void    tls_dane_verbose(int on)
306 {
307     dane_verbose = on;
308 }
309 
310 /* add_digest - validate and append digest to digest list */
311 
312 static dane_digest *add_digest(char *mdalg, int pref)
313 {
314     iana_digest *i;
315     dane_digest *d;
316     int     dane_id = -1;
317     const char *dane_mdalg = mdalg;
318     char   *value = split_at(mdalg, '=');
319     const EVP_MD *md = 0;
320     size_t  mdlen = 0;
321 
322     if (value && *value) {
323 	unsigned long l;
324 	char   *endcp;
325 
326 	/*
327 	 * XXX: safe_strtoul() does not flag empty or white-space only input.
328 	 * Since we get idbuf by splitting white-space/comma delimited
329 	 * tokens, this is not a problem here. Fixed as of 210131209.
330 	 */
331 	l = safe_strtoul(value, &endcp, 10);
332 	if ((l == 0 && (errno == EINVAL || endcp == value))
333 	    || l >= MAXDIGESTS
334 	    || *endcp) {
335 	    msg_warn("Invalid matching type number in %s: %s=%s",
336 		     VAR_TLS_DANE_DIGESTS, mdalg, value);
337 	    return (0);
338 	}
339 	dane_id = l;
340     }
341 
342     /*
343      * Check for known IANA conflicts
344      */
345     for (i = iana_table; i->mdalg; ++i) {
346 	if (*mdalg && strcasecmp(i->mdalg, mdalg) == 0) {
347 	    if (dane_id >= 0 && i->dane_id != dane_id) {
348 		msg_warn("Non-standard value in %s: %s%s%s",
349 			 VAR_TLS_DANE_DIGESTS, mdalg,
350 			 value ? "=" : "", value ? value : "");
351 		return (0);
352 	    }
353 	    dane_id = i->dane_id;
354 	} else if (i->dane_id == dane_id) {
355 	    if (*mdalg) {
356 		msg_warn("Non-standard algorithm in %s: %s%s%s",
357 			 VAR_TLS_DANE_DIGESTS, mdalg,
358 			 value ? "=" : "", value ? value : "");
359 		return (0);
360 	    }
361 	    dane_mdalg = i->mdalg;
362 	}
363     }
364 
365     /*
366      * Check for unknown implicit digest or value
367      */
368     if (dane_id < 0 || (dane_id > 0 && !*dane_mdalg)) {
369 	msg_warn("Unknown incompletely specified element in %s: %s%s%s",
370 		 VAR_TLS_DANE_DIGESTS, mdalg,
371 		 value ? "=" : "", value ? value : "");
372 	return 0;
373     }
374 
375     /*
376      * Check for duplicate entries
377      */
378     for (d = digest_list; d; d = d->next) {
379 	if (strcasecmp(d->mdalg, dane_mdalg) == 0
380 	    || d->dane_id == dane_id) {
381 	    msg_warn("Duplicate element in %s: %s%s%s",
382 		     VAR_TLS_DANE_DIGESTS, mdalg,
383 		     value ? "=" : "", value ? value : "");
384 	    return (0);
385 	}
386     }
387 
388     if (*dane_mdalg
389 	&& ((md = EVP_get_digestbyname(dane_mdalg)) == 0
390 	    || (mdlen = EVP_MD_size(md)) <= 0
391 	    || mdlen > EVP_MAX_MD_SIZE)) {
392 	msg_warn("Unimplemented digest algorithm in %s: %s%s%s",
393 		 VAR_TLS_DANE_DIGESTS, mdalg,
394 		 value ? "=" : "", value ? value : "");
395 	return (0);
396     }
397     d = (dane_digest *) mymalloc(sizeof(*d));
398     d->next = digest_list;
399     d->mdalg = mystrdup(dane_mdalg);
400     d->md = md;
401     d->len = mdlen;
402     d->pref = pref;
403     d->dane_id = dane_id;
404 
405     return (digest_list = d);
406 }
407 
408 /* digest_byid - locate digest_table entry for given IANA id */
409 
410 static dane_digest *digest_byid(uint8_t dane_id)
411 {
412     dane_digest *d;
413 
414     for (d = digest_list; d; d = d->next)
415 	if (d->dane_id == dane_id)
416 	    return (d);
417     return (0);
418 }
419 
420 /* digest_pref_byid - digest preference by IANA id */
421 
422 static int digest_pref_byid(uint8_t dane_id)
423 {
424     dane_digest *d = digest_byid(dane_id);
425 
426     return (d ? (d->pref) : (MAXDIGESTS + dane_id));
427 }
428 
429 /* gencakey - generate interal DANE root CA key */
430 
431 static EVP_PKEY *gencakey(void)
432 {
433     EVP_PKEY *key = 0;
434 
435 #ifdef WRAP_SIGNED
436     EC_KEY *eckey;
437     EC_GROUP *group = 0;
438 
439     ERR_clear_error();
440 
441     if ((eckey = EC_KEY_new()) != 0
442 	&& (group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)) != 0
443 	&& (EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE),
444 	    EC_KEY_set_group(eckey, group))
445 	&& EC_KEY_generate_key(eckey)
446 	&& (key = EVP_PKEY_new()) != 0
447 	&& !EVP_PKEY_set1_EC_KEY(key, eckey)) {
448 	EVP_PKEY_free(key);
449 	key = 0;
450     }
451     if (group)
452 	EC_GROUP_free(group);
453     if (eckey)
454 	EC_KEY_free(eckey);
455 #endif						/* WRAP_SIGNED */
456     return (key);
457 }
458 
459 /* dane_init - initialize DANE parameters */
460 
461 static void dane_init(void)
462 {
463     int     digest_pref = 0;
464     char   *cp;
465     char   *save;
466     char   *tok;
467     static char fullmtype[] = "=0";
468     dane_digest *d;
469 
470     /*
471      * Add the full matching type at highest preference and then the users
472      * configured list.
473      *
474      * The most preferred digest will be used for cert signing and hashing full
475      * values for comparison.
476      */
477     if ((digest_agility = name_code(agility, 0, var_tls_dane_agility)) < 0) {
478 	msg_warn("Invalid %s syntax: %s. DANE support disabled.",
479 		 VAR_TLS_DANE_AGILITY, var_tls_dane_agility);
480     } else if (add_digest(fullmtype, 0)) {
481 	save = cp = mystrdup(var_tls_dane_digests);
482 	while ((tok = mystrtok(&cp, CHARS_COMMA_SP)) != 0) {
483 	    if ((d = add_digest(tok, ++digest_pref)) == 0) {
484 		signalg = 0;
485 		signmd = 0;
486 		break;
487 	    }
488 	    if (digest_pref == 1) {
489 		signalg = d->mdalg;
490 		signmd = d->md;
491 	    }
492 	}
493 	myfree(save);
494     }
495     /* Don't report old news */
496     ERR_clear_error();
497 
498     /*
499      * DANE TLSA support requires trust-anchor support plus working DANE
500      * digests.
501      */
502     if (!ta_support
503 	|| (wrap_signed && (signkey = gencakey()) == 0)
504 	|| (serverAuth = OBJ_nid2obj(NID_server_auth)) == 0) {
505 	msg_warn("cannot generate TA certificates, "
506 		 "no trust-anchor or DANE support");
507 	tls_print_errors();
508 	dane_tlsa_support = ta_support = 0;
509     } else if (signmd == 0) {
510 	msg_warn("digest algorithm initializaton failed, no DANE support");
511 	tls_print_errors();
512 	dane_tlsa_support = 0;
513     }
514     dane_initialized = 1;
515 }
516 
517 /* tls_dane_avail - check for availability of dane required digests */
518 
519 int     tls_dane_avail(void)
520 {
521     if (!dane_initialized)
522 	dane_init();
523     return (dane_tlsa_support);
524 }
525 
526 /* tls_dane_flush - flush the cache */
527 
528 void    tls_dane_flush(void)
529 {
530     if (dane_cache)
531 	ctable_free(dane_cache);
532     dane_cache = 0;
533 }
534 
535 /* tls_dane_alloc - allocate a TLS_DANE structure */
536 
537 TLS_DANE *tls_dane_alloc(void)
538 {
539     TLS_DANE *dane = (TLS_DANE *) mymalloc(sizeof(*dane));
540 
541     dane->ta = 0;
542     dane->ee = 0;
543     dane->certs = 0;
544     dane->pkeys = 0;
545     dane->base_domain = 0;
546     dane->flags = 0;
547     dane->expires = 0;
548     dane->refs = 1;
549     return (dane);
550 }
551 
552 static void ta_cert_insert(TLS_DANE *d, X509 *x)
553 {
554     TLS_CERTS *new = (TLS_CERTS *) mymalloc(sizeof(*new));
555 
556     X509_up_ref(x);
557     new->cert = x;
558     new->next = d->certs;
559     d->certs = new;
560 }
561 
562 static void free_ta_certs(TLS_DANE *d)
563 {
564     TLS_CERTS *head;
565     TLS_CERTS *next;
566 
567     for (head = d->certs; head; head = next) {
568 	next = head->next;
569 	X509_free(head->cert);
570 	myfree((void *) head);
571     }
572 }
573 
574 static void ta_pkey_insert(TLS_DANE *d, EVP_PKEY *k)
575 {
576     TLS_PKEYS *new = (TLS_PKEYS *) mymalloc(sizeof(*new));
577 
578     EVP_PKEY_up_ref(k);
579     new->pkey = k;
580     new->next = d->pkeys;
581     d->pkeys = new;
582 }
583 
584 static void free_ta_pkeys(TLS_DANE *d)
585 {
586     TLS_PKEYS *head;
587     TLS_PKEYS *next;
588 
589     for (head = d->pkeys; head; head = next) {
590 	next = head->next;
591 	EVP_PKEY_free(head->pkey);
592 	myfree((void *) head);
593     }
594 }
595 
596 static void tlsa_free(TLS_TLSA *tlsa)
597 {
598 
599     myfree(tlsa->mdalg);
600     if (tlsa->certs)
601 	argv_free(tlsa->certs);
602     if (tlsa->pkeys)
603 	argv_free(tlsa->pkeys);
604     myfree((void *) tlsa);
605 }
606 
607 /* tls_dane_free - free a TLS_DANE structure */
608 
609 void    tls_dane_free(TLS_DANE *dane)
610 {
611     TLS_TLSA *tlsa;
612     TLS_TLSA *next;
613 
614     if (--dane->refs > 0)
615 	return;
616 
617     /* De-allocate TA and EE lists */
618     for (tlsa = dane->ta; tlsa; tlsa = next) {
619 	next = tlsa->next;
620 	tlsa_free(tlsa);
621     }
622     for (tlsa = dane->ee; tlsa; tlsa = next) {
623 	next = tlsa->next;
624 	tlsa_free(tlsa);
625     }
626 
627     /* De-allocate full trust-anchor certs and pkeys */
628     free_ta_certs(dane);
629     free_ta_pkeys(dane);
630     if (dane->base_domain)
631 	myfree(dane->base_domain);
632 
633     myfree((void *) dane);
634 }
635 
636 /* dane_free - ctable style */
637 
638 static void dane_free(void *dane, void *unused_context)
639 {
640     tls_dane_free((TLS_DANE *) dane);
641 }
642 
643 /* dane_locate - list head address of TLSA sublist for given algorithm */
644 
645 static TLS_TLSA **dane_locate(TLS_TLSA **tlsap, const char *mdalg)
646 {
647     TLS_TLSA *new;
648 
649     /*
650      * Correct computation of the session cache serverid requires a TLSA
651      * digest list that is sorted by algorithm name.  Below we maintain the
652      * sort order (by algorithm name canonicalized to lowercase).
653      */
654     for (; *tlsap; tlsap = &(*tlsap)->next) {
655 	int     cmp = strcasecmp(mdalg, (*tlsap)->mdalg);
656 
657 	if (cmp == 0)
658 	    return (tlsap);
659 	if (cmp < 0)
660 	    break;
661     }
662 
663     new = (TLS_TLSA *) mymalloc(sizeof(*new));
664     new->mdalg = lowercase(mystrdup(mdalg));
665     new->certs = 0;
666     new->pkeys = 0;
667     new->next = *tlsap;
668     *tlsap = new;
669 
670     return (tlsap);
671 }
672 
673 /* tls_dane_add_ee_digests - split and append digests */
674 
675 void    tls_dane_add_ee_digests(TLS_DANE *dane, const char *mdalg,
676 			              const char *digest, const char *delim)
677 {
678     TLS_TLSA **tlsap = dane_locate(&dane->ee, mdalg);
679     TLS_TLSA *tlsa = *tlsap;
680 
681     /* Delimited append, may append nothing */
682     if (tlsa->pkeys == 0)
683 	tlsa->pkeys = argv_split(digest, delim);
684     else
685 	argv_split_append(tlsa->pkeys, digest, delim);
686 
687     /* Remove empty elements from the list */
688     if (tlsa->pkeys->argc == 0) {
689 	argv_free(tlsa->pkeys);
690 	tlsa->pkeys = 0;
691 
692 	if (tlsa->certs == 0) {
693 	    *tlsap = tlsa->next;
694 	    tlsa_free(tlsa);
695 	}
696 	return;
697     }
698 
699     /*
700      * At the "fingerprint" security level certificate digests and public key
701      * digests are interchangeable.  Each leaf certificate is matched via
702      * either the public key digest or full certificate digest.  The DER
703      * encoding of a certificate is not a valid public key, and conversely,
704      * the DER encoding of a public key is not a valid certificate.  An
705      * attacker would need a 2nd-preimage that is feasible across types
706      * (given cert digest == some pkey digest) and yet presumably difficult
707      * within a type (e.g. given cert digest == some other cert digest).  No
708      * such attacks are known at this time, and it is expected that if any
709      * are found they would work within as well as across the cert/pkey data
710      * types.
711      */
712     if (tlsa->certs == 0)
713 	tlsa->certs = argv_split(digest, delim);
714     else
715 	argv_split_append(tlsa->certs, digest, delim);
716 }
717 
718 /* dane_add - add a digest entry */
719 
720 static void dane_add(TLS_DANE *dane, int certusage, int selector,
721 		             const char *mdalg, char *digest)
722 {
723     TLS_TLSA **tlsap;
724     TLS_TLSA *tlsa;
725     ARGV  **argvp;
726 
727     switch (certusage) {
728     case DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION:
729 	certusage = TLS_DANE_TA;
730 	break;
731     case DNS_TLSA_USAGE_SERVICE_CERTIFICATE_CONSTRAINT:
732     case DNS_TLSA_USAGE_DOMAIN_ISSUED_CERTIFICATE:
733 	certusage = TLS_DANE_EE;		/* Collapse 1/3 -> 3 */
734 	break;
735     default:
736 	msg_panic("Unsupported DANE certificate usage: %d", certusage);
737     }
738 
739     switch (selector) {
740     case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
741 	selector = TLS_DANE_CERT;
742 	break;
743     case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
744 	selector = TLS_DANE_PKEY;
745 	break;
746     default:
747 	msg_panic("Unsupported DANE selector: %d", selector);
748     }
749 
750     tlsap = (certusage == TLS_DANE_EE) ? &dane->ee : &dane->ta;
751     tlsa = *(tlsap = dane_locate(tlsap, mdalg));
752     argvp = (selector == TLS_DANE_PKEY) ? &tlsa->pkeys : &tlsa->certs;
753 
754     if (*argvp == 0)
755 	*argvp = argv_alloc(1);
756     argv_add(*argvp, digest, ARGV_END);
757 }
758 
759 #define FILTER_CTX_AGILITY_OK		(1<<0)
760 #define FILTER_CTX_CHECK_AGILITY	(1<<1)
761 #define FILTER_CTX_APPLY_AGILITY	(1<<2)
762 #define FILTER_CTX_PARSE_DATA		(1<<3)
763 
764 #define FILTER_RR_DROP			0
765 #define FILTER_RR_KEEP			1
766 
767 typedef struct filter_ctx {
768     TLS_DANE *dane;			/* Parsed result */
769     int     count;			/* Digest mtype count */
770     int     target;			/* Digest mtype target count */
771     int     flags;			/* Action/result bitmask */
772 } filter_ctx;
773 
774 typedef int (*tlsa_filter) (DNS_RR *, filter_ctx *);
775 
776 /* tlsa_apply - apply filter to each rr in turn */
777 
778 static DNS_RR *tlsa_apply(DNS_RR *rr, tlsa_filter filter, filter_ctx *ctx)
779 {
780     DNS_RR *head = 0;			/* First retained RR */
781     DNS_RR *tail = 0;			/* Last retained RR */
782     DNS_RR *next;
783 
784     /*
785      * XXX Code that modifies or destroys DNS_RR lists or entries belongs in
786      * the DNS library, not here.
787      */
788     for ( /* nop */ ; rr; rr = next) {
789 	next = rr->next;
790 
791 	if (filter(rr, ctx) == FILTER_RR_KEEP) {
792 	    tail = rr;
793 	    if (!head)
794 		head = rr;
795 	} else {
796 	    if (tail)
797 		tail->next = rr->next;
798 	    rr->next = 0;
799 	    dns_rr_free(rr);
800 	}
801     }
802     return (head);
803 }
804 
805 /* usmdelta - packed usage/selector/mtype bits changing in next record */
806 
807 static unsigned int usmdelta(uint8_t u, uint8_t s, uint8_t m, DNS_RR *next)
808 {
809     uint8_t *ip = (next && next->data_len >= 3) ? (uint8_t *) next->data : 0;
810     uint8_t nu = ip ? *ip++ : ~u;
811     uint8_t ns = ip ? *ip++ : ~s;
812     uint8_t nm = ip ? *ip++ : ~m;
813 
814     return (((u ^ nu) << 16) | ((s ^ ns) << 8) | (m ^ nm));
815 }
816 
817 /* tlsa_rr_cmp - qsort TLSA rrs in case shuffled by name server */
818 
819 static int tlsa_rr_cmp(DNS_RR *a, DNS_RR *b)
820 {
821     int     cmp;
822 
823     /*
824      * Sort in ascending order, by usage, selector, matching type preference
825      * and payload.  The usage, selector and matching type are the first
826      * three unsigned octets of the RR data.
827      */
828     if (a->data_len > 2 && b->data_len > 2) {
829 	uint8_t *ai = (uint8_t *) a->data;
830 	uint8_t *bi = (uint8_t *) b->data;
831 
832 #define signedcmp(x, y) (((int)(x)) - ((int)(y)))
833 
834 	if ((cmp = signedcmp(ai[0], bi[0])) != 0
835 	    || (cmp = signedcmp(ai[1], bi[1])) != 0
836 	    || (cmp = digest_pref_byid(ai[2]) -
837 		digest_pref_byid(bi[2])) != 0)
838 	    return (cmp);
839     }
840     if ((cmp = a->data_len - b->data_len) != 0)
841 	return (cmp);
842     return (memcmp(a->data, b->data, a->data_len));
843 }
844 
845 /* parse_tlsa_rr - parse a validated TLSA RRset */
846 
847 static int parse_tlsa_rr(DNS_RR *rr, filter_ctx *ctx)
848 {
849     uint8_t *ip;
850     uint8_t usage;
851     uint8_t selector;
852     uint8_t mtype;
853     ssize_t dlen;
854     D2I_const unsigned char *data;
855     D2I_const unsigned char *p;
856     int     iscname = strcasecmp(rr->rname, rr->qname);
857     const char *q = (iscname) ? (rr)->qname : "";
858     const char *a = (iscname) ? " -> " : "";
859     const char *r = rr->rname;
860     unsigned int change;
861 
862     if (rr->type != T_TLSA)
863 	msg_panic("unexpected non-TLSA RR type %u for %s%s%s", rr->type,
864 		  q, a, r);
865 
866     /* Drop truncated records */
867     if ((dlen = rr->data_len - 3) < 0) {
868 	msg_warn("truncated length %u RR: %s%s%s IN TLSA ...",
869 		 (unsigned) rr->data_len, q, a, r);
870 	ctx->flags &= ~FILTER_CTX_AGILITY_OK;
871 	return (FILTER_RR_DROP);
872     }
873     ip = (uint8_t *) rr->data;
874     usage = *ip++;
875     selector = *ip++;
876     mtype = *ip++;
877     change = usmdelta(usage, selector, mtype, rr->next);
878     p = data = (D2I_const unsigned char *) ip;
879 
880     /*
881      * Handle digest agility for non-zero matching types.
882      */
883     if (mtype) {
884 	if (ctx->count && (ctx->flags & FILTER_CTX_APPLY_AGILITY)) {
885 	    if (change & 0xffff00)		/* New usage/selector, */
886 		ctx->count = 0;			/* disable drop */
887 	    return (FILTER_RR_DROP);
888 	}
889 	if ((ctx->flags & FILTER_CTX_CHECK_AGILITY)
890 	    && (ctx->flags & FILTER_CTX_AGILITY_OK)) {
891 	    ++ctx->count;
892 	    if (change) {
893 		/*-
894 		 * Count changed from last mtype for same usage/selector?
895 		 * Yes, disable agility.
896 		 * Else, set or (on usage/selector change) reset target.
897 		 */
898 		if (ctx->target && ctx->target != ctx->count)
899 		    ctx->flags &= ~FILTER_CTX_AGILITY_OK;
900 		else
901 		    ctx->target = (change & 0xffff00) ? 0 : ctx->count;
902 		ctx->count = 0;
903 	    }
904 	}
905     }
906     /*-
907      * Drop unsupported usages.
908      * Note: NO SUPPORT for usage 0 which does not apply to SMTP.
909      * Note: Best-effort support for usage 1, which simply maps to 3.
910      */
911     switch (usage) {
912     case DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION:
913     case DNS_TLSA_USAGE_SERVICE_CERTIFICATE_CONSTRAINT:
914     case DNS_TLSA_USAGE_DOMAIN_ISSUED_CERTIFICATE:
915 	break;
916     default:
917 	msg_warn("unsupported certificate usage %u in RR: "
918 		 "%s%s%s IN TLSA %u ...", usage,
919 		 q, a, r, usage);
920 	return (FILTER_RR_DROP);
921     }
922 
923     /*
924      * Drop unsupported selectors
925      */
926     switch (selector) {
927     case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
928     case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
929 	break;
930     default:
931 	msg_warn("unsupported selector %u in RR: "
932 		 "%s%s%s IN TLSA %u %u ...", selector,
933 		 q, a, r, usage, selector);
934 	return (FILTER_RR_DROP);
935     }
936 
937     if (mtype) {
938 	dane_digest *d = digest_byid(mtype);
939 
940 	if (d == 0) {
941 	    msg_warn("unsupported matching type %u in RR: "
942 		     "%s%s%s IN TLSA %u %u %u ...", mtype,
943 		     q, a, r, usage, selector, mtype);
944 	    return (FILTER_RR_DROP);
945 	}
946 	if (dlen != d->len) {
947 	    msg_warn("malformed %s digest, length %lu, in RR: "
948 		     "%s%s%s IN TLSA %u %u %u ...",
949 		     d->mdalg, (unsigned long) dlen,
950 		     q, a, r, usage, selector, mtype);
951 	    ctx->flags &= ~FILTER_CTX_AGILITY_OK;
952 	    return (FILTER_RR_DROP);
953 	}
954 	if (!var_tls_dane_taa_dgst
955 	    && usage == DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION) {
956 	    msg_warn("trust-anchor digests disabled, ignoring RR: "
957 		     "%s%s%s IN TLSA %u %u %u ...", q, a, r,
958 		     usage, selector, mtype);
959 	    return (FILTER_RR_DROP);
960 	}
961 	/* New digest mtype next? Prepare to drop following RRs */
962 	if (change && (change & 0xffff00) == 0
963 	    && (ctx->flags & FILTER_CTX_APPLY_AGILITY))
964 	    ++ctx->count;
965 
966 	if (ctx->flags & FILTER_CTX_PARSE_DATA) {
967 	    char   *digest = tls_digest_encode(data, dlen);
968 
969 	    dane_add(ctx->dane, usage, selector, d->mdalg, digest);
970 	    if (msg_verbose || dane_verbose)
971 		msg_info("using DANE RR: %s%s%s IN TLSA %u %u %u %s",
972 			 q, a, r, usage, selector, mtype, digest);
973 	    myfree(digest);
974 	}
975     } else {
976 	X509   *x = 0;			/* OpenSSL re-uses *x if x!=0 */
977 	EVP_PKEY *k = 0;		/* OpenSSL re-uses *k if k!=0 */
978 
979 	/* Validate the cert or public key via d2i_mumble() */
980 	switch (selector) {
981 	case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
982 	    if (!d2i_X509(&x, &p, dlen) || dlen != p - data) {
983 		msg_warn("malformed %s in RR: "
984 			 "%s%s%s IN TLSA %u %u %u ...", "certificate",
985 			 q, a, r, usage, selector, mtype);
986 		if (x)
987 		    X509_free(x);
988 		return (FILTER_RR_DROP);
989 	    }
990 	    /* Also unusable if public key is malformed or unsupported */
991 	    k = X509_get_pubkey(x);
992 	    EVP_PKEY_free(k);
993 	    if (k == 0) {
994 		msg_warn("malformed %s in RR: %s%s%s IN TLSA %u %u %u ...",
995 			 "or unsupported certificate public key",
996 			 q, a, r, usage, selector, mtype);
997 		X509_free(x);
998 		return (FILTER_RR_DROP);
999 	    }
1000 
1001 	    /*
1002 	     * When a full trust-anchor certificate is published via DNS, we
1003 	     * may need to use it to validate the server trust chain. Store
1004 	     * it away for later use.
1005 	     */
1006 	    if (usage == DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION
1007 		&& (ctx->flags & FILTER_CTX_PARSE_DATA))
1008 		ta_cert_insert(ctx->dane, x);
1009 	    X509_free(x);
1010 	    break;
1011 
1012 	case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
1013 	    if (!d2i_PUBKEY(&k, &p, dlen) || dlen != p - data) {
1014 		msg_warn("malformed %s in RR: %s%s%s IN TLSA %u %u %u ...",
1015 			 "public key", q, a, r, usage, selector, mtype);
1016 		if (k)
1017 		    EVP_PKEY_free(k);
1018 		return (FILTER_RR_DROP);
1019 	    }
1020 
1021 	    /*
1022 	     * When a full trust-anchor public key is published via DNS, we
1023 	     * may need to use it to validate the server trust chain. Store
1024 	     * it away for later use.
1025 	     */
1026 	    if (usage == DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION
1027 		&& (ctx->flags & FILTER_CTX_PARSE_DATA))
1028 		ta_pkey_insert(ctx->dane, k);
1029 	    EVP_PKEY_free(k);
1030 	    break;
1031 	}
1032 
1033 	/*
1034 	 * The cert or key was valid, just digest the raw object, and encode
1035 	 * the digest value.
1036 	 */
1037 	if (ctx->flags & FILTER_CTX_PARSE_DATA) {
1038 	    char   *digest = tls_data_fprint((char *) data, dlen, signalg);
1039 
1040 	    dane_add(ctx->dane, usage, selector, signalg, digest);
1041 	    if (msg_verbose || dane_verbose)
1042 		msg_info("using DANE RR: %s%s%s IN TLSA %u %u %u <%s>; "
1043 			 "%s digest %s", q, a, r, usage, selector, mtype,
1044 			 (selector == DNS_TLSA_SELECTOR_FULL_CERTIFICATE) ?
1045 			 "certificate" : "public key", signalg, digest);
1046 	    myfree(digest);
1047 	}
1048     }
1049     return (FILTER_RR_KEEP);
1050 }
1051 
1052 /* process_rrs - filter and parse the TLSA RRset */
1053 
1054 static DNS_RR *process_rrs(TLS_DANE *dane, DNS_RR *rrset)
1055 {
1056     filter_ctx ctx;
1057 
1058     ctx.dane = dane;
1059     ctx.count = ctx.target = 0;
1060     ctx.flags = 0;
1061 
1062     switch (digest_agility) {
1063     case AGILITY_ON:
1064 	ctx.flags |= FILTER_CTX_APPLY_AGILITY | FILTER_CTX_PARSE_DATA;
1065 	break;
1066     case AGILITY_OFF:
1067 	ctx.flags |= FILTER_CTX_PARSE_DATA;
1068 	break;
1069     case AGILITY_MAYBE:
1070 	ctx.flags |= FILTER_CTX_CHECK_AGILITY | FILTER_CTX_AGILITY_OK;
1071 	break;
1072     }
1073 
1074     rrset = tlsa_apply(rrset, parse_tlsa_rr, &ctx);
1075 
1076     if (digest_agility == AGILITY_MAYBE) {
1077 	/* Two-pass algorithm */
1078 	if (ctx.flags & FILTER_CTX_AGILITY_OK)
1079 	    ctx.flags = FILTER_CTX_APPLY_AGILITY | FILTER_CTX_PARSE_DATA;
1080 	else
1081 	    ctx.flags = FILTER_CTX_PARSE_DATA;
1082 	rrset = tlsa_apply(rrset, parse_tlsa_rr, &ctx);
1083     }
1084     if (dane->ta == 0 && dane->ee == 0)
1085 	dane->flags |= TLS_DANE_FLAG_EMPTY;
1086 
1087     return (rrset);
1088 }
1089 
1090 /* dane_lookup - TLSA record lookup, ctable style */
1091 
1092 static void *dane_lookup(const char *tlsa_fqdn, void *unused_ctx)
1093 {
1094     static VSTRING *why = 0;
1095     int     ret;
1096     DNS_RR *rrs = 0;
1097     TLS_DANE *dane;
1098 
1099     if (why == 0)
1100 	why = vstring_alloc(10);
1101 
1102     dane = tls_dane_alloc();
1103     ret = dns_lookup(tlsa_fqdn, T_TLSA, RES_USE_DNSSEC, &rrs, 0, why);
1104 
1105     switch (ret) {
1106     case DNS_OK:
1107 	if (TLS_DANE_CACHE_TTL_MIN && rrs->ttl < TLS_DANE_CACHE_TTL_MIN)
1108 	    rrs->ttl = TLS_DANE_CACHE_TTL_MIN;
1109 	if (TLS_DANE_CACHE_TTL_MAX && rrs->ttl > TLS_DANE_CACHE_TTL_MAX)
1110 	    rrs->ttl = TLS_DANE_CACHE_TTL_MAX;
1111 
1112 	/* One more second to account for discrete time */
1113 	dane->expires = 1 + event_time() + rrs->ttl;
1114 
1115 	if (rrs->dnssec_valid) {
1116 
1117 	    /*
1118 	     * Sort for deterministic digest in session cache lookup key. In
1119 	     * addition we must arrange for more preferred matching types
1120 	     * (full value or digest) to precede less preferred ones for the
1121 	     * same usage and selector.
1122 	     */
1123 	    rrs = dns_rr_sort(rrs, tlsa_rr_cmp);
1124 	    rrs = process_rrs(dane, rrs);
1125 	} else
1126 	    dane->flags |= TLS_DANE_FLAG_NORRS;
1127 
1128 	if (rrs)
1129 	    dns_rr_free(rrs);
1130 	break;
1131 
1132     case DNS_NOTFOUND:
1133 	dane->flags |= TLS_DANE_FLAG_NORRS;
1134 	dane->expires = 1 + event_time() + TLS_DANE_CACHE_TTL_MIN;
1135 	break;
1136 
1137     default:
1138 	msg_warn("DANE TLSA lookup problem: %s", STR(why));
1139 	dane->flags |= TLS_DANE_FLAG_ERROR;
1140 	break;
1141     }
1142 
1143     return (void *) dane;
1144 }
1145 
1146 /* resolve_host - resolve TLSA RRs for hostname (rname or qname) */
1147 
1148 static TLS_DANE *resolve_host(const char *host, const char *proto,
1149 			              unsigned port)
1150 {
1151     static VSTRING *query_domain;
1152     TLS_DANE *dane;
1153 
1154     if (query_domain == 0)
1155 	query_domain = vstring_alloc(64);
1156 
1157     vstring_sprintf(query_domain, "_%u._%s.%s", ntohs(port), proto, host);
1158     dane = (TLS_DANE *) ctable_locate(dane_cache, STR(query_domain));
1159     if (timecmp(event_time(), dane->expires) > 0)
1160 	dane = (TLS_DANE *) ctable_refresh(dane_cache, STR(query_domain));
1161     if (dane->base_domain == 0)
1162 	dane->base_domain = mystrdup(host);
1163     /* Increment ref-count of cached entry */
1164     ++dane->refs;
1165     return (dane);
1166 }
1167 
1168 /* qname_secure - Lookup qname DNSSEC status */
1169 
1170 static int qname_secure(const char *qname)
1171 {
1172     static VSTRING *why;
1173     int     ret = 0;
1174     DNS_RR *rrs;
1175 
1176     if (!why)
1177 	why = vstring_alloc(10);
1178 
1179     /*
1180      * We assume that qname is already an fqdn, and does not need any
1181      * suffixes from RES_DEFNAME or RES_DNSRCH.  This is typically the name
1182      * of an MX host, and must be a complete DNS name.  DANE initialization
1183      * code in the SMTP client is responsible for checking that the default
1184      * resolver flags do not include RES_DEFNAME and RES_DNSRCH.
1185      */
1186     ret = dns_lookup(qname, T_CNAME, RES_USE_DNSSEC, &rrs, 0, why);
1187     if (ret == DNS_OK) {
1188 	ret = rrs->dnssec_valid;
1189 	dns_rr_free(rrs);
1190 	return (ret);
1191     }
1192     if (ret == DNS_NOTFOUND)
1193 	vstring_sprintf(why, "no longer a CNAME");
1194     msg_warn("DNSSEC status lookup error for %s: %s", qname, STR(why));
1195     return (-1);
1196 }
1197 
1198 /* tls_dane_resolve - cached map: (name, proto, port) -> TLS_DANE */
1199 
1200 TLS_DANE *tls_dane_resolve(unsigned port, const char *proto, DNS_RR *hostrr,
1201 			           int forcetlsa)
1202 {
1203     TLS_DANE *dane = 0;
1204     int     iscname = strcasecmp(hostrr->rname, hostrr->qname);
1205     int     isvalid = 1;
1206 
1207     if (!tls_dane_avail())
1208 	return (0);				/* Error */
1209 
1210     /*
1211      * By default suppress TLSA lookups for hosts in non-DNSSEC zones.  If
1212      * the host zone is not DNSSEC validated, the TLSA qname sub-domain is
1213      * safely assumed to not be in a DNSSEC Look-aside Validation child zone.
1214      */
1215     if (!forcetlsa && !hostrr->dnssec_valid) {
1216 	isvalid = iscname ? qname_secure(hostrr->qname) : 0;
1217 	if (isvalid < 0)
1218 	    return (0);				/* Error */
1219     }
1220     if (!isvalid) {
1221 	dane = tls_dane_alloc();
1222 	dane->flags = TLS_DANE_FLAG_NORRS;
1223     } else {
1224 	if (!dane_cache)
1225 	    dane_cache = ctable_create(CACHE_SIZE, dane_lookup, dane_free, 0);
1226 
1227 	/*
1228 	 * Try the rname first if secure, if nothing there, try the qname if
1229 	 * different.  Note, lookup errors are distinct from success with
1230 	 * nothing found.  If the rname lookup fails we don't try the qname.
1231 	 */
1232 	if (hostrr->dnssec_valid) {
1233 	    dane = resolve_host(hostrr->rname, proto, port);
1234 	    if (tls_dane_notfound(dane) && iscname) {
1235 		tls_dane_free(dane);
1236 		dane = 0;
1237 	    }
1238 	}
1239 	if (!dane)
1240 	    dane = resolve_host(hostrr->qname, proto, port);
1241 	if (dane->flags & TLS_DANE_FLAG_ERROR) {
1242 	    /* We don't return this object. */
1243 	    tls_dane_free(dane);
1244 	    dane = 0;
1245 	}
1246     }
1247 
1248     return (dane);
1249 }
1250 
1251 /* tls_dane_load_trustfile - load trust anchor certs or keys from file */
1252 
1253 int     tls_dane_load_trustfile(TLS_DANE *dane, const char *tafile)
1254 {
1255 #ifdef TRUST_ANCHOR_SUPPORT
1256     BIO    *bp;
1257     char   *name = 0;
1258     char   *header = 0;
1259     unsigned char *data = 0;
1260     long    len;
1261     int     tacount;
1262     char   *errtype = 0;		/* if error: cert or pkey? */
1263     const char *mdalg;
1264 
1265     /* nop */
1266     if (tafile == 0 || *tafile == 0)
1267 	return (1);
1268 
1269     if (!dane_initialized)
1270 	dane_init();
1271 
1272     if (!ta_support) {
1273 	msg_warn("trust-anchor files not supported");
1274 	return (0);
1275     }
1276     mdalg = signalg ? signalg : "sha1";
1277 
1278     /*
1279      * On each call, PEM_read() wraps a stdio file in a BIO_NOCLOSE bio,
1280      * calls PEM_read_bio() and then frees the bio.  It is just as easy to
1281      * open a BIO as a stdio file, so we use BIOs and call PEM_read_bio()
1282      * directly.
1283      */
1284     if ((bp = BIO_new_file(tafile, "r")) == NULL) {
1285 	msg_warn("error opening trust anchor file: %s: %m", tafile);
1286 	return (0);
1287     }
1288     /* Don't report old news */
1289     ERR_clear_error();
1290 
1291     for (tacount = 0;
1292 	 errtype == 0 && PEM_read_bio(bp, &name, &header, &data, &len);
1293 	 ++tacount) {
1294 	D2I_const unsigned char *p = data;
1295 	int     usage = DNS_TLSA_USAGE_TRUST_ANCHOR_ASSERTION;
1296 	int     selector;
1297 	char   *digest;
1298 
1299 	if (strcmp(name, PEM_STRING_X509) == 0
1300 	    || strcmp(name, PEM_STRING_X509_OLD) == 0) {
1301 	    X509   *cert = d2i_X509(0, &p, len);
1302 
1303 	    if (cert && (p - data) == len) {
1304 		selector = DNS_TLSA_SELECTOR_FULL_CERTIFICATE;
1305 		digest = tls_data_fprint((char *) data, len, mdalg);
1306 		dane_add(dane, usage, selector, mdalg, digest);
1307 		myfree(digest);
1308 		ta_cert_insert(dane, cert);
1309 	    } else
1310 		errtype = "certificate";
1311 	    if (cert)
1312 		X509_free(cert);
1313 	} else if (strcmp(name, PEM_STRING_PUBLIC) == 0) {
1314 	    EVP_PKEY *pkey = d2i_PUBKEY(0, &p, len);
1315 
1316 	    if (pkey && (p - data) == len) {
1317 		selector = DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO;
1318 		digest = tls_data_fprint((char *) data, len, mdalg);
1319 		dane_add(dane, usage, selector, mdalg, digest);
1320 		myfree(digest);
1321 		ta_pkey_insert(dane, pkey);
1322 	    } else
1323 		errtype = "public key";
1324 	    if (pkey)
1325 		EVP_PKEY_free(pkey);
1326 	}
1327 
1328 	/*
1329 	 * If any of these were null, PEM_read() would have failed.
1330 	 */
1331 	OPENSSL_free(name);
1332 	OPENSSL_free(header);
1333 	OPENSSL_free(data);
1334     }
1335     BIO_free(bp);
1336 
1337     if (errtype) {
1338 	tls_print_errors();
1339 	msg_warn("error reading: %s: malformed trust-anchor %s",
1340 		 tafile, errtype);
1341 	return (0);
1342     }
1343     if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) {
1344 	/* Reached end of PEM file */
1345 	ERR_clear_error();
1346 	return (tacount > 0);
1347     }
1348     /* Some other PEM read error */
1349     tls_print_errors();
1350 #else
1351     msg_warn("Trust anchor files not supported");
1352 #endif
1353     return (0);
1354 }
1355 
1356 /* tls_dane_match - match cert against given list of TA or EE digests */
1357 
1358 int     tls_dane_match(TLS_SESS_STATE *TLScontext, int usage,
1359 		               X509 *cert, int depth)
1360 {
1361     const TLS_DANE *dane = TLScontext->dane;
1362     TLS_TLSA *tlsa = (usage == TLS_DANE_EE) ? dane->ee : dane->ta;
1363     const char *namaddr = TLScontext->namaddr;
1364     const char *ustr = (usage == TLS_DANE_EE) ? "end entity" : "trust anchor";
1365     int     matched;
1366 
1367     for (matched = 0; tlsa && !matched; tlsa = tlsa->next) {
1368 	char  **dgst;
1369 
1370 	/*
1371 	 * Note, set_trust() needs to know whether the match was for a pkey
1372 	 * digest or a certificate digest.  We return MATCHED_PKEY or
1373 	 * MATCHED_CERT accordingly.
1374 	 */
1375 #define MATCHED_CERT 1
1376 #define MATCHED_PKEY 2
1377 
1378 	if (tlsa->pkeys) {
1379 	    char   *pkey_dgst = tls_pkey_fprint(cert, tlsa->mdalg);
1380 
1381 	    for (dgst = tlsa->pkeys->argv; !matched && *dgst; ++dgst)
1382 		if (strcasecmp(pkey_dgst, *dgst) == 0)
1383 		    matched = MATCHED_PKEY;
1384 	    if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_CERTMATCH)
1385 		&& matched)
1386 		msg_info("%s: depth=%d matched %s public-key %s digest=%s",
1387 			 namaddr, depth, ustr, tlsa->mdalg, pkey_dgst);
1388 	    myfree(pkey_dgst);
1389 	}
1390 	if (tlsa->certs != 0 && !matched) {
1391 	    char   *cert_dgst = tls_cert_fprint(cert, tlsa->mdalg);
1392 
1393 	    for (dgst = tlsa->certs->argv; !matched && *dgst; ++dgst)
1394 		if (strcasecmp(cert_dgst, *dgst) == 0)
1395 		    matched = MATCHED_CERT;
1396 	    if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_CERTMATCH)
1397 		&& matched)
1398 		msg_info("%s: depth=%d matched %s certificate %s digest %s",
1399 			 namaddr, depth, ustr, tlsa->mdalg, cert_dgst);
1400 	    myfree(cert_dgst);
1401 	}
1402     }
1403 
1404     return (matched);
1405 }
1406 
1407 /* push_ext - push extension onto certificate's stack, else free it */
1408 
1409 static int push_ext(X509 *cert, X509_EXTENSION *ext)
1410 {
1411     if (ext) {
1412 	if (X509_add_ext(cert, ext, -1))
1413 	    return 1;
1414 	X509_EXTENSION_free(ext);
1415     }
1416     return 0;
1417 }
1418 
1419 /* add_ext - add simple extension (no config section references) */
1420 
1421 static int add_ext(X509 *issuer, X509 *subject, int ext_nid, char *ext_val)
1422 {
1423     X509V3_CTX v3ctx;
1424 
1425     X509V3_set_ctx(&v3ctx, issuer, subject, 0, 0, 0);
1426     return push_ext(subject, X509V3_EXT_conf_nid(0, &v3ctx, ext_nid, ext_val));
1427 }
1428 
1429 /* set_serial - set serial number to match akid or use subject's plus 1 */
1430 
1431 static int set_serial(X509 *cert, AUTHORITY_KEYID *akid, X509 *subject)
1432 {
1433     int     ret = 0;
1434     BIGNUM *bn;
1435 
1436     if (akid && akid->serial)
1437 	return (X509_set_serialNumber(cert, akid->serial));
1438 
1439     /*
1440      * Add one to subject's serial to avoid collisions between TA serial and
1441      * serial of signing root.
1442      */
1443     if ((bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(subject), 0)) != 0
1444 	&& BN_add_word(bn, 1)
1445 	&& BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert)))
1446 	ret = 1;
1447 
1448     if (bn)
1449 	BN_free(bn);
1450     return (ret);
1451 }
1452 
1453 /* add_akid - add authority key identifier */
1454 
1455 static int add_akid(X509 *cert, AUTHORITY_KEYID *akid)
1456 {
1457     ASN1_OCTET_STRING *id;
1458     unsigned char c = 0;
1459     int     nid = NID_authority_key_identifier;
1460     int     ret = 0;
1461 
1462     /*
1463      * 0 will never be our subject keyid from a SHA-1 hash, but it could be
1464      * our subject keyid if forced from child's akid.  If so, set our
1465      * authority keyid to 1.  This way we are never self-signed, and thus
1466      * exempt from any potential (off by default for now in OpenSSL)
1467      * self-signature checks!
1468      */
1469     id = ((akid && akid->keyid) ? akid->keyid : 0);
1470     if (id && ASN1_STRING_length(id) == 1 && *ASN1_STRING_get0_data(id) == c)
1471 	c = 1;
1472 
1473     if ((akid = AUTHORITY_KEYID_new()) != 0
1474 	&& (akid->keyid = ASN1_OCTET_STRING_new()) != 0
1475 	&& ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
1476 	&& X509_add1_ext_i2d(cert, nid, akid, 0, X509V3_ADD_DEFAULT) > 0)
1477 	ret = 1;
1478     if (akid)
1479 	AUTHORITY_KEYID_free(akid);
1480     return (ret);
1481 }
1482 
1483 /* add_skid - add subject key identifier to match child's akid */
1484 
1485 static int add_skid(X509 *cert, AUTHORITY_KEYID *akid)
1486 {
1487     int     nid = NID_subject_key_identifier;
1488 
1489     if (!akid || !akid->keyid)
1490 	return (add_ext(0, cert, nid, "hash"));
1491     else
1492 	return (X509_add1_ext_i2d(cert, nid, akid->keyid, 0,
1493 				  X509V3_ADD_DEFAULT) > 0);
1494 }
1495 
1496 /* akid_issuer_name - get akid issuer directory name */
1497 
1498 static X509_NAME *akid_issuer_name(AUTHORITY_KEYID *akid)
1499 {
1500     if (akid && akid->issuer) {
1501 	int     i;
1502 	general_name_stack_t *gens = akid->issuer;
1503 
1504 	for (i = 0; i < sk_GENERAL_NAME_num(gens); ++i) {
1505 	    GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
1506 
1507 	    if (gn->type == GEN_DIRNAME)
1508 		return (gn->d.dirn);
1509 	}
1510     }
1511     return (0);
1512 }
1513 
1514 /* set_issuer - set issuer DN to match akid if specified */
1515 
1516 static int set_issuer_name(X509 *cert, AUTHORITY_KEYID *akid)
1517 {
1518     X509_NAME *name = akid_issuer_name(akid);
1519 
1520     /*
1521      * If subject's akid specifies an authority key identifer issuer name, we
1522      * must use that.
1523      */
1524     if (name)
1525 	return (X509_set_issuer_name(cert, name));
1526     return (X509_set_issuer_name(cert, X509_get_subject_name(cert)));
1527 }
1528 
1529 /* grow_chain - add certificate to trusted or untrusted chain */
1530 
1531 static void grow_chain(TLS_SESS_STATE *TLScontext, int trusted, X509 *cert)
1532 {
1533     x509_stack_t **xs = trusted ? &TLScontext->trusted : &TLScontext->untrusted;
1534 
1535 #define UNTRUSTED 0
1536 #define TRUSTED 1
1537 
1538     if (!*xs && (*xs = sk_X509_new_null()) == 0)
1539 	msg_fatal("out of memory");
1540     if (cert) {
1541 	if (trusted && !X509_add1_trust_object(cert, serverAuth))
1542 	    msg_fatal("out of memory");
1543 	X509_up_ref(cert);
1544 	if (!sk_X509_push(*xs, cert))
1545 	    msg_fatal("out of memory");
1546     }
1547 }
1548 
1549 /* wrap_key - wrap TA "key" as issuer of "subject" */
1550 
1551 static void wrap_key(TLS_SESS_STATE *TLScontext, int depth,
1552 		             EVP_PKEY *key, X509 *subject)
1553 {
1554     X509   *cert = 0;
1555     AUTHORITY_KEYID *akid;
1556     X509_NAME *name = X509_get_issuer_name(subject);
1557 
1558     /*
1559      * The subject name is never a NULL object unless we run out of memory.
1560      * It may be an empty sequence, but the containing object always exists
1561      * and its storage is owned by the certificate itself.
1562      */
1563     if (name == 0 || (cert = X509_new()) == 0)
1564 	msg_fatal("Out of memory");
1565 
1566     /*
1567      * Record the depth of the intermediate wrapper certificate, logged in
1568      * the verify callback.
1569      */
1570     if (TLScontext->tadepth < 0) {
1571 	TLScontext->tadepth = depth + 1;
1572 	if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_CERTMATCH))
1573 	    msg_info("%s: depth=%d chain is trust-anchor signed",
1574 		     TLScontext->namaddr, depth);
1575     }
1576     akid = X509_get_ext_d2i(subject, NID_authority_key_identifier, 0, 0);
1577 
1578     ERR_clear_error();
1579 
1580     /*
1581      * If key is NULL generate a self-signed root CA, with key "signkey",
1582      * otherwise an intermediate CA signed by above.
1583      *
1584      * CA cert valid for +/- 30 days.
1585      */
1586     if (!X509_set_version(cert, 2)
1587 	|| !set_serial(cert, akid, subject)
1588 	|| !set_issuer_name(cert, akid)
1589 	|| !X509_gmtime_adj(X509_getm_notBefore(cert), -30 * 86400L)
1590 	|| !X509_gmtime_adj(X509_getm_notAfter(cert), 30 * 86400L)
1591 	|| !X509_set_subject_name(cert, name)
1592 	|| !X509_set_pubkey(cert, key ? key : signkey)
1593 	|| !add_ext(0, cert, NID_basic_constraints, "CA:TRUE")
1594 	|| (key && !add_akid(cert, akid))
1595 	|| !add_skid(cert, akid)
1596 	|| (wrap_signed && !X509_sign(cert, signkey, signmd))) {
1597 	tls_print_errors();
1598 	msg_fatal("error generating DANE wrapper certificate");
1599     }
1600     if (akid)
1601 	AUTHORITY_KEYID_free(akid);
1602     if (key && wrap_signed) {
1603 	wrap_key(TLScontext, depth + 1, 0, cert);
1604 	grow_chain(TLScontext, UNTRUSTED, cert);
1605     } else
1606 	grow_chain(TLScontext, TRUSTED, cert);
1607     if (cert)
1608 	X509_free(cert);
1609 }
1610 
1611 /* wrap_cert - wrap "tacert" as trust-anchor. */
1612 
1613 static void wrap_cert(TLS_SESS_STATE *TLScontext, X509 *tacert, int depth)
1614 {
1615     X509   *cert;
1616     int     len;
1617     unsigned char *asn1;
1618     unsigned char *buf;
1619 
1620     if (TLScontext->tadepth < 0)
1621 	TLScontext->tadepth = depth + 1;
1622 
1623     if (TLScontext->log_mask & (TLS_LOG_VERBOSE | TLS_LOG_CERTMATCH))
1624 	msg_info("%s: depth=%d trust-anchor certificate",
1625 		 TLScontext->namaddr, depth);
1626 
1627     /*
1628      * If the TA certificate is self-issued, use it directly.
1629      */
1630     if (!wrap_signed || X509_check_issued(tacert, tacert) == X509_V_OK) {
1631 	grow_chain(TLScontext, TRUSTED, tacert);
1632 	return;
1633     }
1634     /* Deep-copy tacert by converting to ASN.1 and back */
1635     len = i2d_X509(tacert, NULL);
1636     asn1 = buf = (unsigned char *) mymalloc(len);
1637     i2d_X509(tacert, &buf);
1638     if (buf - asn1 != len)
1639 	msg_panic("i2d_X509 failed to encode TA certificate");
1640 
1641     buf = asn1;
1642     cert = d2i_X509(0, (D2I_const unsigned char **) &buf, len);
1643     if (!cert || (buf - asn1) != len)
1644 	msg_panic("d2i_X509 failed to decode TA certificate");
1645     myfree((void *) asn1);
1646 
1647     grow_chain(TLScontext, UNTRUSTED, cert);
1648 
1649     /* Sign and wrap TA cert with internal "signkey" */
1650     if (!X509_sign(cert, signkey, signmd)) {
1651 	tls_print_errors();
1652 	msg_fatal("error generating DANE wrapper certificate");
1653     }
1654     wrap_key(TLScontext, depth + 1, signkey, cert);
1655     X509_free(cert);
1656 }
1657 
1658 /* ta_signed - is certificate signed by a TLSA cert or pkey */
1659 
1660 static int ta_signed(TLS_SESS_STATE *TLScontext, X509 *cert, int depth)
1661 {
1662     const TLS_DANE *dane = TLScontext->dane;
1663     EVP_PKEY *pk;
1664     TLS_PKEYS *k;
1665     TLS_CERTS *x;
1666     int     done = 0;
1667 
1668     /*
1669      * First check whether issued and signed by a TA cert, this is cheaper
1670      * than the bare-public key checks below, since we can determine whether
1671      * the candidate TA certificate issued the certificate to be checked
1672      * first (name comparisons), before we bother with signature checks
1673      * (public key operations).
1674      */
1675     for (x = dane->certs; !done && x; x = x->next) {
1676 	if (X509_check_issued(x->cert, cert) == X509_V_OK) {
1677 	    if ((pk = X509_get_pubkey(x->cert)) == 0)
1678 		continue;
1679 	    /* Check signature, since some other TA may work if not this. */
1680 	    if ((done = (X509_verify(cert, pk) > 0)) != 0)
1681 		wrap_cert(TLScontext, x->cert, depth);
1682 	    EVP_PKEY_free(pk);
1683 	}
1684     }
1685 
1686     /*
1687      * With bare TA public keys, we can't check whether the trust chain is
1688      * issued by the key, but we can determine whether it is signed by the
1689      * key, so we go with that.
1690      *
1691      * Ideally, the corresponding certificate was presented in the chain, and we
1692      * matched it by its public key digest one level up.  This code is here
1693      * to handle adverse conditions imposed by sloppy administrators of
1694      * receiving systems with poorly constructed chains.
1695      *
1696      * We'd like to optimize out keys that should not match when the cert's
1697      * authority key id does not match the key id of this key computed via
1698      * the RFC keyid algorithm (SHA-1 digest of public key bit-string sans
1699      * ASN1 tag and length thus also excluding the unused bits field that is
1700      * logically part of the length).  However, some CAs have a non-standard
1701      * authority keyid, so we lose.  Too bad.
1702      *
1703      * This may push errors onto the stack when the certificate signature is not
1704      * of the right type or length, throw these away.
1705      */
1706     for (k = dane->pkeys; !done && k; k = k->next)
1707 	if ((done = (X509_verify(cert, k->pkey) > 0)) != 0)
1708 	    wrap_key(TLScontext, depth, k->pkey, cert);
1709 	else
1710 	    ERR_clear_error();
1711 
1712     return (done);
1713 }
1714 
1715 /* set_trust - configure for DANE validation */
1716 
1717 static void set_trust(TLS_SESS_STATE *TLScontext, X509_STORE_CTX *ctx)
1718 {
1719     int     n;
1720     int     i;
1721     int     match;
1722     int     depth = 0;
1723     EVP_PKEY *takey;
1724     X509   *ca;
1725     X509   *cert = X509_STORE_CTX_get0_cert(ctx);
1726     x509_stack_t *in = X509_STORE_CTX_get0_untrusted(ctx);
1727 
1728     /* shallow copy */
1729     if ((in = sk_X509_dup(in)) == 0)
1730 	msg_fatal("out of memory");
1731 
1732     /*
1733      * At each iteration we consume the issuer of the current cert.  This
1734      * reduces the length of the "in" chain by one.  If no issuer is found,
1735      * we are done.  We also stop when a certificate matches a TA in the
1736      * peer's TLSA RRset.
1737      *
1738      * Caller ensures that the initial certificate is not self-signed.
1739      */
1740     for (n = sk_X509_num(in); n > 0; --n, ++depth) {
1741 	for (i = 0; i < n; ++i)
1742 	    if (X509_check_issued(sk_X509_value(in, i), cert) == X509_V_OK)
1743 		break;
1744 
1745 	/*
1746 	 * Final untrusted element with no issuer in the peer's chain, it may
1747 	 * however be signed by a pkey or cert obtained via a TLSA RR.
1748 	 */
1749 	if (i == n)
1750 	    break;
1751 
1752 	/* Peer's chain contains an issuer ca. */
1753 	ca = sk_X509_delete(in, i);
1754 
1755 	/* Is it a trust anchor? */
1756 	match = tls_dane_match(TLScontext, TLS_DANE_TA, ca, depth + 1);
1757 	if (match) {
1758 	    switch (match) {
1759 	    case MATCHED_CERT:
1760 		wrap_cert(TLScontext, ca, depth);
1761 		break;
1762 	    case MATCHED_PKEY:
1763 		if ((takey = X509_get_pubkey(ca)) == 0)
1764 		    msg_panic("trust-anchor certificate has null pkey");
1765 		wrap_key(TLScontext, depth, takey, cert);
1766 		EVP_PKEY_free(takey);
1767 		break;
1768 	    default:
1769 		msg_panic("unexpected tls_dane_match result: %d", match);
1770 	    }
1771 	    cert = 0;
1772 	    break;
1773 	}
1774 	/* Add untrusted ca. */
1775 	grow_chain(TLScontext, UNTRUSTED, ca);
1776 
1777 	/* Final untrusted self-signed element? */
1778 	if (X509_check_issued(ca, ca) == X509_V_OK) {
1779 	    cert = 0;
1780 	    break;
1781 	}
1782 	/* Restart with issuer as subject */
1783 	cert = ca;
1784     }
1785 
1786     /*
1787      * When the loop exits, if "cert" is set, it is not self-signed and has
1788      * no issuer in the chain, we check for a possible signature via a DNS
1789      * obtained TA cert or public key.  Otherwise, we found no TAs and no
1790      * issuer, so set an empty list of TAs.
1791      */
1792     if (!cert || !ta_signed(TLScontext, cert, depth)) {
1793 	/* Create empty trust list if null, else NOP */
1794 	grow_chain(TLScontext, TRUSTED, 0);
1795     }
1796     /* shallow free */
1797     if (in)
1798 	sk_X509_free(in);
1799 }
1800 
1801 /* dane_cb - wrap chain verification for DANE */
1802 
1803 static int dane_cb(X509_STORE_CTX *ctx, void *app_ctx)
1804 {
1805     const char *myname = "dane_cb";
1806     TLS_SESS_STATE *TLScontext = (TLS_SESS_STATE *) app_ctx;
1807     X509   *cert = X509_STORE_CTX_get0_cert(ctx);
1808 
1809     /*
1810      * Degenerate case: depth 0 self-signed cert.
1811      *
1812      * XXX: Should we suppress name checks, ... when the leaf certificate is a
1813      * TA.  After all they could sign any name they want.  However, this
1814      * requires a bit of additional code.  For now we allow depth 0 TAs, but
1815      * then the peer name has to match.
1816      */
1817     if (X509_check_issued(cert, cert) == X509_V_OK) {
1818 
1819 	/*
1820 	 * Empty untrusted chain, could be NULL, but then ABI check less
1821 	 * reliable, we may zero some other field, ...
1822 	 */
1823 	grow_chain(TLScontext, UNTRUSTED, 0);
1824 	if (tls_dane_match(TLScontext, TLS_DANE_TA, cert, 0)) {
1825 	    TLScontext->tadepth = 0;
1826 	    grow_chain(TLScontext, TRUSTED, cert);
1827 	} else
1828 	    grow_chain(TLScontext, TRUSTED, 0);
1829     } else {
1830 	set_trust(TLScontext, ctx);
1831     }
1832 
1833     /*
1834      * Check that setting the untrusted chain updates the expected structure
1835      * member at the expected offset.
1836      */
1837     X509_STORE_CTX_set0_trusted_stack(ctx, TLScontext->trusted);
1838     X509_STORE_CTX_set0_untrusted(ctx, TLScontext->untrusted);
1839     if (X509_STORE_CTX_get0_untrusted(ctx) != TLScontext->untrusted)
1840 	msg_panic("%s: OpenSSL ABI change", myname);
1841 
1842     return X509_verify_cert(ctx);
1843 }
1844 
1845 /* tls_dane_set_callback - set or clear verification wrapper callback */
1846 
1847 void    tls_dane_set_callback(SSL_CTX *ctx, TLS_SESS_STATE *TLScontext)
1848 {
1849     if (ta_support && TLS_DANE_HASTA(TLScontext->dane))
1850 	SSL_CTX_set_cert_verify_callback(ctx, dane_cb, (void *) TLScontext);
1851     else
1852 	SSL_CTX_set_cert_verify_callback(ctx, 0, 0);
1853 }
1854 
1855 #ifdef TEST
1856 
1857 #include <unistd.h>
1858 #include <stdarg.h>
1859 
1860 #include <mail_params.h>
1861 #include <mail_conf.h>
1862 #include <msg_vstream.h>
1863 
1864 /* Cut/paste from OpenSSL 1.0.1: ssl/ssl_cert.c */
1865 
1866 static int ssl_verify_cert_chain(SSL *s, x509_stack_t *sk)
1867 {
1868     X509   *x;
1869     int     i;
1870     X509_STORE_CTX ctx;
1871 
1872     if ((sk == NULL) || (sk_X509_num(sk) == 0))
1873 	return (0);
1874 
1875     x = sk_X509_value(sk, 0);
1876     if (!X509_STORE_CTX_init(&ctx, s->ctx->cert_store, x, sk)) {
1877 	SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_X509_LIB);
1878 	return (0);
1879     }
1880     X509_STORE_CTX_set_ex_data(&ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s);
1881     X509_STORE_CTX_set_default(&ctx, s->server ? "ssl_client" : "ssl_server");
1882     X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(&ctx), s->param);
1883 
1884     if (s->verify_callback)
1885 	X509_STORE_CTX_set_verify_cb(&ctx, s->verify_callback);
1886 
1887     if (s->ctx->app_verify_callback != NULL)
1888 	i = s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg);
1889     else
1890 	i = X509_verify_cert(&ctx);
1891 
1892     s->verify_result = ctx.error;
1893     X509_STORE_CTX_cleanup(&ctx);
1894 
1895     return (i);
1896 }
1897 
1898 static void add_tlsa(TLS_DANE *dane, char *argv[])
1899 {
1900     char   *digest;
1901     X509   *cert = 0;
1902     BIO    *bp;
1903     unsigned char *buf;
1904     unsigned char *buf2;
1905     int     len;
1906     uint8_t u = atoi(argv[1]);
1907     uint8_t s = atoi(argv[2]);
1908     const char *mdname = argv[3];
1909     EVP_PKEY *pkey;
1910 
1911     if ((bp = BIO_new_file(argv[4], "r")) == NULL)
1912 	msg_fatal("error opening %s: %m", argv[4]);
1913     if (!PEM_read_bio_X509(bp, &cert, 0, 0)) {
1914 	tls_print_errors();
1915 	msg_fatal("error loading certificate from %s: %m", argv[4]);
1916     }
1917     BIO_free(bp);
1918 
1919     /*
1920      * Extract ASN.1 DER form of certificate or public key.
1921      */
1922     switch (s) {
1923     case DNS_TLSA_SELECTOR_FULL_CERTIFICATE:
1924 	len = i2d_X509(cert, NULL);
1925 	buf2 = buf = (unsigned char *) mymalloc(len);
1926 	i2d_X509(cert, &buf2);
1927 	if (!*mdname)
1928 	    ta_cert_insert(dane, cert);
1929 	break;
1930     case DNS_TLSA_SELECTOR_SUBJECTPUBLICKEYINFO:
1931 	pkey = X509_get_pubkey(cert);
1932 	len = i2d_PUBKEY(pkey, NULL);
1933 	buf2 = buf = (unsigned char *) mymalloc(len);
1934 	i2d_PUBKEY(pkey, &buf2);
1935 	if (!*mdname)
1936 	    ta_pkey_insert(dane, pkey);
1937 	EVP_PKEY_free(pkey);
1938 	break;
1939     }
1940     OPENSSL_assert(buf2 - buf == len);
1941 
1942     digest = tls_data_fprint((char *) buf, len, *mdname ? mdname : signalg);
1943     dane_add(dane, u, s, *mdname ? mdname : signalg, digest);
1944     myfree((void *) digest);
1945     myfree((void *) buf);
1946 }
1947 
1948 static x509_stack_t *load_chain(const char *chainfile)
1949 {
1950     BIO    *bp;
1951     char   *name = 0;
1952     char   *header = 0;
1953     unsigned char *data = 0;
1954     long    len;
1955     int     count;
1956     char   *errtype = 0;		/* if error: cert or pkey? */
1957     x509_stack_t *chain;
1958     typedef X509 *(*d2i_X509_t) (X509 **, const unsigned char **, long);
1959 
1960     if ((chain = sk_X509_new_null()) == 0) {
1961 	perror("malloc");
1962 	exit(1);
1963     }
1964 
1965     /*
1966      * On each call, PEM_read() wraps a stdio file in a BIO_NOCLOSE bio,
1967      * calls PEM_read_bio() and then frees the bio.  It is just as easy to
1968      * open a BIO as a stdio file, so we use BIOs and call PEM_read_bio()
1969      * directly.
1970      */
1971     if ((bp = BIO_new_file(chainfile, "r")) == NULL) {
1972 	fprintf(stderr, "error opening chainfile: %s: %m\n", chainfile);
1973 	exit(1);
1974     }
1975     /* Don't report old news */
1976     ERR_clear_error();
1977 
1978     for (count = 0;
1979 	 errtype == 0 && PEM_read_bio(bp, &name, &header, &data, &len);
1980 	 ++count) {
1981 	const unsigned char *p = data;
1982 
1983 	if (strcmp(name, PEM_STRING_X509) == 0
1984 	    || strcmp(name, PEM_STRING_X509_TRUSTED) == 0
1985 	    || strcmp(name, PEM_STRING_X509_OLD) == 0) {
1986 	    d2i_X509_t d;
1987 	    X509   *cert;
1988 
1989 	    d = strcmp(name, PEM_STRING_X509_TRUSTED) ? d2i_X509_AUX : d2i_X509;
1990 	    if ((cert = d(0, &p, len)) == 0 || (p - data) != len)
1991 		errtype = "certificate";
1992 	    else if (sk_X509_push(chain, cert) == 0) {
1993 		perror("malloc");
1994 		exit(1);
1995 	    }
1996 	} else {
1997 	    fprintf(stderr, "unexpected chain file object: %s\n", name);
1998 	    exit(1);
1999 	}
2000 
2001 	/*
2002 	 * If any of these were null, PEM_read() would have failed.
2003 	 */
2004 	OPENSSL_free(name);
2005 	OPENSSL_free(header);
2006 	OPENSSL_free(data);
2007     }
2008     BIO_free(bp);
2009 
2010     if (errtype) {
2011 	tls_print_errors();
2012 	fprintf(stderr, "error reading: %s: malformed %s", chainfile, errtype);
2013 	exit(1);
2014     }
2015     if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) {
2016 	/* Reached end of PEM file */
2017 	ERR_clear_error();
2018 	if (count > 0)
2019 	    return chain;
2020 	fprintf(stderr, "no certificates found in: %s\n", chainfile);
2021 	exit(1);
2022     }
2023     /* Some other PEM read error */
2024     tls_print_errors();
2025     fprintf(stderr, "error reading: %s\n", chainfile);
2026     exit(1);
2027 }
2028 
2029 static void usage(const char *progname)
2030 {
2031     fprintf(stderr, "Usage: %s certificate-usage selector matching-type"
2032 	    " certfile \\\n\t\tCAfile chainfile hostname [certname ...]\n",
2033 	    progname);
2034     fprintf(stderr, "  where, certificate-usage = TLSA certificate usage,\n");
2035     fprintf(stderr, "\t selector = TLSA selector,\n");
2036     fprintf(stderr, "\t matching-type = empty string or OpenSSL digest algorithm name,\n");
2037     fprintf(stderr, "\t PEM certfile provides certificate association data,\n");
2038     fprintf(stderr, "\t PEM CAfile contains any usage 0/1 trusted roots,\n");
2039     fprintf(stderr, "\t PEM chainfile = server chain file to verify\n");
2040     fprintf(stderr, "\t hostname = destination hostname,\n");
2041     fprintf(stderr, "\t each certname augments the hostname for name checks.\n");
2042     exit(1);
2043 }
2044 
2045 /* match_servername -  match servername against pattern */
2046 
2047 static int match_servername(const char *certid, ARGV *margv)
2048 {
2049     const char *domain;
2050     const char *parent;
2051     int     match_subdomain;
2052     int     i;
2053     int     idlen;
2054     int     domlen;
2055 
2056     /*
2057      * XXX EAI support.
2058      */
2059 
2060     /*
2061      * Match the certid against each pattern until we find a match.
2062      */
2063     for (i = 0; i < margv->argc; ++i) {
2064 	match_subdomain = 0;
2065 	domain = margv->argv[i];
2066 	if (*domain == '.' && domain[1] != '\0') {
2067 	    ++domain;
2068 	    match_subdomain = 1;
2069 	}
2070 
2071 	/*
2072 	 * Sub-domain match: certid is any sub-domain of hostname.
2073 	 */
2074 	if (match_subdomain) {
2075 	    if ((idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
2076 		&& certid[idlen - domlen - 1] == '.'
2077 		&& !strcasecmp(certid + (idlen - domlen), domain))
2078 		return (1);
2079 	    else
2080 		continue;
2081 	}
2082 
2083 	/*
2084 	 * Exact match and initial "*" match. The initial "*" in a certid
2085 	 * matches one (if var_tls_multi_label is false) or more hostname
2086 	 * components under the condition that the certid contains multiple
2087 	 * hostname components.
2088 	 */
2089 	if (!strcasecmp(certid, domain)
2090 	    || (certid[0] == '*' && certid[1] == '.' && certid[2] != 0
2091 		&& (parent = strchr(domain, '.')) != 0
2092 		&& (idlen = strlen(certid + 1)) <= (domlen = strlen(parent))
2093 		&& strcasecmp(var_tls_multi_wildcard == 0 ? parent :
2094 			      parent + domlen - idlen,
2095 			      certid + 1) == 0))
2096 	    return (1);
2097     }
2098     return (0);
2099 }
2100 
2101 static void check_name(TLS_SESS_STATE *tctx, X509 *cert, ARGV *margs)
2102 {
2103     char   *cn;
2104     int     matched = 0;
2105     general_name_stack_t *gens;
2106 
2107     if (SSL_get_verify_result(tctx->con) != X509_V_OK)
2108 	return;
2109 
2110     tctx->peer_status |= TLS_CERT_FLAG_TRUSTED;
2111 
2112     gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
2113     if (gens) {
2114 	int     has_dnsname = 0;
2115 	int     num_gens = sk_GENERAL_NAME_num(gens);
2116 	int     i;
2117 
2118 	for (i = 0; !matched && i < num_gens; ++i) {
2119 	    const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
2120 	    const char *dnsname;
2121 
2122 	    if (gn->type != GEN_DNS)
2123 		continue;
2124 	    has_dnsname = 1;
2125 	    tctx->peer_status |= TLS_CERT_FLAG_ALTNAME;
2126 	    dnsname = tls_dns_name(gn, tctx);
2127 	    if (dnsname && *dnsname
2128 		&& (matched = match_servername(dnsname, margs)) != 0)
2129 		tctx->peer_status |= TLS_CERT_FLAG_MATCHED;
2130 	}
2131 	sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
2132 	if (has_dnsname)
2133 	    return;
2134     }
2135     cn = tls_peer_CN(cert, tctx);
2136     if (match_servername(cn, margs))
2137 	tctx->peer_status |= TLS_CERT_FLAG_MATCHED;
2138     myfree(cn);
2139 }
2140 
2141 static void check_print(TLS_SESS_STATE *tctx, X509 *cert)
2142 {
2143     if (TLS_DANE_HASEE(tctx->dane)
2144 	&& tls_dane_match(tctx, TLS_DANE_EE, cert, 0))
2145 	tctx->peer_status |= TLS_CERT_FLAG_TRUSTED | TLS_CERT_FLAG_MATCHED;
2146 }
2147 
2148 static void check_peer(TLS_SESS_STATE *tctx, X509 *cert, int argc, char **argv)
2149 {
2150     ARGV    match;
2151 
2152     tctx->peer_status |= TLS_CERT_FLAG_PRESENT;
2153     check_print(tctx, cert);
2154     if (!TLS_CERT_IS_MATCHED(tctx)) {
2155 	match.argc = argc;
2156 	match.argv = argv;
2157 	check_name(tctx, cert, &match);
2158     }
2159 }
2160 
2161 static SSL_CTX *ctx_init(const char *CAfile)
2162 {
2163     SSL_CTX *client_ctx;
2164 
2165     tls_param_init();
2166     tls_check_version();
2167 
2168 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2169     SSL_load_error_strings();
2170     SSL_library_init();
2171 #endif
2172 
2173     if (!tls_validate_digest(LN_sha1))
2174 	msg_fatal("%s digest algorithm not available", LN_sha1);
2175 
2176     if (TLScontext_index < 0)
2177 	if ((TLScontext_index = SSL_get_ex_new_index(0, 0, 0, 0, 0)) < 0)
2178 	    msg_fatal("Cannot allocate SSL application data index");
2179 
2180     ERR_clear_error();
2181     if ((client_ctx = SSL_CTX_new(SSLv23_client_method())) == 0)
2182 	msg_fatal("cannot allocate client SSL_CTX");
2183     SSL_CTX_set_verify_depth(client_ctx, 5);
2184 
2185     if (tls_set_ca_certificate_info(client_ctx, CAfile, "") < 0) {
2186 	tls_print_errors();
2187 	msg_fatal("cannot load CAfile: %s", CAfile);
2188     }
2189     SSL_CTX_set_verify(client_ctx, SSL_VERIFY_NONE,
2190 		       tls_verify_certificate_callback);
2191     return (client_ctx);
2192 }
2193 
2194 int     main(int argc, char *argv[])
2195 {
2196     SSL_CTX *ssl_ctx;
2197     TLS_SESS_STATE *tctx;
2198     x509_stack_t *chain;
2199 
2200     var_procname = mystrdup(basename(argv[0]));
2201     set_mail_conf_str(VAR_PROCNAME, var_procname);
2202     msg_vstream_init(var_procname, VSTREAM_OUT);
2203 
2204     if (argc < 8)
2205 	usage(argv[0]);
2206 
2207     ssl_ctx = ctx_init(argv[5]);
2208     if (!tls_dane_avail())
2209 	msg_fatal("DANE TLSA support not available");
2210 
2211     tctx = tls_alloc_sess_context(TLS_LOG_NONE, argv[7]);
2212     tctx->namaddr = argv[7];
2213     tctx->mdalg = LN_sha1;
2214     tctx->dane = tls_dane_alloc();
2215 
2216     if ((tctx->con = SSL_new(ssl_ctx)) == 0
2217 	|| !SSL_set_ex_data(tctx->con, TLScontext_index, tctx)) {
2218 	tls_print_errors();
2219 	msg_fatal("Error allocating SSL connection");
2220     }
2221     SSL_set_connect_state(tctx->con);
2222     add_tlsa((TLS_DANE *) tctx->dane, argv);
2223     tls_dane_set_callback(ssl_ctx, tctx);
2224 
2225     /* Verify saved server chain */
2226     chain = load_chain(argv[6]);
2227     ssl_verify_cert_chain(tctx->con, chain);
2228     check_peer(tctx, sk_X509_value(chain, 0), argc - 7, argv + 7);
2229     tls_print_errors();
2230 
2231     msg_info("%s %s", TLS_CERT_IS_MATCHED(tctx) ? "Verified" :
2232 	     TLS_CERT_IS_TRUSTED(tctx) ? "Trusted" : "Untrusted", argv[7]);
2233 
2234     return (TLS_CERT_IS_MATCHED(tctx) ? 0 : 1);
2235 }
2236 
2237 #endif					/* TEST */
2238 
2239 #endif					/* USE_TLS */
2240