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