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