af7497a934111c94c23746149268a9880063a0c0
[exim.git] / src / src / dane-openssl.c
1 /*
2  *  Author: Viktor Dukhovni
3  *  License: THIS CODE IS IN THE PUBLIC DOMAIN.
4  *
5  * Copyright (c) The Exim Maintainers 2014 - 2019
6  */
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdint.h>
10
11 #include <openssl/opensslv.h>
12 #include <openssl/err.h>
13 #include <openssl/crypto.h>
14 #include <openssl/safestack.h>
15 #include <openssl/objects.h>
16 #include <openssl/x509.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/evp.h>
19 #include <openssl/bn.h>
20
21 #if OPENSSL_VERSION_NUMBER < 0x1000000fL
22 # error "OpenSSL 1.0.0 or higher required"
23 #endif
24
25 #if OPENSSL_VERSION_NUMBER < 0x10100000L
26 # define X509_up_ref(x) CRYPTO_add(&((x)->references), 1, CRYPTO_LOCK_X509)
27 #endif
28
29 /* LibreSSL 2.9.0 and later - 2.9.0 has removed a number of macros ... */
30 #ifdef LIBRESSL_VERSION_NUMBER
31 # if LIBRESSL_VERSION_NUMBER >= 0x2090000fL
32 #  define EXIM_HAVE_ASN1_MACROS
33 #  define EXIM_OPAQUE_X509
34 # endif
35 #endif
36 /* OpenSSL */
37 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
38 # define EXIM_HAVE_ASN1_MACROS
39 # define EXIM_OPAQUE_X509
40 #else
41 /* Older OpenSSL and all LibreSSL */
42 # if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x3050000fL
43 /* LibreSSL before 3.5.0 */
44 #  define X509_STORE_CTX_get_verify(ctx)        (ctx)->verify
45 #  define X509_STORE_CTX_get_verify_cb(ctx)     (ctx)->verify_cb
46 #  define X509_STORE_CTX_get0_cert(ctx)         (ctx)->cert
47 #  define X509_STORE_CTX_get0_chain(ctx)        (ctx)->chain
48 #  define X509_STORE_CTX_get0_untrusted(ctx)    (ctx)->untrusted
49
50 #  define X509_STORE_CTX_set_verify(ctx, verify_chain)  (ctx)->verify = (verify_chain)
51 #  define X509_STORE_CTX_set0_verified_chain(ctx, sk)   (ctx)->chain = (sk)
52 #  define X509_STORE_CTX_set_error_depth(ctx, val)      (ctx)->error_depth = (val)
53 #  define X509_STORE_CTX_set_current_cert(ctx, cert)    (ctx)->current_cert = (cert)
54
55 #  define ASN1_STRING_get0_data ASN1_STRING_data
56 #  define X509_getm_notBefore   X509_get_notBefore
57 #  define X509_getm_notAfter    X509_get_notAfter
58 # endif /* LibreSSL < 3.5.0 */
59
60 # define CRYPTO_ONCE_STATIC_INIT 0
61 # define CRYPTO_THREAD_run_once  run_once
62 typedef int CRYPTO_ONCE;
63 #endif
64
65
66 #include "danessl.h"
67
68 #define DANESSL_F_ADD_SKID              100
69 #define DANESSL_F_ADD_TLSA              101
70 #define DANESSL_F_CHECK_END_ENTITY      102
71 #define DANESSL_F_CTX_INIT              103
72 #define DANESSL_F_GROW_CHAIN            104
73 #define DANESSL_F_INIT                  105
74 #define DANESSL_F_LIBRARY_INIT          106
75 #define DANESSL_F_LIST_ALLOC            107
76 #define DANESSL_F_MATCH                 108
77 #define DANESSL_F_PUSH_EXT              109
78 #define DANESSL_F_SET_TRUST_ANCHOR      110
79 #define DANESSL_F_VERIFY_CERT           111
80 #define DANESSL_F_WRAP_CERT             112
81 #define DANESSL_F_DANESSL_VERIFY_CHAIN  113
82
83 #define DANESSL_R_BAD_CERT              100
84 #define DANESSL_R_BAD_CERT_PKEY         101
85 #define DANESSL_R_BAD_DATA_LENGTH       102
86 #define DANESSL_R_BAD_DIGEST            103
87 #define DANESSL_R_BAD_NULL_DATA         104
88 #define DANESSL_R_BAD_PKEY              105
89 #define DANESSL_R_BAD_SELECTOR          106
90 #define DANESSL_R_BAD_USAGE             107
91 #define DANESSL_R_INIT                  108
92 #define DANESSL_R_LIBRARY_INIT          109
93 #define DANESSL_R_NOSIGN_KEY            110
94 #define DANESSL_R_SCTX_INIT             111
95 #define DANESSL_R_SUPPORT               112
96
97 #ifndef OPENSSL_NO_ERR
98 #define DANESSL_F_PLACEHOLDER           0               /* FIRST! Value TBD */
99 static ERR_STRING_DATA dane_str_functs[] = {
100     /*  error                           string */
101     {DANESSL_F_PLACEHOLDER,             "DANE library"},        /* FIRST!!! */
102     {DANESSL_F_ADD_SKID,                "add_skid"},
103     {DANESSL_F_ADD_TLSA,                "DANESSL_add_tlsa"},
104     {DANESSL_F_CHECK_END_ENTITY,        "check_end_entity"},
105     {DANESSL_F_CTX_INIT,                "DANESSL_CTX_init"},
106     {DANESSL_F_GROW_CHAIN,              "grow_chain"},
107     {DANESSL_F_INIT,                    "DANESSL_init"},
108     {DANESSL_F_LIBRARY_INIT,            "DANESSL_library_init"},
109     {DANESSL_F_LIST_ALLOC,              "list_alloc"},
110     {DANESSL_F_MATCH,                   "match"},
111     {DANESSL_F_PUSH_EXT,                "push_ext"},
112     {DANESSL_F_SET_TRUST_ANCHOR,        "set_trust_anchor"},
113     {DANESSL_F_VERIFY_CERT,             "verify_cert"},
114     {DANESSL_F_WRAP_CERT,               "wrap_cert"},
115     {0,                                 NULL}
116 };
117 static ERR_STRING_DATA dane_str_reasons[] = {
118     /*  error                           string */
119     {DANESSL_R_BAD_CERT,        "Bad TLSA record certificate"},
120     {DANESSL_R_BAD_CERT_PKEY,   "Bad TLSA record certificate public key"},
121     {DANESSL_R_BAD_DATA_LENGTH, "Bad TLSA record digest length"},
122     {DANESSL_R_BAD_DIGEST,      "Bad TLSA record digest"},
123     {DANESSL_R_BAD_NULL_DATA,   "Bad TLSA record null data"},
124     {DANESSL_R_BAD_PKEY,        "Bad TLSA record public key"},
125     {DANESSL_R_BAD_SELECTOR,    "Bad TLSA record selector"},
126     {DANESSL_R_BAD_USAGE,       "Bad TLSA record usage"},
127     {DANESSL_R_INIT,            "DANESSL_init() required"},
128     {DANESSL_R_LIBRARY_INIT,    "DANESSL_library_init() required"},
129     {DANESSL_R_NOSIGN_KEY,      "Certificate usage 2 requires EC support"},
130     {DANESSL_R_SCTX_INIT,       "DANESSL_CTX_init() required"},
131     {DANESSL_R_SUPPORT,         "DANE library features not supported"},
132     {0,                         NULL}
133 };
134 #endif
135
136 #define DANEerr(f, r) ERR_PUT_error(err_lib_dane, (f), (r), __FUNCTION__, __LINE__)
137
138 static int err_lib_dane = -1;
139 static int dane_idx = -1;
140
141 #ifdef X509_V_FLAG_PARTIAL_CHAIN       /* OpenSSL >= 1.0.2 */
142 static int wrap_to_root = 0;
143 #else
144 static int wrap_to_root = 1;
145 #endif
146
147 static void (*cert_free)(void *) = (void (*)(void *)) X509_free;
148 static void (*pkey_free)(void *) = (void (*)(void *)) EVP_PKEY_free;
149
150 typedef struct dane_list
151 {
152     struct dane_list *next;
153     void *value;
154 } *dane_list;
155
156 #define LINSERT(h, e) do { (e)->next = (h); (h) = (e); } while (0)
157
158 typedef struct dane_host_list
159 {
160     struct dane_host_list *next;
161     char *value;
162 } *dane_host_list;
163
164 typedef struct dane_data
165 {
166     size_t datalen;
167     unsigned char data[0];
168 } *dane_data;
169
170 typedef struct dane_data_list
171 {
172     struct dane_data_list *next;
173     dane_data value;
174 } *dane_data_list;
175
176 typedef struct dane_mtype
177 {
178     int mdlen;
179     const EVP_MD *md;
180     dane_data_list data;
181 } *dane_mtype;
182
183 typedef struct dane_mtype_list
184 {
185     struct dane_mtype_list *next;
186     dane_mtype value;
187 } *dane_mtype_list;
188
189 typedef struct dane_selector
190 {
191     uint8_t selector;
192     dane_mtype_list mtype;
193 } *dane_selector;
194
195 typedef struct dane_selector_list
196 {
197     struct dane_selector_list *next;
198     dane_selector value;
199 } *dane_selector_list;
200
201 typedef struct dane_pkey_list
202 {
203     struct dane_pkey_list *next;
204     EVP_PKEY *value;
205 } *dane_pkey_list;
206
207 typedef struct dane_cert_list
208 {
209     struct dane_cert_list *next;
210     X509 *value;
211 } *dane_cert_list;
212
213 typedef struct ssl_dane
214 {
215     int            (*verify)(X509_STORE_CTX *);
216     STACK_OF(X509) *roots;
217     STACK_OF(X509) *chain;
218     X509           *match;              /* Matched cert */
219     const char     *thost;              /* TLSA base domain */
220     char           *mhost;              /* Matched peer name */
221     dane_pkey_list pkeys;
222     dane_cert_list certs;
223     dane_host_list hosts;
224     dane_selector_list selectors[DANESSL_USAGE_LAST + 1];
225     int            depth;
226     int            mdpth;               /* Depth of matched cert */
227     int            multi;               /* Multi-label wildcards? */
228     int            count;               /* Number of TLSA records */
229 } ssl_dane;
230
231 #ifndef X509_V_ERR_HOSTNAME_MISMATCH
232 # define X509_V_ERR_HOSTNAME_MISMATCH X509_V_ERR_APPLICATION_VERIFICATION
233 #endif
234
235
236
237 static int
238 match(dane_selector_list slist, X509 *cert, int depth)
239 {
240 int matched;
241
242 /*
243  * Note, set_trust_anchor() needs to know whether the match was for a
244  * pkey digest or a certificate digest.  We return MATCHED_PKEY or
245  * MATCHED_CERT accordingly.
246  */
247 #define MATCHED_CERT (DANESSL_SELECTOR_CERT + 1)
248 #define MATCHED_PKEY (DANESSL_SELECTOR_SPKI + 1)
249
250 /*
251  * Loop over each selector, mtype, and associated data element looking
252  * for a match.
253  */
254 for (matched = 0; !matched && slist; slist = slist->next)
255   {
256   unsigned char mdbuf[EVP_MAX_MD_SIZE];
257   unsigned char *buf = NULL;
258   unsigned char *buf2;
259   unsigned int len = 0;
260
261   /*
262    * Extract ASN.1 DER form of certificate or public key.
263    */
264   switch(slist->value->selector)
265     {
266     case DANESSL_SELECTOR_CERT:
267       len = i2d_X509(cert, NULL);
268       buf2 = buf = US  OPENSSL_malloc(len);
269       if(buf) i2d_X509(cert, &buf2);
270       break;
271     case DANESSL_SELECTOR_SPKI:
272       len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
273       buf2 = buf = US  OPENSSL_malloc(len);
274       if(buf) i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf2);
275       break;
276     }
277
278   if (!buf)
279     {
280     DANEerr(DANESSL_F_MATCH, ERR_R_MALLOC_FAILURE);
281     return 0;
282     }
283   OPENSSL_assert(buf2 - buf == len);
284
285   /*
286    * Loop over each mtype and data element
287    */
288   for (dane_mtype_list m = slist->value->mtype; !matched && m; m = m->next)
289     {
290     unsigned char *cmpbuf = buf;
291     unsigned int cmplen = len;
292
293     /*
294      * If it is a digest, compute the corresponding digest of the
295      * DER data for comparison, otherwise, use the full object.
296      */
297     if (m->value->md)
298       {
299       cmpbuf = mdbuf;
300       if (!EVP_Digest(buf, len, cmpbuf, &cmplen, m->value->md, 0))
301           matched = -1;
302       }
303     for (dane_data_list d = m->value->data; !matched && d; d = d->next)
304         if (  cmplen == d->value->datalen
305            && memcmp(cmpbuf, d->value->data, cmplen) == 0)
306             matched = slist->value->selector + 1;
307     }
308
309   OPENSSL_free(buf);
310   }
311
312 return matched;
313 }
314
315 static int
316 push_ext(X509 *cert, X509_EXTENSION *ext)
317 {
318 if (ext)
319   {
320   if (X509_add_ext(cert, ext, -1))
321       return 1;
322   X509_EXTENSION_free(ext);
323   }
324 DANEerr(DANESSL_F_PUSH_EXT, ERR_R_MALLOC_FAILURE);
325 return 0;
326 }
327
328 static int
329 add_ext(X509 *issuer, X509 *subject, int ext_nid, char *ext_val)
330 {
331 X509V3_CTX v3ctx;
332
333 X509V3_set_ctx(&v3ctx, issuer, subject, 0, 0, 0);
334 return push_ext(subject, X509V3_EXT_conf_nid(0, &v3ctx, ext_nid, ext_val));
335 }
336
337 static int
338 set_serial(X509 *cert, AUTHORITY_KEYID *akid, X509 *subject)
339 {
340 int ret = 0;
341 BIGNUM *bn;
342
343 if (akid && akid->serial)
344   return (X509_set_serialNumber(cert, akid->serial));
345
346 /*
347  * Add one to subject's serial to avoid collisions between TA serial and
348  * serial of signing root.
349  */
350 if (  (bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(subject), 0)) != 0
351    && BN_add_word(bn, 1)
352    && BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert)))
353   ret = 1;
354
355 if (bn)
356   BN_free(bn);
357 return ret;
358 }
359
360 static int
361 add_akid(X509 *cert, AUTHORITY_KEYID *akid)
362 {
363 int nid = NID_authority_key_identifier;
364 ASN1_OCTET_STRING *id;
365 unsigned char c = 0;
366 int ret = 0;
367
368 /*
369  * 0 will never be our subject keyid from a SHA-1 hash, but it could be
370  * our subject keyid if forced from child's akid.  If so, set our
371  * authority keyid to 1.  This way we are never self-signed, and thus
372  * exempt from any potential (off by default for now in OpenSSL)
373  * self-signature checks!
374  */
375 id =  akid && akid->keyid ? akid->keyid : 0;
376 if (id && ASN1_STRING_length(id) == 1 && *ASN1_STRING_get0_data(id) == c)
377   c = 1;
378
379 if (  (akid = AUTHORITY_KEYID_new()) != 0
380    && (akid->keyid = ASN1_OCTET_STRING_new()) != 0
381 #ifdef EXIM_HAVE_ASN1_MACROS
382    && ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
383 #else
384    && M_ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
385 #endif
386    && X509_add1_ext_i2d(cert, nid, akid, 0, X509V3_ADD_APPEND))
387   ret = 1;
388 if (akid)
389   AUTHORITY_KEYID_free(akid);
390 return ret;
391 }
392
393 static int
394 add_skid(X509 *cert, AUTHORITY_KEYID *akid)
395 {
396 int nid = NID_subject_key_identifier;
397
398 if (!akid || !akid->keyid)
399   return add_ext(0, cert, nid, "hash");
400 return X509_add1_ext_i2d(cert, nid, akid->keyid, 0, X509V3_ADD_APPEND) > 0;
401 }
402
403 static X509_NAME *
404 akid_issuer_name(AUTHORITY_KEYID *akid)
405 {
406 if (akid && akid->issuer)
407   {
408   GENERAL_NAMES *gens = akid->issuer;
409
410   for (int i = 0; i < sk_GENERAL_NAME_num(gens); ++i)
411     {
412     GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
413
414     if (gn->type == GEN_DIRNAME)
415       return (gn->d.dirn);
416     }
417   }
418 return 0;
419 }
420
421 static int
422 set_issuer_name(X509 *cert, AUTHORITY_KEYID *akid, X509_NAME *subj)
423 {
424 X509_NAME *name = akid_issuer_name(akid);
425
426 /*
427  * If subject's akid specifies an authority key identifier issuer name, we
428  * must use that.
429  */
430 return X509_set_issuer_name(cert,
431                             name ? name : subj);
432 }
433
434 static int
435 grow_chain(ssl_dane *dane, int trusted, X509 *cert)
436 {
437 STACK_OF(X509) **xs = trusted ? &dane->roots : &dane->chain;
438 static ASN1_OBJECT *serverAuth = 0;
439
440 #define UNTRUSTED 0
441 #define TRUSTED 1
442
443 if (  trusted && !serverAuth
444    && !(serverAuth = OBJ_nid2obj(NID_server_auth)))
445   {
446   DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
447   return 0;
448   }
449 if (!*xs && !(*xs = sk_X509_new_null()))
450   {
451   DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
452   return 0;
453   }
454
455 if (cert)
456   {
457   if (trusted && !X509_add1_trust_object(cert, serverAuth))
458     return 0;
459 #ifdef EXIM_OPAQUE_X509
460   X509_up_ref(cert);
461 #else
462   CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
463 #endif
464   if (!sk_X509_push(*xs, cert))
465     {
466     X509_free(cert);
467     DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
468     return 0;
469     }
470   }
471 return 1;
472 }
473
474 static int
475 wrap_issuer(ssl_dane *dane, EVP_PKEY *key, X509 *subject, int depth, int top)
476 {
477 int ret = 1;
478 X509 *cert = 0;
479 AUTHORITY_KEYID *akid;
480 X509_NAME *name = X509_get_issuer_name(subject);
481 EVP_PKEY *newkey = key ? key : X509_get_pubkey(subject);
482
483 #define WRAP_MID 0              /* Ensure intermediate. */
484 #define WRAP_TOP 1              /* Ensure self-signed. */
485
486 if (!name || !newkey || !(cert = X509_new()))
487   return 0;
488
489 /*
490  * Record the depth of the trust-anchor certificate.
491  */
492 if (dane->depth < 0)
493   dane->depth = depth + 1;
494
495 /*
496  * XXX: Uncaught error condition:
497  *
498  * The return value is NULL both when the extension is missing, and when
499  * OpenSSL rans out of memory while parsing the extension.
500  */
501 ERR_clear_error();
502 akid = X509_get_ext_d2i(subject, NID_authority_key_identifier, 0, 0);
503 /* XXX: Should we peek at the error stack here??? */
504
505 /*
506  * If top is true generate a self-issued root CA, otherwise an
507  * intermediate CA and possibly its self-signed issuer.
508  *
509  * CA cert valid for +/- 30 days
510  */
511 if (  !X509_set_version(cert, 2)
512    || !set_serial(cert, akid, subject)
513    || !set_issuer_name(cert, akid, name)
514    || !X509_gmtime_adj(X509_getm_notBefore(cert), -30 * 86400L)
515    || !X509_gmtime_adj(X509_getm_notAfter(cert), 30 * 86400L)
516    || !X509_set_subject_name(cert, name)
517    || !X509_set_pubkey(cert, newkey)
518    || !add_ext(0, cert, NID_basic_constraints, "CA:TRUE")
519    || (!top && !add_akid(cert, akid))
520    || !add_skid(cert, akid)
521    || (  !top && wrap_to_root
522       && !wrap_issuer(dane, newkey, cert, depth, WRAP_TOP)))
523   ret = 0;
524
525 if (akid)
526   AUTHORITY_KEYID_free(akid);
527 if (!key)
528   EVP_PKEY_free(newkey);
529 if (ret)
530   ret = grow_chain(dane, !top && wrap_to_root ? UNTRUSTED : TRUSTED, cert);
531 if (cert)
532   X509_free(cert);
533 return ret;
534 }
535
536 static int
537 wrap_cert(ssl_dane *dane, X509 *tacert, int depth)
538 {
539 if (dane->depth < 0)
540   dane->depth = depth + 1;
541
542 /*
543  * If the TA certificate is self-issued, or need not be, use it directly.
544  * Otherwise, synthesize requisite ancestors.
545  */
546 if (  !wrap_to_root
547    || X509_check_issued(tacert, tacert) == X509_V_OK)
548   return grow_chain(dane, TRUSTED, tacert);
549
550 if (wrap_issuer(dane, 0, tacert, depth, WRAP_MID))
551   return grow_chain(dane, UNTRUSTED, tacert);
552 return 0;
553 }
554
555 static int
556 ta_signed(ssl_dane *dane, X509 *cert, int depth)
557 {
558 EVP_PKEY *pk;
559 int done = 0;
560
561 /*
562  * First check whether issued and signed by a TA cert, this is cheaper
563  * than the bare-public key checks below, since we can determine whether
564  * the candidate TA certificate issued the certificate to be checked
565  * first (name comparisons), before we bother with signature checks
566  * (public key operations).
567  */
568 for (dane_cert_list x = dane->certs; !done && x; x = x->next)
569   {
570   if (X509_check_issued(x->value, cert) == X509_V_OK)
571     {
572     if (!(pk = X509_get_pubkey(x->value)))
573       {
574       /*
575        * The cert originally contained a valid pkey, which does
576        * not just vanish, so this is most likely a memory error.
577        */
578       done = -1;
579       break;
580       }
581     /* Check signature, since some other TA may work if not this. */
582     if (X509_verify(cert, pk) > 0)
583       done = wrap_cert(dane, x->value, depth) ? 1 : -1;
584     EVP_PKEY_free(pk);
585     }
586   }
587
588 /*
589  * With bare TA public keys, we can't check whether the trust chain is
590  * issued by the key, but we can determine whether it is signed by the
591  * key, so we go with that.
592  *
593  * Ideally, the corresponding certificate was presented in the chain, and we
594  * matched it by its public key digest one level up.  This code is here
595  * to handle adverse conditions imposed by sloppy administrators of
596  * receiving systems with poorly constructed chains.
597  *
598  * We'd like to optimize out keys that should not match when the cert's
599  * authority key id does not match the key id of this key computed via
600  * the RFC keyid algorithm (SHA-1 digest of public key bit-string sans
601  * ASN1 tag and length thus also excluding the unused bits field that is
602  * logically part of the length).  However, some CAs have a non-standard
603  * authority keyid, so we lose.  Too bad.
604  *
605  * This may push errors onto the stack when the certificate signature is
606  * not of the right type or length, throw these away,
607  */
608 for (dane_pkey_list k = dane->pkeys; !done && k; k = k->next)
609   if (X509_verify(cert, k->value) > 0)
610     done = wrap_issuer(dane, k->value, cert, depth, WRAP_MID) ? 1 : -1;
611   else
612     ERR_clear_error();
613
614 return done;
615 }
616
617 static int
618 set_trust_anchor(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
619 {
620 int matched = 0;
621 int depth = 0;
622 EVP_PKEY *takey;
623 X509 *ca;
624 STACK_OF(X509) *in = X509_STORE_CTX_get0_untrusted(ctx);
625
626 if (!grow_chain(dane, UNTRUSTED, 0))
627   return -1;
628
629 /*
630  * Accept a degenerate case: depth 0 self-signed trust-anchor.
631  */
632 if (X509_check_issued(cert, cert) == X509_V_OK)
633   {
634   dane->depth = 0;
635   matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], cert, 0);
636   if (matched > 0 && !grow_chain(dane, TRUSTED, cert))
637     matched = -1;
638   return matched;
639   }
640
641 /* Make a shallow copy of the input untrusted chain. */
642 if (!(in = sk_X509_dup(in)))
643   {
644   DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
645   return -1;
646   }
647
648 /*
649  * At each iteration we consume the issuer of the current cert.  This
650  * reduces the length of the "in" chain by one.  If no issuer is found,
651  * we are done.  We also stop when a certificate matches a TA in the
652  * peer's TLSA RRset.
653  *
654  * Caller ensures that the initial certificate is not self-signed.
655  */
656 for (int n = sk_X509_num(in); n > 0; --n, ++depth)
657   {
658   int i;
659   for (i = 0; i < n; ++i)
660     if (X509_check_issued(sk_X509_value(in, i), cert) == X509_V_OK)
661       break;
662
663   /*
664    * Final untrusted element with no issuer in the peer's chain, it may
665    * however be signed by a pkey or cert obtained via a TLSA RR.
666    */
667   if (i == n)
668     break;
669
670   /* Peer's chain contains an issuer ca. */
671   ca = sk_X509_delete(in, i);
672
673   /* If not a trust anchor, record untrusted ca and continue. */
674   if ((matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], ca,
675                      depth + 1)) == 0)
676     {
677     if (grow_chain(dane, UNTRUSTED, ca))
678       {
679       if (X509_check_issued(ca, ca) != X509_V_OK)
680         {
681         /* Restart with issuer as subject */
682         cert = ca;
683         continue;
684         }
685       /* Final self-signed element, skip ta_signed() check. */
686       cert = 0;
687       }
688     else
689       matched = -1;
690     }
691   else if(matched == MATCHED_CERT)
692     {
693     if(!wrap_cert(dane, ca, depth))
694       matched = -1;
695     }
696   else if(matched == MATCHED_PKEY)
697     {
698     if (  !(takey = X509_get_pubkey(ca))
699        || !wrap_issuer(dane, takey, cert, depth, WRAP_MID))
700       {
701       if (takey)
702         EVP_PKEY_free(takey);
703       else
704         DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
705       matched = -1;
706       }
707     }
708   break;
709   }
710
711 /* Shallow free the duplicated input untrusted chain. */
712 sk_X509_free(in);
713
714 /*
715  * When the loop exits, if "cert" is set, it is not self-signed and has
716  * no issuer in the chain, we check for a possible signature via a DNS
717  * obtained TA cert or public key.
718  */
719 if (matched == 0 && cert)
720   matched = ta_signed(dane, cert, depth);
721
722 return matched;
723 }
724
725 static int
726 check_end_entity(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
727 {
728 int matched;
729
730 matched = match(dane->selectors[DANESSL_USAGE_DANE_EE], cert, 0);
731 if (matched > 0)
732   {
733   dane->mdpth = 0;
734   dane->match = cert;
735   X509_up_ref(cert);
736   if(!X509_STORE_CTX_get0_chain(ctx))
737     {
738     STACK_OF(X509) * sk = sk_X509_new_null();
739     if (sk && sk_X509_push(sk, cert))
740       {
741       X509_up_ref(cert);
742       X509_STORE_CTX_set0_verified_chain(ctx, sk);
743       }
744     else
745       {
746       if (sk) sk_X509_free(sk);
747       DANEerr(DANESSL_F_CHECK_END_ENTITY, ERR_R_MALLOC_FAILURE);
748       return -1;
749       }
750     }
751   }
752 return matched;
753 }
754
755 static int
756 match_name(const char *certid, ssl_dane *dane)
757 {
758 int multi = dane->multi;
759
760 for (dane_host_list hosts = dane->hosts; hosts; hosts = hosts->next)
761   {
762   int match_subdomain = 0;
763   const char *domain = hosts->value;
764   const char *parent;
765   int idlen;
766   int domlen;
767
768   if (*domain == '.' && domain[1] != '\0')
769     {
770     ++domain;
771     match_subdomain = 1;
772     }
773
774   /*
775    * Sub-domain match: certid is any sub-domain of hostname.
776    */
777   if(match_subdomain)
778     {
779     if (  (idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
780        && certid[idlen - domlen - 1] == '.'
781        && !strcasecmp(certid + (idlen - domlen), domain))
782       return 1;
783     else
784       continue;
785     }
786
787   /*
788    * Exact match and initial "*" match. The initial "*" in a certid
789    * matches one (if multi is false) or more hostname components under
790    * the condition that the certid contains multiple hostname components.
791    */
792   if (  !strcasecmp(certid, domain)
793      || (  certid[0] == '*' && certid[1] == '.' && certid[2] != 0
794         && (parent = strchr(domain, '.')) != 0
795         && (idlen = strlen(certid + 1)) <= (domlen = strlen(parent))
796         && strcasecmp(multi ? parent + domlen - idlen : parent, certid+1) == 0))
797     return 1;
798   }
799 return 0;
800 }
801
802 static const char *
803 check_name(const char *name, int len)
804 {
805 const char *cp = name + len;
806
807 while (len > 0 && !*--cp)
808   --len;                          /* Ignore trailing NULs */
809 if (len <= 0)
810   return 0;
811 for (cp = name; *cp; cp++)
812   {
813   char c = *cp;
814   if (!((c >= 'a' && c <= 'z') ||
815         (c >= '0' && c <= '9') ||
816         (c >= 'A' && c <= 'Z') ||
817         (c == '.' || c == '-') ||
818         (c == '*')))
819     return 0;                   /* Only LDH, '.' and '*' */
820   }
821 if (cp - name != len)               /* Guard against internal NULs */
822   return 0;
823 return name;
824 }
825
826 static const char *
827 parse_dns_name(const GENERAL_NAME *gn)
828 {
829 if (gn->type != GEN_DNS)
830   return 0;
831 if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
832   return 0;
833 return check_name(CCS  ASN1_STRING_get0_data(gn->d.ia5),
834                   ASN1_STRING_length(gn->d.ia5));
835 }
836
837 static char *
838 parse_subject_name(X509 *cert)
839 {
840 X509_NAME *name = X509_get_subject_name(cert);
841 X509_NAME_ENTRY *entry;
842 ASN1_STRING *entry_str;
843 unsigned char *namebuf;
844 int nid = NID_commonName;
845 int len;
846 int i;
847
848 if (!name || (i = X509_NAME_get_index_by_NID(name, nid, -1)) < 0)
849   return 0;
850 if (!(entry = X509_NAME_get_entry(name, i)))
851   return 0;
852 if (!(entry_str = X509_NAME_ENTRY_get_data(entry)))
853   return 0;
854
855 if ((len = ASN1_STRING_to_UTF8(&namebuf, entry_str)) < 0)
856   return 0;
857 if (len <= 0 || check_name(CS  namebuf, len) == 0)
858   {
859   OPENSSL_free(namebuf);
860   return 0;
861   }
862 return CS  namebuf;
863 }
864
865 static int
866 name_check(ssl_dane *dane, X509 *cert)
867 {
868 int matched = 0;
869 BOOL got_altname = FALSE;
870 GENERAL_NAMES *gens;
871
872 gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
873 if (gens)
874   {
875   int n = sk_GENERAL_NAME_num(gens);
876
877   for (int i = 0; i < n; ++i)
878     {
879     const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
880     const char *certid;
881
882     if (gn->type != GEN_DNS)
883         continue;
884     got_altname = TRUE;
885     certid = parse_dns_name(gn);
886     if (certid && *certid)
887       {
888       if ((matched = match_name(certid, dane)) == 0)
889         continue;
890       if (!(dane->mhost = OPENSSL_strdup(certid)))
891         matched = -1;
892       DEBUG(D_tls) debug_printf("Dane name_check: matched SAN %s\n", certid);
893       break;
894       }
895     }
896   GENERAL_NAMES_free(gens);
897   }
898
899 /*
900  * XXX: Should the subjectName be skipped when *any* altnames are present,
901  * or only when DNS altnames are present?
902  */
903 if (!got_altname)
904   {
905   char *certid = parse_subject_name(cert);
906   if (certid != 0 && *certid && (matched = match_name(certid, dane)) != 0)
907     {
908     DEBUG(D_tls) debug_printf("Dane name_check: matched SN %s\n", certid);
909     dane->mhost = OPENSSL_strdup(certid);
910     }
911   if (certid)
912     OPENSSL_free(certid);
913   }
914 return matched;
915 }
916
917 static int
918 verify_chain(X509_STORE_CTX *ctx)
919 {
920 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
921 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
922 STACK_OF(X509) * chain = X509_STORE_CTX_get0_chain(ctx);
923 int chain_length = sk_X509_num(chain);
924 int ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
925 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
926 ssl_dane *dane = SSL_get_ex_data(ssl, dane_idx);
927 dane_selector_list issuer_rrs = dane->selectors[DANESSL_USAGE_PKIX_TA];
928 dane_selector_list leaf_rrs = dane->selectors[DANESSL_USAGE_PKIX_EE];
929 int matched = 0;
930
931 DEBUG(D_tls) debug_printf("Dane verify_chain\n");
932
933 /* Restore OpenSSL's internal_verify() as the signature check function */
934 X509_STORE_CTX_set_verify(ctx, dane->verify);
935
936 if ((matched = name_check(dane, cert)) < 0)
937   {
938   X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
939   return 0;
940   }
941
942 if (!matched)
943   {
944   X509_STORE_CTX_set_error_depth(ctx, 0);
945   X509_STORE_CTX_set_current_cert(ctx, cert);
946   X509_STORE_CTX_set_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH);
947   if (!cb(0, ctx))
948     return 0;
949   }
950 matched = 0;
951
952 /*
953  * Satisfy at least one usage 0 or 1 constraint, unless we've already
954  * matched a usage 2 trust anchor.
955  *
956  * XXX: internal_verify() doesn't callback with top certs that are not
957  * self-issued.  This is fixed in OpenSSL 1.1.0.
958  */
959 if (dane->roots && sk_X509_num(dane->roots))
960   {
961   X509 *top = sk_X509_value(chain, dane->depth);
962
963   dane->mdpth = dane->depth;
964   dane->match = top;
965   X509_up_ref(top);
966
967 #if OPENSSL_VERSION_NUMBER < 0x10100000L
968   if (X509_check_issued(top, top) != X509_V_OK)
969     {
970     X509_STORE_CTX_set_error_depth(ctx, dane->depth);
971     X509_STORE_CTX_set_current_cert(ctx, top);
972     if (!cb(1, ctx))
973       return 0;
974     }
975 #endif
976   /* Pop synthetic trust-anchor ancestors off the chain! */
977   while (--chain_length > dane->depth)
978       X509_free(sk_X509_pop(chain));
979   }
980 else
981   {
982   int n = 0;
983   X509 *xn = cert;
984
985   /*
986    * Check for an EE match, then a CA match at depths > 0, and
987    * finally, if the EE cert is self-issued, for a depth 0 CA match.
988    */
989   if (leaf_rrs)
990     matched = match(leaf_rrs, xn, 0);
991   if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched EE\n");
992
993   if (!matched && issuer_rrs)
994     for (n = chain_length-1; !matched && n >= 0; --n)
995       {
996       xn = sk_X509_value(chain, n);
997       if (n > 0 || X509_check_issued(xn, xn) == X509_V_OK)
998         matched = match(issuer_rrs, xn, n);
999       }
1000   if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched %s\n",
1001     n>0 ? "CA" : "selfisssued EE");
1002
1003   if (!matched)
1004     {
1005     X509_STORE_CTX_set_error_depth(ctx, 0);
1006     X509_STORE_CTX_set_current_cert(ctx, cert);
1007     X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_UNTRUSTED);
1008     if (!cb(0, ctx))
1009       return 0;
1010     }
1011   else
1012     {
1013     dane->mdpth = n;
1014     dane->match = xn;
1015     X509_up_ref(xn);
1016     }
1017   }
1018
1019 /* Tail recurse into OpenSSL's internal_verify */
1020 return dane->verify(ctx);
1021 }
1022
1023 static void
1024 dane_reset(ssl_dane *dane)
1025 {
1026 dane->depth = -1;
1027 if (dane->mhost)
1028   {
1029   OPENSSL_free(dane->mhost);
1030   dane->mhost = 0;
1031   }
1032 if (dane->roots)
1033   {
1034   sk_X509_pop_free(dane->roots, X509_free);
1035   dane->roots = 0;
1036   }
1037 if (dane->chain)
1038   {
1039   sk_X509_pop_free(dane->chain, X509_free);
1040   dane->chain = 0;
1041   }
1042 if (dane->match)
1043   {
1044   X509_free(dane->match);
1045   dane->match = 0;
1046   }
1047 dane->mdpth = -1;
1048 }
1049
1050 static int
1051 verify_cert(X509_STORE_CTX *ctx, void *unused_ctx)
1052 {
1053 static int ssl_idx = -1;
1054 SSL *ssl;
1055 ssl_dane *dane;
1056 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
1057 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
1058 int matched;
1059
1060 DEBUG(D_tls) debug_printf("Dane verify_cert\n");
1061
1062 if (ssl_idx < 0)
1063   ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1064 if (dane_idx < 0)
1065   {
1066   DANEerr(DANESSL_F_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
1067   return -1;
1068   }
1069
1070 ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
1071 if (!(dane = SSL_get_ex_data(ssl, dane_idx)) || !cert)
1072   return X509_verify_cert(ctx);
1073
1074 /* Reset for verification of a new chain, perhaps a renegotiation. */
1075 dane_reset(dane);
1076
1077 if (dane->selectors[DANESSL_USAGE_DANE_EE])
1078   {
1079   if ((matched = check_end_entity(ctx, dane, cert)) > 0)
1080     {
1081     X509_STORE_CTX_set_error_depth(ctx, 0);
1082     X509_STORE_CTX_set_current_cert(ctx, cert);
1083     return cb(1, ctx);
1084     }
1085   if (matched < 0)
1086     {
1087     X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1088     return -1;
1089     }
1090   }
1091
1092 if (dane->selectors[DANESSL_USAGE_DANE_TA])
1093   {
1094   if ((matched = set_trust_anchor(ctx, dane, cert)) < 0)
1095     {
1096     X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1097     return -1;
1098     }
1099   if (matched)
1100     {
1101     /*
1102      * Check that setting the untrusted chain updates the expected
1103      * structure member at the expected offset.
1104      */
1105     X509_STORE_CTX_trusted_stack(ctx, dane->roots);
1106     X509_STORE_CTX_set_chain(ctx, dane->chain);
1107     OPENSSL_assert(dane->chain == X509_STORE_CTX_get0_untrusted(ctx));
1108     }
1109   }
1110
1111 /*
1112  * Name checks and usage 0/1 constraint enforcement are delayed until
1113  * X509_verify_cert() builds the full chain and calls our verify_chain()
1114  * wrapper.
1115  */
1116 dane->verify = X509_STORE_CTX_get_verify(ctx);
1117 X509_STORE_CTX_set_verify(ctx, verify_chain);
1118
1119 if (X509_verify_cert(ctx))
1120   return 1;
1121
1122 /*
1123  * If the chain is invalid, clear any matching cert or hostname, to
1124  * protect callers that might erroneously rely on these alone without
1125  * checking the validation status.
1126  */
1127 if (dane->match)
1128   {
1129   X509_free(dane->match);
1130   dane->match = 0;
1131   }
1132 if (dane->mhost)
1133   {
1134   OPENSSL_free(dane->mhost);
1135   dane->mhost = 0;
1136   }
1137  return 0;
1138 }
1139
1140 static dane_list
1141 list_alloc(size_t vsize)
1142 {
1143 void *value = (void *) OPENSSL_malloc(vsize);
1144 dane_list l;
1145
1146 if (!value)
1147   {
1148   DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1149   return 0;
1150   }
1151 if (!(l = (dane_list) OPENSSL_malloc(sizeof(*l))))
1152   {
1153   OPENSSL_free(value);
1154   DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1155   return 0;
1156   }
1157 l->next = 0;
1158 l->value = value;
1159 return l;
1160 }
1161
1162 static void
1163 list_free(void *list, void (*f)(void *))
1164 {
1165 dane_list next;
1166
1167 for (dane_list head = (dane_list) list; head; head = next)
1168   {
1169   next = head->next;
1170   if (f && head->value)
1171       f(head->value);
1172   OPENSSL_free(head);
1173   }
1174 }
1175
1176 static void
1177 ossl_free(void * p)
1178 {
1179 OPENSSL_free(p);
1180 }
1181
1182 static void
1183 dane_mtype_free(void *p)
1184 {
1185 list_free(((dane_mtype) p)->data, ossl_free);
1186 OPENSSL_free(p);
1187 }
1188
1189 static void
1190 dane_selector_free(void *p)
1191 {
1192 list_free(((dane_selector) p)->mtype, dane_mtype_free);
1193 OPENSSL_free(p);
1194 }
1195
1196
1197
1198 /*
1199
1200 Tidy up once the connection is finished with.
1201
1202 Arguments
1203   ssl           The ssl connection handle
1204
1205 => Before calling SSL_free()
1206 tls_close() and tls_getc() [the error path] are the obvious places.
1207 Could we do it earlier - right after verification?  In tls_client_start()
1208 right after SSL_connect() returns, in that case.
1209
1210 */
1211
1212 void
1213 DANESSL_cleanup(SSL *ssl)
1214 {
1215 ssl_dane *dane;
1216
1217 DEBUG(D_tls) debug_printf("Dane lib-cleanup\n");
1218
1219 if (dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1220   return;
1221 (void) SSL_set_ex_data(ssl, dane_idx, 0);
1222
1223 dane_reset(dane);
1224 if (dane->hosts)
1225   list_free(dane->hosts, ossl_free);
1226 for (int u = 0; u <= DANESSL_USAGE_LAST; ++u)
1227   if (dane->selectors[u])
1228     list_free(dane->selectors[u], dane_selector_free);
1229 if (dane->pkeys)
1230   list_free(dane->pkeys, pkey_free);
1231 if (dane->certs)
1232   list_free(dane->certs, cert_free);
1233 OPENSSL_free(dane);
1234 }
1235
1236 static dane_host_list
1237 host_list_init(const char **src)
1238 {
1239 dane_host_list head = NULL;
1240
1241 while (*src)
1242   {
1243   dane_host_list elem = (dane_host_list) OPENSSL_malloc(sizeof(*elem));
1244   if (elem == 0)
1245     {
1246     list_free(head, ossl_free);
1247     return 0;
1248     }
1249   elem->value = OPENSSL_strdup(*src++);
1250   LINSERT(head, elem);
1251   }
1252 return head;
1253 }
1254
1255
1256 int
1257 DANESSL_get_match_cert(SSL *ssl, X509 **match, const char **mhost, int *depth)
1258 {
1259 ssl_dane *dane;
1260
1261 if (dane_idx < 0 || (dane = SSL_get_ex_data(ssl, dane_idx)) == 0)
1262   {
1263   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1264   return -1;
1265   }
1266
1267 if (dane->match)
1268   {
1269   if (match)
1270     *match = dane->match;
1271   if (mhost)
1272     *mhost = dane->mhost;
1273   if (depth)
1274     *depth = dane->mdpth;
1275   }
1276
1277   return (dane->match != 0);
1278 }
1279
1280
1281 #ifdef never_called
1282 int
1283 DANESSL_verify_chain(SSL *ssl, STACK_OF(X509) *chain)
1284 {
1285 int ret;
1286 X509 *cert;
1287 X509_STORE_CTX * store_ctx;
1288 SSL_CTX *ssl_ctx = SSL_get_SSL_CTX(ssl);
1289 X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
1290 int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1291
1292 cert = sk_X509_value(chain, 0);
1293 if (!(store_ctx = X509_STORE_CTX_new()))
1294   {
1295   DANEerr(DANESSL_F_DANESSL_VERIFY_CHAIN, ERR_R_MALLOC_FAILURE);
1296   return 0;
1297   }
1298 if (!X509_STORE_CTX_init(store_ctx, store, cert, chain))
1299   {
1300   X509_STORE_CTX_free(store_ctx);
1301   return 0;
1302   }
1303 X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx, ssl);
1304
1305 X509_STORE_CTX_set_default(store_ctx,
1306             SSL_is_server(ssl) ? "ssl_client" : "ssl_server");
1307 X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
1308             SSL_get0_param(ssl));
1309
1310 if (SSL_get_verify_callback(ssl))
1311   X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
1312
1313 ret = verify_cert(store_ctx, NULL);
1314
1315 SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
1316 X509_STORE_CTX_cleanup(store_ctx);
1317
1318 return (ret);
1319 }
1320 #endif
1321
1322
1323
1324
1325 /*
1326
1327 Call this for each TLSA record found for the target, after the
1328 DANE setup has been done on the ssl connection handle.
1329
1330 Arguments:
1331   ssl           Connection handle
1332   usage         TLSA record field
1333   selector      TLSA record field
1334   mdname        ??? message digest name?
1335   data          ??? TLSA record megalump?
1336   dlen          length of data
1337
1338 Return
1339   -1 on error
1340   0  action not taken
1341   1  record accepted
1342 */
1343
1344 int
1345 DANESSL_add_tlsa(SSL *ssl, uint8_t usage, uint8_t selector, const char *mdname,
1346         unsigned const char *data, size_t dlen)
1347 {
1348 ssl_dane *dane;
1349 dane_selector_list s = 0;
1350 dane_mtype_list m = 0;
1351 dane_data_list d = 0;
1352 dane_cert_list xlist = 0;
1353 dane_pkey_list klist = 0;
1354 const EVP_MD *md = 0;
1355
1356 DEBUG(D_tls) debug_printf("Dane add-tlsa: usage %u sel %u mdname \"%s\"\n",
1357                           usage, selector, mdname);
1358
1359 if(dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1360   {
1361   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1362   return -1;
1363   }
1364
1365 if (usage > DANESSL_USAGE_LAST)
1366   {
1367   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_USAGE);
1368   return 0;
1369   }
1370 if (selector > DANESSL_SELECTOR_LAST)
1371   {
1372   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_SELECTOR);
1373   return 0;
1374   }
1375
1376 /* Support built-in standard one-digit mtypes */
1377 if (mdname && *mdname && mdname[1] == '\0')
1378   switch (*mdname - '0')
1379   {
1380   case DANESSL_MATCHING_FULL: mdname = 0;          break;
1381   case DANESSL_MATCHING_2256: mdname = "sha256"; break;
1382   case DANESSL_MATCHING_2512: mdname = "sha512"; break;
1383   }
1384 if (mdname && *mdname && !(md = EVP_get_digestbyname(mdname)))
1385   {
1386   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DIGEST);
1387   return 0;
1388   }
1389 if (mdname && *mdname && dlen != EVP_MD_size(md))
1390   {
1391   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DATA_LENGTH);
1392   return 0;
1393   }
1394 if (!data)
1395   {
1396   DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_NULL_DATA);
1397   return 0;
1398   }
1399
1400 /*
1401  * Full Certificate or Public Key when NULL or empty digest name
1402  */
1403 if (!mdname || !*mdname)
1404   {
1405   X509 *x = 0;
1406   EVP_PKEY *k = 0;
1407   const unsigned char *p = data;
1408
1409 #define xklistinit(lvar, ltype, var, freeFunc) do { \
1410           (lvar) = (ltype) OPENSSL_malloc(sizeof(*(lvar))); \
1411           if ((lvar) == 0) { \
1412               DANEerr(DANESSL_F_ADD_TLSA, ERR_R_MALLOC_FAILURE); \
1413               freeFunc((var)); \
1414               return 0; \
1415           } \
1416           (lvar)->next = 0; \
1417           lvar->value = var; \
1418       } while (0)
1419 #define xkfreeret(ret) do { \
1420           if (xlist) list_free(xlist, cert_free); \
1421           if (klist) list_free(klist, pkey_free); \
1422           return (ret); \
1423       } while (0)
1424
1425   switch (selector)
1426     {
1427     case DANESSL_SELECTOR_CERT:
1428       if (!d2i_X509(&x, &p, dlen) || dlen != p - data)
1429         {
1430         if (x)
1431           X509_free(x);
1432         DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT);
1433         return 0;
1434         }
1435       k = X509_get_pubkey(x);
1436       EVP_PKEY_free(k);
1437       if (k == 0)
1438         {
1439         X509_free(x);
1440         DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT_PKEY);
1441         return 0;
1442         }
1443       if (usage == DANESSL_USAGE_DANE_TA)
1444         xklistinit(xlist, dane_cert_list, x, X509_free);
1445       break;
1446
1447     case DANESSL_SELECTOR_SPKI:
1448       if (!d2i_PUBKEY(&k, &p, dlen) || dlen != p - data)
1449         {
1450         if (k)
1451           EVP_PKEY_free(k);
1452       DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_PKEY);
1453       return 0;
1454         }
1455       if (usage == DANESSL_USAGE_DANE_TA)
1456         xklistinit(klist, dane_pkey_list, k, EVP_PKEY_free);
1457       break;
1458     }
1459   }
1460
1461 /* Find insertion point and don't add duplicate elements. */
1462 for (s = dane->selectors[usage]; s; s = s->next)
1463   if (s->value->selector == selector)
1464     {
1465     for (m = s->value->mtype; m; m = m->next)
1466       if (m->value->md == md)
1467         {
1468         for (d = m->value->data; d; d = d->next)
1469           if (  d->value->datalen == dlen
1470              && memcmp(d->value->data, data, dlen) == 0)
1471             xkfreeret(1);
1472         break;
1473         }
1474     break;
1475     }
1476
1477 if ((d = (dane_data_list) list_alloc(sizeof(*d->value) + dlen)) == 0)
1478   xkfreeret(0);
1479 d->value->datalen = dlen;
1480 memcpy(d->value->data, data, dlen);
1481 if (!m)
1482   {
1483   if ((m = (dane_mtype_list) list_alloc(sizeof(*m->value))) == 0)
1484     {
1485     list_free(d, ossl_free);
1486     xkfreeret(0);
1487     }
1488   m->value->data = 0;
1489   if ((m->value->md = md) != 0)
1490     m->value->mdlen = dlen;
1491   if (!s)
1492     {
1493     if ((s = (dane_selector_list) list_alloc(sizeof(*s->value))) == 0)
1494       {
1495       list_free(m, dane_mtype_free);
1496       xkfreeret(0);
1497       }
1498     s->value->mtype = 0;
1499     s->value->selector = selector;
1500     LINSERT(dane->selectors[usage], s);
1501     }
1502   LINSERT(s->value->mtype, m);
1503   }
1504 LINSERT(m->value->data, d);
1505
1506 if (xlist)
1507   LINSERT(dane->certs, xlist);
1508 else if (klist)
1509   LINSERT(dane->pkeys, klist);
1510 ++dane->count;
1511 return 1;
1512 }
1513
1514
1515
1516
1517 /*
1518 Call this once we have an ssl connection handle but before
1519 making the TLS connection.
1520
1521 => In tls_client_start() after the call to SSL_new()
1522 and before the call to SSL_connect().  Exactly where
1523 probably does not matter.
1524 We probably want to keep our existing SNI handling;
1525 call this with NULL.
1526
1527 Arguments:
1528   ssl           Connection handle
1529   sni_domain    Optional peer server name
1530   hostnames     list of names to chack against peer cert
1531
1532 Return
1533   -1 on fatal error
1534   0  nonfatal error
1535   1  success
1536 */
1537
1538 int
1539 DANESSL_init(SSL *ssl, const char *sni_domain, const char **hostnames)
1540 {
1541 ssl_dane *dane;
1542
1543 DEBUG(D_tls) debug_printf("Dane ssl_init\n");
1544 if (dane_idx < 0)
1545   {
1546   DANEerr(DANESSL_F_INIT, DANESSL_R_LIBRARY_INIT);
1547   return -1;
1548   }
1549
1550 if (sni_domain && !SSL_set_tlsext_host_name(ssl, sni_domain))
1551   return 0;
1552
1553 if ((dane = (ssl_dane *) OPENSSL_malloc(sizeof(ssl_dane))) == 0)
1554   {
1555   DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1556   return 0;
1557   }
1558 if (!SSL_set_ex_data(ssl, dane_idx, dane))
1559   {
1560   DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1561   OPENSSL_free(dane);
1562   return 0;
1563   }
1564
1565 dane->verify = 0;
1566 dane->hosts = 0;
1567 dane->thost = 0;
1568 dane->pkeys = 0;
1569 dane->certs = 0;
1570 dane->chain = 0;
1571 dane->match = 0;
1572 dane->roots = 0;
1573 dane->depth = -1;
1574 dane->mhost = 0;                        /* Future SSL control interface */
1575 dane->mdpth = 0;                        /* Future SSL control interface */
1576 dane->multi = 0;                        /* Future SSL control interface */
1577 dane->count = 0;
1578 dane->hosts = 0;
1579
1580 for (int i = 0; i <= DANESSL_USAGE_LAST; ++i)
1581   dane->selectors[i] = 0;
1582
1583 if (hostnames && (dane->hosts = host_list_init(hostnames)) == 0)
1584   {
1585   DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1586   DANESSL_cleanup(ssl);
1587   return 0;
1588   }
1589
1590 return 1;
1591 }
1592
1593
1594 /*
1595
1596 Call this once we have a context to work with, but
1597 before DANESSL_init()
1598
1599 => in tls_client_start(), after tls_init() call gives us the ctx,
1600 if we decide we want to (policy) and can (TLSA records available)
1601 replacing (? what about fallback) everything from testing tls_verify_hosts
1602 down to just before calling SSL_new() for the conn handle.
1603
1604 Arguments
1605   ctx           SSL context
1606
1607 Return
1608   -1    Error
1609   1     Success
1610 */
1611
1612 int
1613 DANESSL_CTX_init(SSL_CTX *ctx)
1614 {
1615 DEBUG(D_tls) debug_printf("Dane ctx-init\n");
1616 if (dane_idx >= 0)
1617   {
1618   SSL_CTX_set_cert_verify_callback(ctx, verify_cert, 0);
1619   return 1;
1620   }
1621 DANEerr(DANESSL_F_CTX_INIT, DANESSL_R_LIBRARY_INIT);
1622 return -1;
1623 }
1624
1625 static void
1626 dane_init(void)
1627 {
1628 /*
1629  * Store library id in zeroth function slot, used to locate the library
1630  * name.  This must be done before we load the error strings.
1631  */
1632 err_lib_dane = ERR_get_next_error_library();
1633
1634 #ifndef OPENSSL_NO_ERR
1635 if (err_lib_dane > 0)
1636   {
1637   dane_str_functs[0].error |= ERR_PACK(err_lib_dane, 0, 0);
1638   ERR_load_strings(err_lib_dane, dane_str_functs);
1639   ERR_load_strings(err_lib_dane, dane_str_reasons);
1640   }
1641 #endif
1642
1643 /*
1644  * Register SHA-2 digests, if implemented and not already registered.
1645  */
1646 #if defined(LN_sha256) && defined(NID_sha256) && !defined(OPENSSL_NO_SHA256)
1647 if (!EVP_get_digestbyname(LN_sha224)) EVP_add_digest(EVP_sha224());
1648 if (!EVP_get_digestbyname(LN_sha256)) EVP_add_digest(EVP_sha256());
1649 #endif
1650 #if defined(LN_sha512) && defined(NID_sha512) && !defined(OPENSSL_NO_SHA512)
1651 if (!EVP_get_digestbyname(LN_sha384)) EVP_add_digest(EVP_sha384());
1652 if (!EVP_get_digestbyname(LN_sha512)) EVP_add_digest(EVP_sha512());
1653 #endif
1654
1655 /*
1656  * Register an SSL index for the connection-specific ssl_dane structure.
1657  * Using a separate index makes it possible to add DANE support to
1658  * existing OpenSSL releases that don't have a suitable pointer in the
1659  * SSL structure.
1660  */
1661 dane_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
1662 }
1663
1664
1665 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1666 static void
1667 run_once(volatile int * once, void (*init)(void))
1668 {
1669 int wlock = 0;
1670
1671 CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
1672 if (!*once)
1673   {
1674   CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1675   CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1676   wlock = 1;
1677   if (!*once)
1678     {
1679     *once = 1;
1680     init();
1681     }
1682   }
1683 if (wlock)
1684   CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1685 else
1686   CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1687 }
1688 #endif
1689
1690
1691
1692 /*
1693
1694 Call this once.  Probably early in startup will do; may need
1695 to be after SSL library init.
1696
1697 => put after call to tls_init() for now
1698
1699 Return
1700   1     Success
1701   0     Fail
1702 */
1703
1704 int
1705 DANESSL_library_init(void)
1706 {
1707 static CRYPTO_ONCE once = CRYPTO_ONCE_STATIC_INIT;
1708
1709 DEBUG(D_tls) debug_printf("Dane lib-init\n");
1710 (void) CRYPTO_THREAD_run_once(&once, dane_init);
1711
1712 #if defined(LN_sha256)
1713 /* No DANE without SHA256 support */
1714 if (dane_idx >= 0 && EVP_get_digestbyname(LN_sha256) != 0)
1715   return 1;
1716 #endif
1717 DANEerr(DANESSL_F_LIBRARY_INIT, DANESSL_R_SUPPORT);
1718 return 0;
1719 }
1720
1721
1722 /* vi: aw ai sw=2
1723 */