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