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