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