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