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