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