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