2 * Author: Viktor Dukhovni
3 * License: THIS CODE IS IN THE PUBLIC DOMAIN.
5 * Copyright (c) The Exim Maintainers 2014 - 2016
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>
19 #include <openssl/bn.h>
21 #if OPENSSL_VERSION_NUMBER < 0x1000000fL
22 # error "OpenSSL 1.0.0 or higher required"
25 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
26 # define X509_up_ref(x) CRYPTO_add(&((x)->references), 1, CRYPTO_LOCK_X509)
28 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
29 # define EXIM_HAVE_ASN1_MACROS
30 # define EXIM_OPAQUE_X509
32 # define X509_STORE_CTX_get_verify(ctx) (ctx)->verify
33 # define X509_STORE_CTX_get_verify_cb(ctx) (ctx)->verify_cb
34 # define X509_STORE_CTX_get0_cert(ctx) (ctx)->cert
35 # define X509_STORE_CTX_get0_chain(ctx) (ctx)->chain
36 # define X509_STORE_CTX_get0_untrusted(ctx) (ctx)->untrusted
38 # define X509_STORE_CTX_set_verify(ctx, verify_chain) (ctx)->verify = (verify_chain)
39 # define X509_STORE_CTX_set0_verified_chain(ctx, sk) (ctx)->chain = (sk)
40 # define X509_STORE_CTX_set_error_depth(ctx, val) (ctx)->error_depth = (val)
41 # define X509_STORE_CTX_set_current_cert(ctx, cert) (ctx)->current_cert = (cert)
43 # define ASN1_STRING_get0_data ASN1_STRING_data
44 # define X509_getm_notBefore X509_get_notBefore
45 # define X509_getm_notAfter X509_get_notAfter
47 # define CRYPTO_ONCE_STATIC_INIT 0
48 # define CRYPTO_THREAD_run_once run_once
49 typedef int CRYPTO_ONCE;
55 #define DANESSL_F_ADD_SKID 100
56 #define DANESSL_F_ADD_TLSA 101
57 #define DANESSL_F_CHECK_END_ENTITY 102
58 #define DANESSL_F_CTX_INIT 103
59 #define DANESSL_F_GROW_CHAIN 104
60 #define DANESSL_F_INIT 105
61 #define DANESSL_F_LIBRARY_INIT 106
62 #define DANESSL_F_LIST_ALLOC 107
63 #define DANESSL_F_MATCH 108
64 #define DANESSL_F_PUSH_EXT 109
65 #define DANESSL_F_SET_TRUST_ANCHOR 110
66 #define DANESSL_F_VERIFY_CERT 111
67 #define DANESSL_F_WRAP_CERT 112
68 #define DANESSL_F_DANESSL_VERIFY_CHAIN 113
70 #define DANESSL_R_BAD_CERT 100
71 #define DANESSL_R_BAD_CERT_PKEY 101
72 #define DANESSL_R_BAD_DATA_LENGTH 102
73 #define DANESSL_R_BAD_DIGEST 103
74 #define DANESSL_R_BAD_NULL_DATA 104
75 #define DANESSL_R_BAD_PKEY 105
76 #define DANESSL_R_BAD_SELECTOR 106
77 #define DANESSL_R_BAD_USAGE 107
78 #define DANESSL_R_INIT 108
79 #define DANESSL_R_LIBRARY_INIT 109
80 #define DANESSL_R_NOSIGN_KEY 110
81 #define DANESSL_R_SCTX_INIT 111
82 #define DANESSL_R_SUPPORT 112
84 #ifndef OPENSSL_NO_ERR
85 #define DANESSL_F_PLACEHOLDER 0 /* FIRST! Value TBD */
86 static ERR_STRING_DATA dane_str_functs[] = {
87 {DANESSL_F_PLACEHOLDER, "DANE library"}, /* FIRST!!! */
88 {DANESSL_F_ADD_SKID, "add_skid"},
89 {DANESSL_F_ADD_TLSA, "DANESSL_add_tlsa"},
90 {DANESSL_F_CHECK_END_ENTITY, "check_end_entity"},
91 {DANESSL_F_CTX_INIT, "DANESSL_CTX_init"},
92 {DANESSL_F_GROW_CHAIN, "grow_chain"},
93 {DANESSL_F_INIT, "DANESSL_init"},
94 {DANESSL_F_LIBRARY_INIT, "DANESSL_library_init"},
95 {DANESSL_F_LIST_ALLOC, "list_alloc"},
96 {DANESSL_F_MATCH, "match"},
97 {DANESSL_F_PUSH_EXT, "push_ext"},
98 {DANESSL_F_SET_TRUST_ANCHOR, "set_trust_anchor"},
99 {DANESSL_F_VERIFY_CERT, "verify_cert"},
100 {DANESSL_F_WRAP_CERT, "wrap_cert"},
103 static ERR_STRING_DATA dane_str_reasons[] = {
104 {DANESSL_R_BAD_CERT, "Bad TLSA record certificate"},
105 {DANESSL_R_BAD_CERT_PKEY, "Bad TLSA record certificate public key"},
106 {DANESSL_R_BAD_DATA_LENGTH, "Bad TLSA record digest length"},
107 {DANESSL_R_BAD_DIGEST, "Bad TLSA record digest"},
108 {DANESSL_R_BAD_NULL_DATA, "Bad TLSA record null data"},
109 {DANESSL_R_BAD_PKEY, "Bad TLSA record public key"},
110 {DANESSL_R_BAD_SELECTOR, "Bad TLSA record selector"},
111 {DANESSL_R_BAD_USAGE, "Bad TLSA record usage"},
112 {DANESSL_R_INIT, "DANESSL_init() required"},
113 {DANESSL_R_LIBRARY_INIT, "DANESSL_library_init() required"},
114 {DANESSL_R_NOSIGN_KEY, "Certificate usage 2 requires EC support"},
115 {DANESSL_R_SCTX_INIT, "DANESSL_CTX_init() required"},
116 {DANESSL_R_SUPPORT, "DANE library features not supported"},
121 #define DANEerr(f, r) ERR_PUT_error(err_lib_dane, (f), (r), __FILE__, __LINE__)
123 static int err_lib_dane = -1;
124 static int dane_idx = -1;
126 #ifdef X509_V_FLAG_PARTIAL_CHAIN /* OpenSSL >= 1.0.2 */
127 static int wrap_to_root = 0;
129 static int wrap_to_root = 1;
132 static void (*cert_free)(void *) = (void (*)(void *)) X509_free;
133 static void (*pkey_free)(void *) = (void (*)(void *)) EVP_PKEY_free;
135 typedef struct dane_list
137 struct dane_list *next;
141 #define LINSERT(h, e) do { (e)->next = (h); (h) = (e); } while (0)
143 typedef struct dane_host_list
145 struct dane_host_list *next;
149 typedef struct dane_data
152 unsigned char data[0];
155 typedef struct dane_data_list
157 struct dane_data_list *next;
161 typedef struct dane_mtype
168 typedef struct dane_mtype_list
170 struct dane_mtype_list *next;
174 typedef struct dane_selector
177 dane_mtype_list mtype;
180 typedef struct dane_selector_list
182 struct dane_selector_list *next;
184 } *dane_selector_list;
186 typedef struct dane_pkey_list
188 struct dane_pkey_list *next;
192 typedef struct dane_cert_list
194 struct dane_cert_list *next;
198 typedef struct ssl_dane
200 int (*verify)(X509_STORE_CTX *);
201 STACK_OF(X509) *roots;
202 STACK_OF(X509) *chain;
203 X509 *match; /* Matched cert */
204 const char *thost; /* TLSA base domain */
205 char *mhost; /* Matched peer name */
206 dane_pkey_list pkeys;
207 dane_cert_list certs;
208 dane_host_list hosts;
209 dane_selector_list selectors[DANESSL_USAGE_LAST + 1];
211 int mdpth; /* Depth of matched cert */
212 int multi; /* Multi-label wildcards? */
213 int count; /* Number of TLSA records */
216 #ifndef X509_V_ERR_HOSTNAME_MISMATCH
217 # define X509_V_ERR_HOSTNAME_MISMATCH X509_V_ERR_APPLICATION_VERIFICATION
223 match(dane_selector_list slist, X509 *cert, int depth)
228 * Note, set_trust_anchor() needs to know whether the match was for a
229 * pkey digest or a certificate digest. We return MATCHED_PKEY or
230 * MATCHED_CERT accordingly.
232 #define MATCHED_CERT (DANESSL_SELECTOR_CERT + 1)
233 #define MATCHED_PKEY (DANESSL_SELECTOR_SPKI + 1)
236 * Loop over each selector, mtype, and associated data element looking
239 for (matched = 0; !matched && slist; slist = slist->next)
242 unsigned char mdbuf[EVP_MAX_MD_SIZE];
243 unsigned char *buf = NULL;
245 unsigned int len = 0;
248 * Extract ASN.1 DER form of certificate or public key.
250 switch(slist->value->selector)
252 case DANESSL_SELECTOR_CERT:
253 len = i2d_X509(cert, NULL);
254 buf2 = buf = (unsigned char *) OPENSSL_malloc(len);
255 if(buf) i2d_X509(cert, &buf2);
257 case DANESSL_SELECTOR_SPKI:
258 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
259 buf2 = buf = (unsigned char *) OPENSSL_malloc(len);
260 if(buf) i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf2);
266 DANEerr(DANESSL_F_MATCH, ERR_R_MALLOC_FAILURE);
269 OPENSSL_assert(buf2 - buf == len);
272 * Loop over each mtype and data element
274 for (m = slist->value->mtype; !matched && m; m = m->next)
277 unsigned char *cmpbuf = buf;
278 unsigned int cmplen = len;
281 * If it is a digest, compute the corresponding digest of the
282 * DER data for comparison, otherwise, use the full object.
287 if (!EVP_Digest(buf, len, cmpbuf, &cmplen, m->value->md, 0))
290 for (d = m->value->data; !matched && d; d = d->next)
291 if ( cmplen == d->value->datalen
292 && memcmp(cmpbuf, d->value->data, cmplen) == 0)
293 matched = slist->value->selector + 1;
303 push_ext(X509 *cert, X509_EXTENSION *ext)
307 if (X509_add_ext(cert, ext, -1))
309 X509_EXTENSION_free(ext);
311 DANEerr(DANESSL_F_PUSH_EXT, ERR_R_MALLOC_FAILURE);
316 add_ext(X509 *issuer, X509 *subject, int ext_nid, char *ext_val)
320 X509V3_set_ctx(&v3ctx, issuer, subject, 0, 0, 0);
321 return push_ext(subject, X509V3_EXT_conf_nid(0, &v3ctx, ext_nid, ext_val));
325 set_serial(X509 *cert, AUTHORITY_KEYID *akid, X509 *subject)
330 if (akid && akid->serial)
331 return (X509_set_serialNumber(cert, akid->serial));
334 * Add one to subject's serial to avoid collisions between TA serial and
335 * serial of signing root.
337 if ( (bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(subject), 0)) != 0
338 && BN_add_word(bn, 1)
339 && BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert)))
348 add_akid(X509 *cert, AUTHORITY_KEYID *akid)
350 int nid = NID_authority_key_identifier;
351 ASN1_OCTET_STRING *id;
356 * 0 will never be our subject keyid from a SHA-1 hash, but it could be
357 * our subject keyid if forced from child's akid. If so, set our
358 * authority keyid to 1. This way we are never self-signed, and thus
359 * exempt from any potential (off by default for now in OpenSSL)
360 * self-signature checks!
362 id = akid && akid->keyid ? akid->keyid : 0;
363 if (id && ASN1_STRING_length(id) == 1 && *ASN1_STRING_get0_data(id) == c)
366 if ( (akid = AUTHORITY_KEYID_new()) != 0
367 && (akid->keyid = ASN1_OCTET_STRING_new()) != 0
368 #ifdef EXIM_HAVE_ASN1_MACROS
369 && ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
371 && M_ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
373 && X509_add1_ext_i2d(cert, nid, akid, 0, X509V3_ADD_APPEND))
376 AUTHORITY_KEYID_free(akid);
381 add_skid(X509 *cert, AUTHORITY_KEYID *akid)
383 int nid = NID_subject_key_identifier;
385 if (!akid || !akid->keyid)
386 return add_ext(0, cert, nid, "hash");
387 return X509_add1_ext_i2d(cert, nid, akid->keyid, 0, X509V3_ADD_APPEND) > 0;
391 akid_issuer_name(AUTHORITY_KEYID *akid)
393 if (akid && akid->issuer)
396 GENERAL_NAMES *gens = akid->issuer;
398 for (i = 0; i < sk_GENERAL_NAME_num(gens); ++i)
400 GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
402 if (gn->type == GEN_DIRNAME)
410 set_issuer_name(X509 *cert, AUTHORITY_KEYID *akid)
412 X509_NAME *name = akid_issuer_name(akid);
415 * If subject's akid specifies an authority key identifer issuer name, we
418 return X509_set_issuer_name(cert,
419 name ? name : X509_get_subject_name(cert));
423 grow_chain(ssl_dane *dane, int trusted, X509 *cert)
425 STACK_OF(X509) **xs = trusted ? &dane->roots : &dane->chain;
426 static ASN1_OBJECT *serverAuth = 0;
431 if ( trusted && !serverAuth
432 && !(serverAuth = OBJ_nid2obj(NID_server_auth)))
434 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
437 if (!*xs && !(*xs = sk_X509_new_null()))
439 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
445 if (trusted && !X509_add1_trust_object(cert, serverAuth))
447 #ifdef EXIM_OPAQUE_X509
450 CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
452 if (!sk_X509_push(*xs, cert))
455 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
463 wrap_issuer(ssl_dane *dane, EVP_PKEY *key, X509 *subject, int depth, int top)
467 AUTHORITY_KEYID *akid;
468 X509_NAME *name = X509_get_issuer_name(subject);
469 EVP_PKEY *newkey = key ? key : X509_get_pubkey(subject);
471 #define WRAP_MID 0 /* Ensure intermediate. */
472 #define WRAP_TOP 1 /* Ensure self-signed. */
474 if (!name || !newkey || !(cert = X509_new()))
478 * Record the depth of the trust-anchor certificate.
481 dane->depth = depth + 1;
484 * XXX: Uncaught error condition:
486 * The return value is NULL both when the extension is missing, and when
487 * OpenSSL rans out of memory while parsing the extension.
490 akid = X509_get_ext_d2i(subject, NID_authority_key_identifier, 0, 0);
491 /* XXX: Should we peek at the error stack here??? */
494 * If top is true generate a self-issued root CA, otherwise an
495 * intermediate CA and possibly its self-signed issuer.
497 * CA cert valid for +/- 30 days
499 if ( !X509_set_version(cert, 2)
500 || !set_serial(cert, akid, subject)
501 || !set_issuer_name(cert, akid)
502 || !X509_gmtime_adj(X509_getm_notBefore(cert), -30 * 86400L)
503 || !X509_gmtime_adj(X509_getm_notAfter(cert), 30 * 86400L)
504 || !X509_set_subject_name(cert, name)
505 || !X509_set_pubkey(cert, newkey)
506 || !add_ext(0, cert, NID_basic_constraints, "CA:TRUE")
507 || (!top && !add_akid(cert, akid))
508 || !add_skid(cert, akid)
509 || ( !top && wrap_to_root
510 && !wrap_issuer(dane, newkey, cert, depth, WRAP_TOP)))
514 AUTHORITY_KEYID_free(akid);
516 EVP_PKEY_free(newkey);
518 ret = grow_chain(dane, !top && wrap_to_root ? UNTRUSTED : TRUSTED, cert);
525 wrap_cert(ssl_dane *dane, X509 *tacert, int depth)
528 dane->depth = depth + 1;
531 * If the TA certificate is self-issued, or need not be, use it directly.
532 * Otherwise, synthesize requisite ancestors.
535 || X509_check_issued(tacert, tacert) == X509_V_OK)
536 return grow_chain(dane, TRUSTED, tacert);
538 if (wrap_issuer(dane, 0, tacert, depth, WRAP_MID))
539 return grow_chain(dane, UNTRUSTED, tacert);
544 ta_signed(ssl_dane *dane, X509 *cert, int depth)
552 * First check whether issued and signed by a TA cert, this is cheaper
553 * than the bare-public key checks below, since we can determine whether
554 * the candidate TA certificate issued the certificate to be checked
555 * first (name comparisons), before we bother with signature checks
556 * (public key operations).
558 for (x = dane->certs; !done && x; x = x->next)
560 if (X509_check_issued(x->value, cert) == X509_V_OK)
562 if (!(pk = X509_get_pubkey(x->value)))
565 * The cert originally contained a valid pkey, which does
566 * not just vanish, so this is most likely a memory error.
571 /* Check signature, since some other TA may work if not this. */
572 if (X509_verify(cert, pk) > 0)
573 done = wrap_cert(dane, x->value, depth) ? 1 : -1;
579 * With bare TA public keys, we can't check whether the trust chain is
580 * issued by the key, but we can determine whether it is signed by the
581 * key, so we go with that.
583 * Ideally, the corresponding certificate was presented in the chain, and we
584 * matched it by its public key digest one level up. This code is here
585 * to handle adverse conditions imposed by sloppy administrators of
586 * receiving systems with poorly constructed chains.
588 * We'd like to optimize out keys that should not match when the cert's
589 * authority key id does not match the key id of this key computed via
590 * the RFC keyid algorithm (SHA-1 digest of public key bit-string sans
591 * ASN1 tag and length thus also excluding the unused bits field that is
592 * logically part of the length). However, some CAs have a non-standard
593 * authority keyid, so we lose. Too bad.
595 * This may push errors onto the stack when the certificate signature is
596 * not of the right type or length, throw these away,
598 for (k = dane->pkeys; !done && k; k = k->next)
599 if (X509_verify(cert, k->value) > 0)
600 done = wrap_issuer(dane, k->value, cert, depth, WRAP_MID) ? 1 : -1;
608 set_trust_anchor(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
616 STACK_OF(X509) *in = X509_STORE_CTX_get0_untrusted(ctx);
618 if (!grow_chain(dane, UNTRUSTED, 0))
622 * Accept a degenerate case: depth 0 self-signed trust-anchor.
624 if (X509_check_issued(cert, cert) == X509_V_OK)
627 matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], cert, 0);
628 if (matched > 0 && !grow_chain(dane, TRUSTED, cert))
633 /* Make a shallow copy of the input untrusted chain. */
634 if (!(in = sk_X509_dup(in)))
636 DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
641 * At each iteration we consume the issuer of the current cert. This
642 * reduces the length of the "in" chain by one. If no issuer is found,
643 * we are done. We also stop when a certificate matches a TA in the
646 * Caller ensures that the initial certificate is not self-signed.
648 for (n = sk_X509_num(in); n > 0; --n, ++depth)
650 for (i = 0; i < n; ++i)
651 if (X509_check_issued(sk_X509_value(in, i), cert) == X509_V_OK)
655 * Final untrusted element with no issuer in the peer's chain, it may
656 * however be signed by a pkey or cert obtained via a TLSA RR.
661 /* Peer's chain contains an issuer ca. */
662 ca = sk_X509_delete(in, i);
664 /* If not a trust anchor, record untrusted ca and continue. */
665 if ((matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], ca,
668 if (grow_chain(dane, UNTRUSTED, ca))
670 if (!X509_check_issued(ca, ca) == X509_V_OK)
672 /* Restart with issuer as subject */
676 /* Final self-signed element, skip ta_signed() check. */
682 else if(matched == MATCHED_CERT)
684 if(!wrap_cert(dane, ca, depth))
687 else if(matched == MATCHED_PKEY)
689 if ( !(takey = X509_get_pubkey(ca))
690 || !wrap_issuer(dane, takey, cert, depth, WRAP_MID))
693 EVP_PKEY_free(takey);
695 DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
702 /* Shallow free the duplicated input untrusted chain. */
706 * When the loop exits, if "cert" is set, it is not self-signed and has
707 * no issuer in the chain, we check for a possible signature via a DNS
708 * obtained TA cert or public key.
710 if (matched == 0 && cert)
711 matched = ta_signed(dane, cert, depth);
717 check_end_entity(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
721 matched = match(dane->selectors[DANESSL_USAGE_DANE_EE], cert, 0);
727 if(!X509_STORE_CTX_get0_chain(ctx))
729 STACK_OF(X509) * sk = sk_X509_new_null();
730 if (sk && sk_X509_push(sk, cert))
733 X509_STORE_CTX_set0_verified_chain(ctx, sk);
737 if (sk) sk_X509_free(sk);
738 DANEerr(DANESSL_F_CHECK_END_ENTITY, ERR_R_MALLOC_FAILURE);
747 match_name(const char *certid, ssl_dane *dane)
749 int multi = dane->multi;
750 dane_host_list hosts;
752 for (hosts = dane->hosts; hosts; hosts = hosts->next)
754 int match_subdomain = 0;
755 const char *domain = hosts->value;
760 if (*domain == '.' && domain[1] != '\0')
767 * Sub-domain match: certid is any sub-domain of hostname.
771 if ( (idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
772 && certid[idlen - domlen - 1] == '.'
773 && !strcasecmp(certid + (idlen - domlen), domain))
780 * Exact match and initial "*" match. The initial "*" in a certid
781 * matches one (if multi is false) or more hostname components under
782 * the condition that the certid contains multiple hostname components.
784 if ( !strcasecmp(certid, domain)
785 || ( certid[0] == '*' && certid[1] == '.' && certid[2] != 0
786 && (parent = strchr(domain, '.')) != 0
787 && (idlen = strlen(certid + 1)) <= (domlen = strlen(parent))
788 && strcasecmp(multi ? parent + domlen - idlen : parent, certid+1) == 0))
795 check_name(const char *name, int len)
797 const char *cp = name + len;
799 while (len > 0 && !*--cp)
800 --len; /* Ignore trailing NULs */
803 for (cp = name; *cp; cp++)
806 if (!((c >= 'a' && c <= 'z') ||
807 (c >= '0' && c <= '9') ||
808 (c >= 'A' && c <= 'Z') ||
809 (c == '.' || c == '-') ||
811 return 0; /* Only LDH, '.' and '*' */
813 if (cp - name != len) /* Guard against internal NULs */
819 parse_dns_name(const GENERAL_NAME *gn)
821 if (gn->type != GEN_DNS)
823 if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
825 return check_name((const char *) ASN1_STRING_get0_data(gn->d.ia5),
826 ASN1_STRING_length(gn->d.ia5));
830 parse_subject_name(X509 *cert)
832 X509_NAME *name = X509_get_subject_name(cert);
833 X509_NAME_ENTRY *entry;
834 ASN1_STRING *entry_str;
835 unsigned char *namebuf;
836 int nid = NID_commonName;
840 if (!name || (i = X509_NAME_get_index_by_NID(name, nid, -1)) < 0)
842 if (!(entry = X509_NAME_get_entry(name, i)))
844 if (!(entry_str = X509_NAME_ENTRY_get_data(entry)))
847 if ((len = ASN1_STRING_to_UTF8(&namebuf, entry_str)) < 0)
849 if (len <= 0 || check_name((char *) namebuf, len) == 0)
851 OPENSSL_free(namebuf);
854 return (char *) namebuf;
858 name_check(ssl_dane *dane, X509 *cert)
861 BOOL got_altname = FALSE;
864 gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
867 int n = sk_GENERAL_NAME_num(gens);
870 for (i = 0; i < n; ++i)
872 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
875 if (gn->type != GEN_DNS)
878 certid = parse_dns_name(gn);
879 if (certid && *certid)
881 if ((matched = match_name(certid, dane)) == 0)
883 if (!(dane->mhost = OPENSSL_strdup(certid)))
885 DEBUG(D_tls) debug_printf("Dane name_check: matched SAN %s\n", certid);
889 GENERAL_NAMES_free(gens);
893 * XXX: Should the subjectName be skipped when *any* altnames are present,
894 * or only when DNS altnames are present?
898 char *certid = parse_subject_name(cert);
899 if (certid != 0 && *certid && (matched = match_name(certid, dane)) != 0)
901 DEBUG(D_tls) debug_printf("Dane name_check: matched SN %s\n", certid);
902 dane->mhost = OPENSSL_strdup(certid);
905 OPENSSL_free(certid);
911 verify_chain(X509_STORE_CTX *ctx)
913 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
914 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
915 STACK_OF(X509) * chain = X509_STORE_CTX_get0_chain(ctx);
916 int chain_length = sk_X509_num(chain);
917 int ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
918 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
919 ssl_dane *dane = SSL_get_ex_data(ssl, dane_idx);
920 dane_selector_list issuer_rrs = dane->selectors[DANESSL_USAGE_PKIX_TA];
921 dane_selector_list leaf_rrs = dane->selectors[DANESSL_USAGE_PKIX_EE];
924 DEBUG(D_tls) debug_printf("Dane verify_chain\n");
926 /* Restore OpenSSL's internal_verify() as the signature check function */
927 X509_STORE_CTX_set_verify(ctx, dane->verify);
929 if ((matched = name_check(dane, cert)) < 0)
931 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
937 X509_STORE_CTX_set_error_depth(ctx, 0);
938 X509_STORE_CTX_set_current_cert(ctx, cert);
939 X509_STORE_CTX_set_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH);
946 * Satisfy at least one usage 0 or 1 constraint, unless we've already
947 * matched a usage 2 trust anchor.
949 * XXX: internal_verify() doesn't callback with top certs that are not
950 * self-issued. This is fixed in OpenSSL 1.1.0.
952 if (dane->roots && sk_X509_num(dane->roots))
954 X509 *top = sk_X509_value(chain, dane->depth);
956 dane->mdpth = dane->depth;
960 #if OPENSSL_VERSION_NUMBER < 0x10100000L
961 if (X509_check_issued(top, top) != X509_V_OK)
963 X509_STORE_CTX_set_error_depth(ctx, dane->depth);
964 X509_STORE_CTX_set_current_cert(ctx, top);
969 /* Pop synthetic trust-anchor ancestors off the chain! */
970 while (--chain_length > dane->depth)
971 X509_free(sk_X509_pop(chain));
979 * Check for an EE match, then a CA match at depths > 0, and
980 * finally, if the EE cert is self-issued, for a depth 0 CA match.
983 matched = match(leaf_rrs, xn, 0);
984 if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched EE\n");
986 if (!matched && issuer_rrs)
987 for (n = chain_length-1; !matched && n >= 0; --n)
989 xn = sk_X509_value(chain, n);
990 if (n > 0 || X509_check_issued(xn, xn) == X509_V_OK)
991 matched = match(issuer_rrs, xn, n);
993 if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched %s\n",
994 n>0 ? "CA" : "selfisssued EE");
998 X509_STORE_CTX_set_error_depth(ctx, 0);
999 X509_STORE_CTX_set_current_cert(ctx, cert);
1000 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_UNTRUSTED);
1012 /* Tail recurse into OpenSSL's internal_verify */
1013 return dane->verify(ctx);
1017 dane_reset(ssl_dane *dane)
1022 OPENSSL_free(dane->mhost);
1027 sk_X509_pop_free(dane->roots, X509_free);
1032 sk_X509_pop_free(dane->chain, X509_free);
1037 X509_free(dane->match);
1044 verify_cert(X509_STORE_CTX *ctx, void *unused_ctx)
1046 static int ssl_idx = -1;
1049 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
1050 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
1053 DEBUG(D_tls) debug_printf("Dane verify_cert\n");
1056 ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1059 DANEerr(DANESSL_F_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
1063 ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
1064 if (!(dane = SSL_get_ex_data(ssl, dane_idx)) || !cert)
1065 return X509_verify_cert(ctx);
1067 /* Reset for verification of a new chain, perhaps a renegotiation. */
1070 if (dane->selectors[DANESSL_USAGE_DANE_EE])
1072 if ((matched = check_end_entity(ctx, dane, cert)) > 0)
1074 X509_STORE_CTX_set_error_depth(ctx, 0);
1075 X509_STORE_CTX_set_current_cert(ctx, cert);
1080 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1085 if (dane->selectors[DANESSL_USAGE_DANE_TA])
1087 if ((matched = set_trust_anchor(ctx, dane, cert)) < 0)
1089 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1095 * Check that setting the untrusted chain updates the expected
1096 * structure member at the expected offset.
1098 X509_STORE_CTX_trusted_stack(ctx, dane->roots);
1099 X509_STORE_CTX_set_chain(ctx, dane->chain);
1100 OPENSSL_assert(dane->chain == X509_STORE_CTX_get0_untrusted(ctx));
1105 * Name checks and usage 0/1 constraint enforcement are delayed until
1106 * X509_verify_cert() builds the full chain and calls our verify_chain()
1109 dane->verify = X509_STORE_CTX_get_verify(ctx);
1110 X509_STORE_CTX_set_verify(ctx, verify_chain);
1112 if (X509_verify_cert(ctx))
1116 * If the chain is invalid, clear any matching cert or hostname, to
1117 * protect callers that might erroneously rely on these alone without
1118 * checking the validation status.
1122 X509_free(dane->match);
1127 OPENSSL_free(dane->mhost);
1134 list_alloc(size_t vsize)
1136 void *value = (void *) OPENSSL_malloc(vsize);
1141 DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1144 if (!(l = (dane_list) OPENSSL_malloc(sizeof(*l))))
1146 OPENSSL_free(value);
1147 DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1156 list_free(void *list, void (*f)(void *))
1161 for (head = (dane_list) list; head; head = next)
1164 if (f && head->value)
1177 dane_mtype_free(void *p)
1179 list_free(((dane_mtype) p)->data, ossl_free);
1184 dane_selector_free(void *p)
1186 list_free(((dane_selector) p)->mtype, dane_mtype_free);
1194 Tidy up once the connection is finished with.
1197 ssl The ssl connection handle
1199 => Before calling SSL_free()
1200 tls_close() and tls_getc() [the error path] are the obvious places.
1201 Could we do it earlier - right after verification? In tls_client_start()
1202 right after SSL_connect() returns, in that case.
1207 DANESSL_cleanup(SSL *ssl)
1212 DEBUG(D_tls) debug_printf("Dane lib-cleanup\n");
1214 if (dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1216 (void) SSL_set_ex_data(ssl, dane_idx, 0);
1220 list_free(dane->hosts, ossl_free);
1221 for (u = 0; u <= DANESSL_USAGE_LAST; ++u)
1222 if (dane->selectors[u])
1223 list_free(dane->selectors[u], dane_selector_free);
1225 list_free(dane->pkeys, pkey_free);
1227 list_free(dane->certs, cert_free);
1231 static dane_host_list
1232 host_list_init(const char **src)
1234 dane_host_list head = NULL;
1238 dane_host_list elem = (dane_host_list) OPENSSL_malloc(sizeof(*elem));
1241 list_free(head, ossl_free);
1244 elem->value = OPENSSL_strdup(*src++);
1245 LINSERT(head, elem);
1252 DANESSL_get_match_cert(SSL *ssl, X509 **match, const char **mhost, int *depth)
1256 if (dane_idx < 0 || (dane = SSL_get_ex_data(ssl, dane_idx)) == 0)
1258 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1265 *match = dane->match;
1267 *mhost = dane->mhost;
1269 *depth = dane->mdpth;
1272 return (dane->match != 0);
1278 DANESSL_verify_chain(SSL *ssl, STACK_OF(X509) *chain)
1282 X509_STORE_CTX * store_ctx;
1283 SSL_CTX *ssl_ctx = SSL_get_SSL_CTX(ssl);
1284 X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
1285 int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1287 cert = sk_X509_value(chain, 0);
1288 if (!(store_ctx = X509_STORE_CTX_new()))
1290 DANEerr(DANESSL_F_DANESSL_VERIFY_CHAIN, ERR_R_MALLOC_FAILURE);
1293 if (!X509_STORE_CTX_init(store_ctx, store, cert, chain))
1295 X509_STORE_CTX_free(store_ctx);
1298 X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx, ssl);
1300 X509_STORE_CTX_set_default(store_ctx,
1301 SSL_is_server(ssl) ? "ssl_client" : "ssl_server");
1302 X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
1303 SSL_get0_param(ssl));
1305 if (SSL_get_verify_callback(ssl))
1306 X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
1308 ret = verify_cert(store_ctx, NULL);
1310 SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
1311 X509_STORE_CTX_cleanup(store_ctx);
1322 Call this for each TLSA record found for the target, after the
1323 DANE setup has been done on the ssl connection handle.
1326 ssl Connection handle
1327 usage TLSA record field
1328 selector TLSA record field
1329 mdname ??? message digest name?
1330 data ??? TLSA record megalump?
1340 DANESSL_add_tlsa(SSL *ssl, uint8_t usage, uint8_t selector, const char *mdname,
1341 unsigned const char *data, size_t dlen)
1344 dane_selector_list s = 0;
1345 dane_mtype_list m = 0;
1346 dane_data_list d = 0;
1347 dane_cert_list xlist = 0;
1348 dane_pkey_list klist = 0;
1349 const EVP_MD *md = 0;
1351 DEBUG(D_tls) debug_printf("Dane add-tlsa: usage %u sel %u mdname \"%s\"\n",
1352 usage, selector, mdname);
1354 if(dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1356 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1360 if (usage > DANESSL_USAGE_LAST)
1362 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_USAGE);
1365 if (selector > DANESSL_SELECTOR_LAST)
1367 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_SELECTOR);
1371 /* Support built-in standard one-digit mtypes */
1372 if (mdname && *mdname && mdname[1] == '\0')
1373 switch (*mdname - '0')
1375 case DANESSL_MATCHING_FULL: mdname = 0; break;
1376 case DANESSL_MATCHING_2256: mdname = "sha256"; break;
1377 case DANESSL_MATCHING_2512: mdname = "sha512"; break;
1379 if (mdname && *mdname && (md = EVP_get_digestbyname(mdname)) == 0)
1381 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DIGEST);
1384 if (mdname && *mdname && dlen != EVP_MD_size(md))
1386 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DATA_LENGTH);
1391 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_NULL_DATA);
1396 * Full Certificate or Public Key when NULL or empty digest name
1398 if (!mdname || !*mdname)
1402 const unsigned char *p = data;
1404 #define xklistinit(lvar, ltype, var, freeFunc) do { \
1405 (lvar) = (ltype) OPENSSL_malloc(sizeof(*(lvar))); \
1406 if ((lvar) == 0) { \
1407 DANEerr(DANESSL_F_ADD_TLSA, ERR_R_MALLOC_FAILURE); \
1412 lvar->value = var; \
1414 #define xkfreeret(ret) do { \
1415 if (xlist) list_free(xlist, cert_free); \
1416 if (klist) list_free(klist, pkey_free); \
1422 case DANESSL_SELECTOR_CERT:
1423 if (!d2i_X509(&x, &p, dlen) || dlen != p - data)
1427 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT);
1430 k = X509_get_pubkey(x);
1435 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT_PKEY);
1438 if (usage == DANESSL_USAGE_DANE_TA)
1439 xklistinit(xlist, dane_cert_list, x, X509_free);
1442 case DANESSL_SELECTOR_SPKI:
1443 if (!d2i_PUBKEY(&k, &p, dlen) || dlen != p - data)
1447 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_PKEY);
1450 if (usage == DANESSL_USAGE_DANE_TA)
1451 xklistinit(klist, dane_pkey_list, k, EVP_PKEY_free);
1456 /* Find insertion point and don't add duplicate elements. */
1457 for (s = dane->selectors[usage]; s; s = s->next)
1458 if (s->value->selector == selector)
1460 for (m = s->value->mtype; m; m = m->next)
1461 if (m->value->md == md)
1463 for (d = m->value->data; d; d = d->next)
1464 if ( d->value->datalen == dlen
1465 && memcmp(d->value->data, data, dlen) == 0)
1472 if ((d = (dane_data_list) list_alloc(sizeof(*d->value) + dlen)) == 0)
1474 d->value->datalen = dlen;
1475 memcpy(d->value->data, data, dlen);
1478 if ((m = (dane_mtype_list) list_alloc(sizeof(*m->value))) == 0)
1480 list_free(d, ossl_free);
1484 if ((m->value->md = md) != 0)
1485 m->value->mdlen = dlen;
1488 if ((s = (dane_selector_list) list_alloc(sizeof(*s->value))) == 0)
1490 list_free(m, dane_mtype_free);
1493 s->value->mtype = 0;
1494 s->value->selector = selector;
1495 LINSERT(dane->selectors[usage], s);
1497 LINSERT(s->value->mtype, m);
1499 LINSERT(m->value->data, d);
1502 LINSERT(dane->certs, xlist);
1504 LINSERT(dane->pkeys, klist);
1513 Call this once we have an ssl connection handle but before
1514 making the TLS connection.
1516 => In tls_client_start() after the call to SSL_new()
1517 and before the call to SSL_connect(). Exactly where
1518 probably does not matter.
1519 We probably want to keep our existing SNI handling;
1520 call this with NULL.
1523 ssl Connection handle
1524 sni_domain Optional peer server name
1525 hostnames list of names to chack against peer cert
1534 DANESSL_init(SSL *ssl, const char *sni_domain, const char **hostnames)
1539 DEBUG(D_tls) debug_printf("Dane ssl_init\n");
1542 DANEerr(DANESSL_F_INIT, DANESSL_R_LIBRARY_INIT);
1546 if (sni_domain && !SSL_set_tlsext_host_name(ssl, sni_domain))
1549 if ((dane = (ssl_dane *) OPENSSL_malloc(sizeof(ssl_dane))) == 0)
1551 DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1554 if (!SSL_set_ex_data(ssl, dane_idx, dane))
1556 DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1570 dane->mhost = 0; /* Future SSL control interface */
1571 dane->mdpth = 0; /* Future SSL control interface */
1572 dane->multi = 0; /* Future SSL control interface */
1576 for (i = 0; i <= DANESSL_USAGE_LAST; ++i)
1577 dane->selectors[i] = 0;
1579 if (hostnames && (dane->hosts = host_list_init(hostnames)) == 0)
1581 DANEerr(DANESSL_F_INIT, ERR_R_MALLOC_FAILURE);
1582 DANESSL_cleanup(ssl);
1592 Call this once we have a context to work with, but
1593 before DANESSL_init()
1595 => in tls_client_start(), after tls_init() call gives us the ctx,
1596 if we decide we want to (policy) and can (TLSA records available)
1597 replacing (? what about fallback) everything from testing tls_verify_hosts
1598 down to just before calling SSL_new() for the conn handle.
1609 DANESSL_CTX_init(SSL_CTX *ctx)
1611 DEBUG(D_tls) debug_printf("Dane ctx-init\n");
1614 SSL_CTX_set_cert_verify_callback(ctx, verify_cert, 0);
1617 DANEerr(DANESSL_F_CTX_INIT, DANESSL_R_LIBRARY_INIT);
1625 * Store library id in zeroth function slot, used to locate the library
1626 * name. This must be done before we load the error strings.
1628 err_lib_dane = ERR_get_next_error_library();
1630 #ifndef OPENSSL_NO_ERR
1631 if (err_lib_dane > 0)
1633 dane_str_functs[0].error |= ERR_PACK(err_lib_dane, 0, 0);
1634 ERR_load_strings(err_lib_dane, dane_str_functs);
1635 ERR_load_strings(err_lib_dane, dane_str_reasons);
1640 * Register SHA-2 digests, if implemented and not already registered.
1642 #if defined(LN_sha256) && defined(NID_sha256) && !defined(OPENSSL_NO_SHA256)
1643 if (!EVP_get_digestbyname(LN_sha224)) EVP_add_digest(EVP_sha224());
1644 if (!EVP_get_digestbyname(LN_sha256)) EVP_add_digest(EVP_sha256());
1646 #if defined(LN_sha512) && defined(NID_sha512) && !defined(OPENSSL_NO_SHA512)
1647 if (!EVP_get_digestbyname(LN_sha384)) EVP_add_digest(EVP_sha384());
1648 if (!EVP_get_digestbyname(LN_sha512)) EVP_add_digest(EVP_sha512());
1652 * Register an SSL index for the connection-specific ssl_dane structure.
1653 * Using a separate index makes it possible to add DANE support to
1654 * existing OpenSSL releases that don't have a suitable pointer in the
1657 dane_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
1661 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1663 run_once(volatile int * once, void (*init)(void))
1667 CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
1670 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1671 CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1680 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1682 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1690 Call this once. Probably early in startup will do; may need
1691 to be after SSL library init.
1693 => put after call to tls_init() for now
1701 DANESSL_library_init(void)
1703 static CRYPTO_ONCE once = CRYPTO_ONCE_STATIC_INIT;
1705 DEBUG(D_tls) debug_printf("Dane lib-init\n");
1706 (void) CRYPTO_THREAD_run_once(&once, dane_init);
1708 #if defined(LN_sha256)
1709 /* No DANE without SHA256 support */
1710 if (dane_idx >= 0 && EVP_get_digestbyname(LN_sha256) != 0)
1713 DANEerr(DANESSL_F_LIBRARY_INIT, DANESSL_R_SUPPORT);