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