2 * Author: Viktor Dukhovni
3 * License: THIS CODE IS IN THE PUBLIC DOMAIN.
5 * Copyright (c) The Exim Maintainers 2014 - 2019
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)
29 /* LibreSSL 2.9.0 and later - 2.9.0 has removed a number of macros ... */
30 #ifdef LIBRESSL_VERSION_NUMBER
31 # if LIBRESSL_VERSION_NUMBER >= 0x2090000fL
32 # define EXIM_HAVE_ASN1_MACROS
36 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
37 # define EXIM_HAVE_ASN1_MACROS
38 # define EXIM_OPAQUE_X509
39 /* Older OpenSSL and all LibreSSL */
41 # define X509_STORE_CTX_get_verify(ctx) (ctx)->verify
42 # define X509_STORE_CTX_get_verify_cb(ctx) (ctx)->verify_cb
43 # define X509_STORE_CTX_get0_cert(ctx) (ctx)->cert
44 # define X509_STORE_CTX_get0_chain(ctx) (ctx)->chain
45 # define X509_STORE_CTX_get0_untrusted(ctx) (ctx)->untrusted
47 # define X509_STORE_CTX_set_verify(ctx, verify_chain) (ctx)->verify = (verify_chain)
48 # define X509_STORE_CTX_set0_verified_chain(ctx, sk) (ctx)->chain = (sk)
49 # define X509_STORE_CTX_set_error_depth(ctx, val) (ctx)->error_depth = (val)
50 # define X509_STORE_CTX_set_current_cert(ctx, cert) (ctx)->current_cert = (cert)
52 # define ASN1_STRING_get0_data ASN1_STRING_data
53 # define X509_getm_notBefore X509_get_notBefore
54 # define X509_getm_notAfter X509_get_notAfter
56 # define CRYPTO_ONCE_STATIC_INIT 0
57 # define CRYPTO_THREAD_run_once run_once
58 typedef int CRYPTO_ONCE;
64 #define DANESSL_F_ADD_SKID 100
65 #define DANESSL_F_ADD_TLSA 101
66 #define DANESSL_F_CHECK_END_ENTITY 102
67 #define DANESSL_F_CTX_INIT 103
68 #define DANESSL_F_GROW_CHAIN 104
69 #define DANESSL_F_INIT 105
70 #define DANESSL_F_LIBRARY_INIT 106
71 #define DANESSL_F_LIST_ALLOC 107
72 #define DANESSL_F_MATCH 108
73 #define DANESSL_F_PUSH_EXT 109
74 #define DANESSL_F_SET_TRUST_ANCHOR 110
75 #define DANESSL_F_VERIFY_CERT 111
76 #define DANESSL_F_WRAP_CERT 112
77 #define DANESSL_F_DANESSL_VERIFY_CHAIN 113
79 #define DANESSL_R_BAD_CERT 100
80 #define DANESSL_R_BAD_CERT_PKEY 101
81 #define DANESSL_R_BAD_DATA_LENGTH 102
82 #define DANESSL_R_BAD_DIGEST 103
83 #define DANESSL_R_BAD_NULL_DATA 104
84 #define DANESSL_R_BAD_PKEY 105
85 #define DANESSL_R_BAD_SELECTOR 106
86 #define DANESSL_R_BAD_USAGE 107
87 #define DANESSL_R_INIT 108
88 #define DANESSL_R_LIBRARY_INIT 109
89 #define DANESSL_R_NOSIGN_KEY 110
90 #define DANESSL_R_SCTX_INIT 111
91 #define DANESSL_R_SUPPORT 112
93 #ifndef OPENSSL_NO_ERR
94 #define DANESSL_F_PLACEHOLDER 0 /* FIRST! Value TBD */
95 static ERR_STRING_DATA dane_str_functs[] = {
97 {DANESSL_F_PLACEHOLDER, "DANE library"}, /* FIRST!!! */
98 {DANESSL_F_ADD_SKID, "add_skid"},
99 {DANESSL_F_ADD_TLSA, "DANESSL_add_tlsa"},
100 {DANESSL_F_CHECK_END_ENTITY, "check_end_entity"},
101 {DANESSL_F_CTX_INIT, "DANESSL_CTX_init"},
102 {DANESSL_F_GROW_CHAIN, "grow_chain"},
103 {DANESSL_F_INIT, "DANESSL_init"},
104 {DANESSL_F_LIBRARY_INIT, "DANESSL_library_init"},
105 {DANESSL_F_LIST_ALLOC, "list_alloc"},
106 {DANESSL_F_MATCH, "match"},
107 {DANESSL_F_PUSH_EXT, "push_ext"},
108 {DANESSL_F_SET_TRUST_ANCHOR, "set_trust_anchor"},
109 {DANESSL_F_VERIFY_CERT, "verify_cert"},
110 {DANESSL_F_WRAP_CERT, "wrap_cert"},
113 static ERR_STRING_DATA dane_str_reasons[] = {
115 {DANESSL_R_BAD_CERT, "Bad TLSA record certificate"},
116 {DANESSL_R_BAD_CERT_PKEY, "Bad TLSA record certificate public key"},
117 {DANESSL_R_BAD_DATA_LENGTH, "Bad TLSA record digest length"},
118 {DANESSL_R_BAD_DIGEST, "Bad TLSA record digest"},
119 {DANESSL_R_BAD_NULL_DATA, "Bad TLSA record null data"},
120 {DANESSL_R_BAD_PKEY, "Bad TLSA record public key"},
121 {DANESSL_R_BAD_SELECTOR, "Bad TLSA record selector"},
122 {DANESSL_R_BAD_USAGE, "Bad TLSA record usage"},
123 {DANESSL_R_INIT, "DANESSL_init() required"},
124 {DANESSL_R_LIBRARY_INIT, "DANESSL_library_init() required"},
125 {DANESSL_R_NOSIGN_KEY, "Certificate usage 2 requires EC support"},
126 {DANESSL_R_SCTX_INIT, "DANESSL_CTX_init() required"},
127 {DANESSL_R_SUPPORT, "DANE library features not supported"},
132 #define DANEerr(f, r) ERR_PUT_error(err_lib_dane, (f), (r), __FUNCTION__, __LINE__)
134 static int err_lib_dane = -1;
135 static int dane_idx = -1;
137 #ifdef X509_V_FLAG_PARTIAL_CHAIN /* OpenSSL >= 1.0.2 */
138 static int wrap_to_root = 0;
140 static int wrap_to_root = 1;
143 static void (*cert_free)(void *) = (void (*)(void *)) X509_free;
144 static void (*pkey_free)(void *) = (void (*)(void *)) EVP_PKEY_free;
146 typedef struct dane_list
148 struct dane_list *next;
152 #define LINSERT(h, e) do { (e)->next = (h); (h) = (e); } while (0)
154 typedef struct dane_host_list
156 struct dane_host_list *next;
160 typedef struct dane_data
163 unsigned char data[0];
166 typedef struct dane_data_list
168 struct dane_data_list *next;
172 typedef struct dane_mtype
179 typedef struct dane_mtype_list
181 struct dane_mtype_list *next;
185 typedef struct dane_selector
188 dane_mtype_list mtype;
191 typedef struct dane_selector_list
193 struct dane_selector_list *next;
195 } *dane_selector_list;
197 typedef struct dane_pkey_list
199 struct dane_pkey_list *next;
203 typedef struct dane_cert_list
205 struct dane_cert_list *next;
209 typedef struct ssl_dane
211 int (*verify)(X509_STORE_CTX *);
212 STACK_OF(X509) *roots;
213 STACK_OF(X509) *chain;
214 X509 *match; /* Matched cert */
215 const char *thost; /* TLSA base domain */
216 char *mhost; /* Matched peer name */
217 dane_pkey_list pkeys;
218 dane_cert_list certs;
219 dane_host_list hosts;
220 dane_selector_list selectors[DANESSL_USAGE_LAST + 1];
222 int mdpth; /* Depth of matched cert */
223 int multi; /* Multi-label wildcards? */
224 int count; /* Number of TLSA records */
227 #ifndef X509_V_ERR_HOSTNAME_MISMATCH
228 # define X509_V_ERR_HOSTNAME_MISMATCH X509_V_ERR_APPLICATION_VERIFICATION
234 match(dane_selector_list slist, X509 *cert, int depth)
239 * Note, set_trust_anchor() needs to know whether the match was for a
240 * pkey digest or a certificate digest. We return MATCHED_PKEY or
241 * MATCHED_CERT accordingly.
243 #define MATCHED_CERT (DANESSL_SELECTOR_CERT + 1)
244 #define MATCHED_PKEY (DANESSL_SELECTOR_SPKI + 1)
247 * Loop over each selector, mtype, and associated data element looking
250 for (matched = 0; !matched && slist; slist = slist->next)
252 unsigned char mdbuf[EVP_MAX_MD_SIZE];
253 unsigned char *buf = NULL;
255 unsigned int len = 0;
258 * Extract ASN.1 DER form of certificate or public key.
260 switch(slist->value->selector)
262 case DANESSL_SELECTOR_CERT:
263 len = i2d_X509(cert, NULL);
264 buf2 = buf = US OPENSSL_malloc(len);
265 if(buf) i2d_X509(cert, &buf2);
267 case DANESSL_SELECTOR_SPKI:
268 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
269 buf2 = buf = US OPENSSL_malloc(len);
270 if(buf) i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf2);
276 DANEerr(DANESSL_F_MATCH, ERR_R_MALLOC_FAILURE);
279 OPENSSL_assert(buf2 - buf == len);
282 * Loop over each mtype and data element
284 for (dane_mtype_list m = slist->value->mtype; !matched && m; m = m->next)
286 unsigned char *cmpbuf = buf;
287 unsigned int cmplen = len;
290 * If it is a digest, compute the corresponding digest of the
291 * DER data for comparison, otherwise, use the full object.
296 if (!EVP_Digest(buf, len, cmpbuf, &cmplen, m->value->md, 0))
299 for (dane_data_list d = m->value->data; !matched && d; d = d->next)
300 if ( cmplen == d->value->datalen
301 && memcmp(cmpbuf, d->value->data, cmplen) == 0)
302 matched = slist->value->selector + 1;
312 push_ext(X509 *cert, X509_EXTENSION *ext)
316 if (X509_add_ext(cert, ext, -1))
318 X509_EXTENSION_free(ext);
320 DANEerr(DANESSL_F_PUSH_EXT, ERR_R_MALLOC_FAILURE);
325 add_ext(X509 *issuer, X509 *subject, int ext_nid, char *ext_val)
329 X509V3_set_ctx(&v3ctx, issuer, subject, 0, 0, 0);
330 return push_ext(subject, X509V3_EXT_conf_nid(0, &v3ctx, ext_nid, ext_val));
334 set_serial(X509 *cert, AUTHORITY_KEYID *akid, X509 *subject)
339 if (akid && akid->serial)
340 return (X509_set_serialNumber(cert, akid->serial));
343 * Add one to subject's serial to avoid collisions between TA serial and
344 * serial of signing root.
346 if ( (bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(subject), 0)) != 0
347 && BN_add_word(bn, 1)
348 && BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(cert)))
357 add_akid(X509 *cert, AUTHORITY_KEYID *akid)
359 int nid = NID_authority_key_identifier;
360 ASN1_OCTET_STRING *id;
365 * 0 will never be our subject keyid from a SHA-1 hash, but it could be
366 * our subject keyid if forced from child's akid. If so, set our
367 * authority keyid to 1. This way we are never self-signed, and thus
368 * exempt from any potential (off by default for now in OpenSSL)
369 * self-signature checks!
371 id = akid && akid->keyid ? akid->keyid : 0;
372 if (id && ASN1_STRING_length(id) == 1 && *ASN1_STRING_get0_data(id) == c)
375 if ( (akid = AUTHORITY_KEYID_new()) != 0
376 && (akid->keyid = ASN1_OCTET_STRING_new()) != 0
377 #ifdef EXIM_HAVE_ASN1_MACROS
378 && ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
380 && M_ASN1_OCTET_STRING_set(akid->keyid, (void *) &c, 1)
382 && X509_add1_ext_i2d(cert, nid, akid, 0, X509V3_ADD_APPEND))
385 AUTHORITY_KEYID_free(akid);
390 add_skid(X509 *cert, AUTHORITY_KEYID *akid)
392 int nid = NID_subject_key_identifier;
394 if (!akid || !akid->keyid)
395 return add_ext(0, cert, nid, "hash");
396 return X509_add1_ext_i2d(cert, nid, akid->keyid, 0, X509V3_ADD_APPEND) > 0;
400 akid_issuer_name(AUTHORITY_KEYID *akid)
402 if (akid && akid->issuer)
404 GENERAL_NAMES *gens = akid->issuer;
406 for (int i = 0; i < sk_GENERAL_NAME_num(gens); ++i)
408 GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
410 if (gn->type == GEN_DIRNAME)
418 set_issuer_name(X509 *cert, AUTHORITY_KEYID *akid, X509_NAME *subj)
420 X509_NAME *name = akid_issuer_name(akid);
423 * If subject's akid specifies an authority key identifier issuer name, we
426 return X509_set_issuer_name(cert,
431 grow_chain(ssl_dane *dane, int trusted, X509 *cert)
433 STACK_OF(X509) **xs = trusted ? &dane->roots : &dane->chain;
434 static ASN1_OBJECT *serverAuth = 0;
439 if ( trusted && !serverAuth
440 && !(serverAuth = OBJ_nid2obj(NID_server_auth)))
442 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
445 if (!*xs && !(*xs = sk_X509_new_null()))
447 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
453 if (trusted && !X509_add1_trust_object(cert, serverAuth))
455 #ifdef EXIM_OPAQUE_X509
458 CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
460 if (!sk_X509_push(*xs, cert))
463 DANEerr(DANESSL_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
471 wrap_issuer(ssl_dane *dane, EVP_PKEY *key, X509 *subject, int depth, int top)
475 AUTHORITY_KEYID *akid;
476 X509_NAME *name = X509_get_issuer_name(subject);
477 EVP_PKEY *newkey = key ? key : X509_get_pubkey(subject);
479 #define WRAP_MID 0 /* Ensure intermediate. */
480 #define WRAP_TOP 1 /* Ensure self-signed. */
482 if (!name || !newkey || !(cert = X509_new()))
486 * Record the depth of the trust-anchor certificate.
489 dane->depth = depth + 1;
492 * XXX: Uncaught error condition:
494 * The return value is NULL both when the extension is missing, and when
495 * OpenSSL rans out of memory while parsing the extension.
498 akid = X509_get_ext_d2i(subject, NID_authority_key_identifier, 0, 0);
499 /* XXX: Should we peek at the error stack here??? */
502 * If top is true generate a self-issued root CA, otherwise an
503 * intermediate CA and possibly its self-signed issuer.
505 * CA cert valid for +/- 30 days
507 if ( !X509_set_version(cert, 2)
508 || !set_serial(cert, akid, subject)
509 || !set_issuer_name(cert, akid, name)
510 || !X509_gmtime_adj(X509_getm_notBefore(cert), -30 * 86400L)
511 || !X509_gmtime_adj(X509_getm_notAfter(cert), 30 * 86400L)
512 || !X509_set_subject_name(cert, name)
513 || !X509_set_pubkey(cert, newkey)
514 || !add_ext(0, cert, NID_basic_constraints, "CA:TRUE")
515 || (!top && !add_akid(cert, akid))
516 || !add_skid(cert, akid)
517 || ( !top && wrap_to_root
518 && !wrap_issuer(dane, newkey, cert, depth, WRAP_TOP)))
522 AUTHORITY_KEYID_free(akid);
524 EVP_PKEY_free(newkey);
526 ret = grow_chain(dane, !top && wrap_to_root ? UNTRUSTED : TRUSTED, cert);
533 wrap_cert(ssl_dane *dane, X509 *tacert, int depth)
536 dane->depth = depth + 1;
539 * If the TA certificate is self-issued, or need not be, use it directly.
540 * Otherwise, synthesize requisite ancestors.
543 || X509_check_issued(tacert, tacert) == X509_V_OK)
544 return grow_chain(dane, TRUSTED, tacert);
546 if (wrap_issuer(dane, 0, tacert, depth, WRAP_MID))
547 return grow_chain(dane, UNTRUSTED, tacert);
552 ta_signed(ssl_dane *dane, X509 *cert, int depth)
558 * First check whether issued and signed by a TA cert, this is cheaper
559 * than the bare-public key checks below, since we can determine whether
560 * the candidate TA certificate issued the certificate to be checked
561 * first (name comparisons), before we bother with signature checks
562 * (public key operations).
564 for (dane_cert_list x = dane->certs; !done && x; x = x->next)
566 if (X509_check_issued(x->value, cert) == X509_V_OK)
568 if (!(pk = X509_get_pubkey(x->value)))
571 * The cert originally contained a valid pkey, which does
572 * not just vanish, so this is most likely a memory error.
577 /* Check signature, since some other TA may work if not this. */
578 if (X509_verify(cert, pk) > 0)
579 done = wrap_cert(dane, x->value, depth) ? 1 : -1;
585 * With bare TA public keys, we can't check whether the trust chain is
586 * issued by the key, but we can determine whether it is signed by the
587 * key, so we go with that.
589 * Ideally, the corresponding certificate was presented in the chain, and we
590 * matched it by its public key digest one level up. This code is here
591 * to handle adverse conditions imposed by sloppy administrators of
592 * receiving systems with poorly constructed chains.
594 * We'd like to optimize out keys that should not match when the cert's
595 * authority key id does not match the key id of this key computed via
596 * the RFC keyid algorithm (SHA-1 digest of public key bit-string sans
597 * ASN1 tag and length thus also excluding the unused bits field that is
598 * logically part of the length). However, some CAs have a non-standard
599 * authority keyid, so we lose. Too bad.
601 * This may push errors onto the stack when the certificate signature is
602 * not of the right type or length, throw these away,
604 for (dane_pkey_list k = dane->pkeys; !done && k; k = k->next)
605 if (X509_verify(cert, k->value) > 0)
606 done = wrap_issuer(dane, k->value, cert, depth, WRAP_MID) ? 1 : -1;
614 set_trust_anchor(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
620 STACK_OF(X509) *in = X509_STORE_CTX_get0_untrusted(ctx);
622 if (!grow_chain(dane, UNTRUSTED, 0))
626 * Accept a degenerate case: depth 0 self-signed trust-anchor.
628 if (X509_check_issued(cert, cert) == X509_V_OK)
631 matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], cert, 0);
632 if (matched > 0 && !grow_chain(dane, TRUSTED, cert))
637 /* Make a shallow copy of the input untrusted chain. */
638 if (!(in = sk_X509_dup(in)))
640 DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
645 * At each iteration we consume the issuer of the current cert. This
646 * reduces the length of the "in" chain by one. If no issuer is found,
647 * we are done. We also stop when a certificate matches a TA in the
650 * Caller ensures that the initial certificate is not self-signed.
652 for (int n = sk_X509_num(in); n > 0; --n, ++depth)
655 for (i = 0; i < n; ++i)
656 if (X509_check_issued(sk_X509_value(in, i), cert) == X509_V_OK)
660 * Final untrusted element with no issuer in the peer's chain, it may
661 * however be signed by a pkey or cert obtained via a TLSA RR.
666 /* Peer's chain contains an issuer ca. */
667 ca = sk_X509_delete(in, i);
669 /* If not a trust anchor, record untrusted ca and continue. */
670 if ((matched = match(dane->selectors[DANESSL_USAGE_DANE_TA], ca,
673 if (grow_chain(dane, UNTRUSTED, ca))
675 if (X509_check_issued(ca, ca) != X509_V_OK)
677 /* Restart with issuer as subject */
681 /* Final self-signed element, skip ta_signed() check. */
687 else if(matched == MATCHED_CERT)
689 if(!wrap_cert(dane, ca, depth))
692 else if(matched == MATCHED_PKEY)
694 if ( !(takey = X509_get_pubkey(ca))
695 || !wrap_issuer(dane, takey, cert, depth, WRAP_MID))
698 EVP_PKEY_free(takey);
700 DANEerr(DANESSL_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
707 /* Shallow free the duplicated input untrusted chain. */
711 * When the loop exits, if "cert" is set, it is not self-signed and has
712 * no issuer in the chain, we check for a possible signature via a DNS
713 * obtained TA cert or public key.
715 if (matched == 0 && cert)
716 matched = ta_signed(dane, cert, depth);
722 check_end_entity(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
726 matched = match(dane->selectors[DANESSL_USAGE_DANE_EE], cert, 0);
732 if(!X509_STORE_CTX_get0_chain(ctx))
734 STACK_OF(X509) * sk = sk_X509_new_null();
735 if (sk && sk_X509_push(sk, cert))
738 X509_STORE_CTX_set0_verified_chain(ctx, sk);
742 if (sk) sk_X509_free(sk);
743 DANEerr(DANESSL_F_CHECK_END_ENTITY, ERR_R_MALLOC_FAILURE);
752 match_name(const char *certid, ssl_dane *dane)
754 int multi = dane->multi;
756 for (dane_host_list hosts = dane->hosts; hosts; hosts = hosts->next)
758 int match_subdomain = 0;
759 const char *domain = hosts->value;
764 if (*domain == '.' && domain[1] != '\0')
771 * Sub-domain match: certid is any sub-domain of hostname.
775 if ( (idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
776 && certid[idlen - domlen - 1] == '.'
777 && !strcasecmp(certid + (idlen - domlen), domain))
784 * Exact match and initial "*" match. The initial "*" in a certid
785 * matches one (if multi is false) or more hostname components under
786 * the condition that the certid contains multiple hostname components.
788 if ( !strcasecmp(certid, domain)
789 || ( certid[0] == '*' && certid[1] == '.' && certid[2] != 0
790 && (parent = strchr(domain, '.')) != 0
791 && (idlen = strlen(certid + 1)) <= (domlen = strlen(parent))
792 && strcasecmp(multi ? parent + domlen - idlen : parent, certid+1) == 0))
799 check_name(const char *name, int len)
801 const char *cp = name + len;
803 while (len > 0 && !*--cp)
804 --len; /* Ignore trailing NULs */
807 for (cp = name; *cp; cp++)
810 if (!((c >= 'a' && c <= 'z') ||
811 (c >= '0' && c <= '9') ||
812 (c >= 'A' && c <= 'Z') ||
813 (c == '.' || c == '-') ||
815 return 0; /* Only LDH, '.' and '*' */
817 if (cp - name != len) /* Guard against internal NULs */
823 parse_dns_name(const GENERAL_NAME *gn)
825 if (gn->type != GEN_DNS)
827 if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
829 return check_name(CCS ASN1_STRING_get0_data(gn->d.ia5),
830 ASN1_STRING_length(gn->d.ia5));
834 parse_subject_name(X509 *cert)
836 X509_NAME *name = X509_get_subject_name(cert);
837 X509_NAME_ENTRY *entry;
838 ASN1_STRING *entry_str;
839 unsigned char *namebuf;
840 int nid = NID_commonName;
844 if (!name || (i = X509_NAME_get_index_by_NID(name, nid, -1)) < 0)
846 if (!(entry = X509_NAME_get_entry(name, i)))
848 if (!(entry_str = X509_NAME_ENTRY_get_data(entry)))
851 if ((len = ASN1_STRING_to_UTF8(&namebuf, entry_str)) < 0)
853 if (len <= 0 || check_name(CS namebuf, len) == 0)
855 OPENSSL_free(namebuf);
862 name_check(ssl_dane *dane, X509 *cert)
865 BOOL got_altname = FALSE;
868 gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
871 int n = sk_GENERAL_NAME_num(gens);
873 for (int i = 0; i < n; ++i)
875 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
878 if (gn->type != GEN_DNS)
881 certid = parse_dns_name(gn);
882 if (certid && *certid)
884 if ((matched = match_name(certid, dane)) == 0)
886 if (!(dane->mhost = OPENSSL_strdup(certid)))
888 DEBUG(D_tls) debug_printf("Dane name_check: matched SAN %s\n", certid);
892 GENERAL_NAMES_free(gens);
896 * XXX: Should the subjectName be skipped when *any* altnames are present,
897 * or only when DNS altnames are present?
901 char *certid = parse_subject_name(cert);
902 if (certid != 0 && *certid && (matched = match_name(certid, dane)) != 0)
904 DEBUG(D_tls) debug_printf("Dane name_check: matched SN %s\n", certid);
905 dane->mhost = OPENSSL_strdup(certid);
908 OPENSSL_free(certid);
914 verify_chain(X509_STORE_CTX *ctx)
916 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
917 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
918 STACK_OF(X509) * chain = X509_STORE_CTX_get0_chain(ctx);
919 int chain_length = sk_X509_num(chain);
920 int ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
921 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
922 ssl_dane *dane = SSL_get_ex_data(ssl, dane_idx);
923 dane_selector_list issuer_rrs = dane->selectors[DANESSL_USAGE_PKIX_TA];
924 dane_selector_list leaf_rrs = dane->selectors[DANESSL_USAGE_PKIX_EE];
927 DEBUG(D_tls) debug_printf("Dane verify_chain\n");
929 /* Restore OpenSSL's internal_verify() as the signature check function */
930 X509_STORE_CTX_set_verify(ctx, dane->verify);
932 if ((matched = name_check(dane, cert)) < 0)
934 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
940 X509_STORE_CTX_set_error_depth(ctx, 0);
941 X509_STORE_CTX_set_current_cert(ctx, cert);
942 X509_STORE_CTX_set_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH);
949 * Satisfy at least one usage 0 or 1 constraint, unless we've already
950 * matched a usage 2 trust anchor.
952 * XXX: internal_verify() doesn't callback with top certs that are not
953 * self-issued. This is fixed in OpenSSL 1.1.0.
955 if (dane->roots && sk_X509_num(dane->roots))
957 X509 *top = sk_X509_value(chain, dane->depth);
959 dane->mdpth = dane->depth;
963 #if OPENSSL_VERSION_NUMBER < 0x10100000L
964 if (X509_check_issued(top, top) != X509_V_OK)
966 X509_STORE_CTX_set_error_depth(ctx, dane->depth);
967 X509_STORE_CTX_set_current_cert(ctx, top);
972 /* Pop synthetic trust-anchor ancestors off the chain! */
973 while (--chain_length > dane->depth)
974 X509_free(sk_X509_pop(chain));
982 * Check for an EE match, then a CA match at depths > 0, and
983 * finally, if the EE cert is self-issued, for a depth 0 CA match.
986 matched = match(leaf_rrs, xn, 0);
987 if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched EE\n");
989 if (!matched && issuer_rrs)
990 for (n = chain_length-1; !matched && n >= 0; --n)
992 xn = sk_X509_value(chain, n);
993 if (n > 0 || X509_check_issued(xn, xn) == X509_V_OK)
994 matched = match(issuer_rrs, xn, n);
996 if (matched) DEBUG(D_tls) debug_printf("Dane verify_chain: matched %s\n",
997 n>0 ? "CA" : "selfisssued EE");
1001 X509_STORE_CTX_set_error_depth(ctx, 0);
1002 X509_STORE_CTX_set_current_cert(ctx, cert);
1003 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_UNTRUSTED);
1015 /* Tail recurse into OpenSSL's internal_verify */
1016 return dane->verify(ctx);
1020 dane_reset(ssl_dane *dane)
1025 OPENSSL_free(dane->mhost);
1030 sk_X509_pop_free(dane->roots, X509_free);
1035 sk_X509_pop_free(dane->chain, X509_free);
1040 X509_free(dane->match);
1047 verify_cert(X509_STORE_CTX *ctx, void *unused_ctx)
1049 static int ssl_idx = -1;
1052 int (*cb)(int, X509_STORE_CTX *) = X509_STORE_CTX_get_verify_cb(ctx);
1053 X509 *cert = X509_STORE_CTX_get0_cert(ctx);
1056 DEBUG(D_tls) debug_printf("Dane verify_cert\n");
1059 ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1062 DANEerr(DANESSL_F_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
1066 ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
1067 if (!(dane = SSL_get_ex_data(ssl, dane_idx)) || !cert)
1068 return X509_verify_cert(ctx);
1070 /* Reset for verification of a new chain, perhaps a renegotiation. */
1073 if (dane->selectors[DANESSL_USAGE_DANE_EE])
1075 if ((matched = check_end_entity(ctx, dane, cert)) > 0)
1077 X509_STORE_CTX_set_error_depth(ctx, 0);
1078 X509_STORE_CTX_set_current_cert(ctx, cert);
1083 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1088 if (dane->selectors[DANESSL_USAGE_DANE_TA])
1090 if ((matched = set_trust_anchor(ctx, dane, cert)) < 0)
1092 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
1098 * Check that setting the untrusted chain updates the expected
1099 * structure member at the expected offset.
1101 X509_STORE_CTX_trusted_stack(ctx, dane->roots);
1102 X509_STORE_CTX_set_chain(ctx, dane->chain);
1103 OPENSSL_assert(dane->chain == X509_STORE_CTX_get0_untrusted(ctx));
1108 * Name checks and usage 0/1 constraint enforcement are delayed until
1109 * X509_verify_cert() builds the full chain and calls our verify_chain()
1112 dane->verify = X509_STORE_CTX_get_verify(ctx);
1113 X509_STORE_CTX_set_verify(ctx, verify_chain);
1115 if (X509_verify_cert(ctx))
1119 * If the chain is invalid, clear any matching cert or hostname, to
1120 * protect callers that might erroneously rely on these alone without
1121 * checking the validation status.
1125 X509_free(dane->match);
1130 OPENSSL_free(dane->mhost);
1137 list_alloc(size_t vsize)
1139 void *value = (void *) OPENSSL_malloc(vsize);
1144 DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1147 if (!(l = (dane_list) OPENSSL_malloc(sizeof(*l))))
1149 OPENSSL_free(value);
1150 DANEerr(DANESSL_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1159 list_free(void *list, void (*f)(void *))
1163 for (dane_list head = (dane_list) list; head; head = next)
1166 if (f && head->value)
1179 dane_mtype_free(void *p)
1181 list_free(((dane_mtype) p)->data, ossl_free);
1186 dane_selector_free(void *p)
1188 list_free(((dane_selector) p)->mtype, dane_mtype_free);
1196 Tidy up once the connection is finished with.
1199 ssl The ssl connection handle
1201 => Before calling SSL_free()
1202 tls_close() and tls_getc() [the error path] are the obvious places.
1203 Could we do it earlier - right after verification? In tls_client_start()
1204 right after SSL_connect() returns, in that case.
1209 DANESSL_cleanup(SSL *ssl)
1213 DEBUG(D_tls) debug_printf("Dane lib-cleanup\n");
1215 if (dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1217 (void) SSL_set_ex_data(ssl, dane_idx, 0);
1221 list_free(dane->hosts, ossl_free);
1222 for (int u = 0; u <= DANESSL_USAGE_LAST; ++u)
1223 if (dane->selectors[u])
1224 list_free(dane->selectors[u], dane_selector_free);
1226 list_free(dane->pkeys, pkey_free);
1228 list_free(dane->certs, cert_free);
1232 static dane_host_list
1233 host_list_init(const char **src)
1235 dane_host_list head = NULL;
1239 dane_host_list elem = (dane_host_list) OPENSSL_malloc(sizeof(*elem));
1242 list_free(head, ossl_free);
1245 elem->value = OPENSSL_strdup(*src++);
1246 LINSERT(head, elem);
1253 DANESSL_get_match_cert(SSL *ssl, X509 **match, const char **mhost, int *depth)
1257 if (dane_idx < 0 || (dane = SSL_get_ex_data(ssl, dane_idx)) == 0)
1259 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1266 *match = dane->match;
1268 *mhost = dane->mhost;
1270 *depth = dane->mdpth;
1273 return (dane->match != 0);
1279 DANESSL_verify_chain(SSL *ssl, STACK_OF(X509) *chain)
1283 X509_STORE_CTX * store_ctx;
1284 SSL_CTX *ssl_ctx = SSL_get_SSL_CTX(ssl);
1285 X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
1286 int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
1288 cert = sk_X509_value(chain, 0);
1289 if (!(store_ctx = X509_STORE_CTX_new()))
1291 DANEerr(DANESSL_F_DANESSL_VERIFY_CHAIN, ERR_R_MALLOC_FAILURE);
1294 if (!X509_STORE_CTX_init(store_ctx, store, cert, chain))
1296 X509_STORE_CTX_free(store_ctx);
1299 X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx, ssl);
1301 X509_STORE_CTX_set_default(store_ctx,
1302 SSL_is_server(ssl) ? "ssl_client" : "ssl_server");
1303 X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
1304 SSL_get0_param(ssl));
1306 if (SSL_get_verify_callback(ssl))
1307 X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
1309 ret = verify_cert(store_ctx, NULL);
1311 SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
1312 X509_STORE_CTX_cleanup(store_ctx);
1323 Call this for each TLSA record found for the target, after the
1324 DANE setup has been done on the ssl connection handle.
1327 ssl Connection handle
1328 usage TLSA record field
1329 selector TLSA record field
1330 mdname ??? message digest name?
1331 data ??? TLSA record megalump?
1341 DANESSL_add_tlsa(SSL *ssl, uint8_t usage, uint8_t selector, const char *mdname,
1342 unsigned const char *data, size_t dlen)
1345 dane_selector_list s = 0;
1346 dane_mtype_list m = 0;
1347 dane_data_list d = 0;
1348 dane_cert_list xlist = 0;
1349 dane_pkey_list klist = 0;
1350 const EVP_MD *md = 0;
1352 DEBUG(D_tls) debug_printf("Dane add-tlsa: usage %u sel %u mdname \"%s\"\n",
1353 usage, selector, mdname);
1355 if(dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1357 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_INIT);
1361 if (usage > DANESSL_USAGE_LAST)
1363 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_USAGE);
1366 if (selector > DANESSL_SELECTOR_LAST)
1368 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_SELECTOR);
1372 /* Support built-in standard one-digit mtypes */
1373 if (mdname && *mdname && mdname[1] == '\0')
1374 switch (*mdname - '0')
1376 case DANESSL_MATCHING_FULL: mdname = 0; break;
1377 case DANESSL_MATCHING_2256: mdname = "sha256"; break;
1378 case DANESSL_MATCHING_2512: mdname = "sha512"; break;
1380 if (mdname && *mdname && !(md = EVP_get_digestbyname(mdname)))
1382 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DIGEST);
1385 if (mdname && *mdname && dlen != EVP_MD_size(md))
1387 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_DATA_LENGTH);
1392 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_NULL_DATA);
1397 * Full Certificate or Public Key when NULL or empty digest name
1399 if (!mdname || !*mdname)
1403 const unsigned char *p = data;
1405 #define xklistinit(lvar, ltype, var, freeFunc) do { \
1406 (lvar) = (ltype) OPENSSL_malloc(sizeof(*(lvar))); \
1407 if ((lvar) == 0) { \
1408 DANEerr(DANESSL_F_ADD_TLSA, ERR_R_MALLOC_FAILURE); \
1413 lvar->value = var; \
1415 #define xkfreeret(ret) do { \
1416 if (xlist) list_free(xlist, cert_free); \
1417 if (klist) list_free(klist, pkey_free); \
1423 case DANESSL_SELECTOR_CERT:
1424 if (!d2i_X509(&x, &p, dlen) || dlen != p - data)
1428 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT);
1431 k = X509_get_pubkey(x);
1436 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_CERT_PKEY);
1439 if (usage == DANESSL_USAGE_DANE_TA)
1440 xklistinit(xlist, dane_cert_list, x, X509_free);
1443 case DANESSL_SELECTOR_SPKI:
1444 if (!d2i_PUBKEY(&k, &p, dlen) || dlen != p - data)
1448 DANEerr(DANESSL_F_ADD_TLSA, DANESSL_R_BAD_PKEY);
1451 if (usage == DANESSL_USAGE_DANE_TA)
1452 xklistinit(klist, dane_pkey_list, k, EVP_PKEY_free);
1457 /* Find insertion point and don't add duplicate elements. */
1458 for (s = dane->selectors[usage]; s; s = s->next)
1459 if (s->value->selector == selector)
1461 for (m = s->value->mtype; m; m = m->next)
1462 if (m->value->md == md)
1464 for (d = m->value->data; d; d = d->next)
1465 if ( d->value->datalen == dlen
1466 && memcmp(d->value->data, data, dlen) == 0)
1473 if ((d = (dane_data_list) list_alloc(sizeof(*d->value) + dlen)) == 0)
1475 d->value->datalen = dlen;
1476 memcpy(d->value->data, data, dlen);
1479 if ((m = (dane_mtype_list) list_alloc(sizeof(*m->value))) == 0)
1481 list_free(d, ossl_free);
1485 if ((m->value->md = md) != 0)
1486 m->value->mdlen = dlen;
1489 if ((s = (dane_selector_list) list_alloc(sizeof(*s->value))) == 0)
1491 list_free(m, dane_mtype_free);
1494 s->value->mtype = 0;
1495 s->value->selector = selector;
1496 LINSERT(dane->selectors[usage], s);
1498 LINSERT(s->value->mtype, m);
1500 LINSERT(m->value->data, d);
1503 LINSERT(dane->certs, xlist);
1505 LINSERT(dane->pkeys, klist);
1514 Call this once we have an ssl connection handle but before
1515 making the TLS connection.
1517 => In tls_client_start() after the call to SSL_new()
1518 and before the call to SSL_connect(). Exactly where
1519 probably does not matter.
1520 We probably want to keep our existing SNI handling;
1521 call this with NULL.
1524 ssl Connection handle
1525 sni_domain Optional peer server name
1526 hostnames list of names to chack against peer cert
1535 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 (int 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);