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