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