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