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