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