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