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