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>
14 #if OPENSSL_VERSION_NUMBER < 0x1000000fL
15 # error "OpenSSL 1.0.0 or higher required"
16 #else /* remainder of file */
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
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
48 #ifndef OPENSSL_NO_ERR
49 # define DANE_F_PLACEHOLDER 0 /* FIRST! Value TBD */
50 static ERR_STRING_DATA dane_str_functs[] =
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"},
68 static ERR_STRING_DATA dane_str_reasons[] =
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"},
85 #endif /*OPENSSL_NO_ERR*/
87 #define DANEerr(f, r) ERR_PUT_error(err_lib_dane, (f), (r), __FILE__, __LINE__)
89 static int err_lib_dane = -1;
90 static int dane_idx = -1;
92 #ifdef X509_V_FLAG_PARTIAL_CHAIN /* OpenSSL >= 1.0.2 */
93 static int wrap_to_root = 0;
95 static int wrap_to_root = 1;
98 static void (*cert_free)(void *) = (void (*)(void *)) X509_free;
99 static void (*pkey_free)(void *) = (void (*)(void *)) EVP_PKEY_free;
101 typedef struct dane_list
103 struct dane_list *next;
107 #define LINSERT(h, e) do { (e)->next = (h); (h) = (e); } while (0)
109 typedef struct dane_host_list
111 struct dane_host_list *next;
115 typedef struct dane_data
118 unsigned char data[0];
121 typedef struct dane_data_list
123 struct dane_data_list *next;
127 typedef struct dane_mtype
134 typedef struct dane_mtype_list
136 struct dane_mtype_list *next;
140 typedef struct dane_selector
143 dane_mtype_list mtype;
146 typedef struct dane_selector_list
148 struct dane_selector_list *next;
150 } *dane_selector_list;
152 typedef struct dane_pkey_list
154 struct dane_pkey_list *next;
158 typedef struct dane_cert_list
160 struct dane_cert_list *next;
164 typedef struct ssl_dane
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 */
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];
176 int multi; /* Multi-label wildcards? */
177 int count; /* Number of TLSA records */
180 #ifndef X509_V_ERR_HOSTNAME_MISMATCH
181 # define X509_V_ERR_HOSTNAME_MISMATCH X509_V_ERR_APPLICATION_VERIFICATION
185 match(dane_selector_list slist, X509 *cert, int depth)
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.
194 #define MATCHED_CERT (SSL_DANE_SELECTOR_CERT + 1)
195 #define MATCHED_PKEY (SSL_DANE_SELECTOR_SPKI + 1)
198 * Loop over each selector, mtype, and associated data element looking
201 for(matched = 0; !matched && slist; slist = slist->next)
204 unsigned char mdbuf[EVP_MAX_MD_SIZE];
210 * Extract ASN.1 DER form of certificate or public key.
212 switch(slist->value->selector)
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);
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);
228 DANEerr(DANE_F_MATCH, ERR_R_MALLOC_FAILURE);
231 OPENSSL_assert(buf2 - buf == len);
234 * Loop over each mtype and data element
236 for(m = slist->value->mtype; !matched && m; m = m->next)
239 unsigned char *cmpbuf = buf;
240 unsigned int cmplen = len;
243 * If it is a digest, compute the corresponding digest of the
244 * DER data for comparison, otherwise, use the full object.
249 if(!EVP_Digest(buf, len, cmpbuf, &cmplen, m->value->md, 0))
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;
265 push_ext(X509 *cert, X509_EXTENSION *ext)
267 X509_EXTENSIONS *exts;
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))
275 X509_EXTENSION_free(ext);
277 DANEerr(DANE_F_PUSH_EXT, ERR_R_MALLOC_FAILURE);
282 add_ext(X509 *issuer, X509 *subject, int ext_nid, char *ext_val)
286 X509V3_set_ctx(&v3ctx, issuer, subject, 0, 0, 0);
287 return push_ext(subject, X509V3_EXT_conf_nid(0, &v3ctx, ext_nid, ext_val));
291 set_serial(X509 *cert, AUTHORITY_KEYID *akid, X509 *subject)
296 if(akid && akid->serial)
297 return (X509_set_serialNumber(cert, akid->serial));
300 * Add one to subject's serial to avoid collisions between TA serial and
301 * serial of signing root.
303 if( (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)))
314 add_akid(X509 *cert, AUTHORITY_KEYID *akid)
316 int nid = NID_authority_key_identifier;
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!
328 id = (ASN1_STRING *) ((akid && akid->keyid) ? akid->keyid : 0);
329 if(id && M_ASN1_STRING_length(id) == 1 && *M_ASN1_STRING_data(id) == c)
332 if( (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))
338 AUTHORITY_KEYID_free(akid);
343 add_skid(X509 *cert, AUTHORITY_KEYID *akid)
345 int nid = NID_subject_key_identifier;
347 if(!akid || !akid->keyid)
348 return add_ext(0, cert, nid, "hash");
349 return X509_add1_ext_i2d(cert, nid, akid->keyid, 0, X509V3_ADD_APPEND) > 0;
353 akid_issuer_name(AUTHORITY_KEYID *akid)
355 if(akid && akid->issuer)
358 GENERAL_NAMES *gens = akid->issuer;
360 for(i = 0; i < sk_GENERAL_NAME_num(gens); ++i)
362 GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
364 if(gn->type == GEN_DIRNAME)
372 set_issuer_name(X509 *cert, AUTHORITY_KEYID *akid)
374 X509_NAME *name = akid_issuer_name(akid);
377 * If subject's akid specifies an authority key identifer issuer name, we
380 return X509_set_issuer_name(cert,
381 name ? name : X509_get_subject_name(cert));
385 grow_chain(ssl_dane *dane, int trusted, X509 *cert)
387 STACK_OF(X509) **xs = trusted ? &dane->roots : &dane->chain;
388 static ASN1_OBJECT *serverAuth = 0;
393 if( trusted && !serverAuth
394 && !(serverAuth = OBJ_nid2obj(NID_server_auth)))
396 DANEerr(DANE_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
399 if(!*xs && !(*xs = sk_X509_new_null()))
401 DANEerr(DANE_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
407 if(trusted && !X509_add1_trust_object(cert, serverAuth))
409 CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
410 if (!sk_X509_push(*xs, cert))
413 DANEerr(DANE_F_GROW_CHAIN, ERR_R_MALLOC_FAILURE);
421 wrap_issuer(ssl_dane *dane, EVP_PKEY *key, X509 *subject, int depth, int top)
425 AUTHORITY_KEYID *akid;
426 X509_NAME *name = X509_get_issuer_name(subject);
427 EVP_PKEY *newkey = key ? key : X509_get_pubkey(subject);
429 #define WRAP_MID 0 /* Ensure intermediate. */
430 #define WRAP_TOP 1 /* Ensure self-signed. */
432 if(!name || !newkey || !(cert = X509_new()))
436 * Record the depth of the trust-anchor certificate.
439 dane->depth = depth + 1;
442 * XXX: Uncaught error condition:
444 * The return value is NULL both when the extension is missing, and when
445 * OpenSSL rans out of memory while parsing the extension.
448 akid = X509_get_ext_d2i(subject, NID_authority_key_identifier, 0, 0);
449 /* XXX: Should we peek at the error stack here??? */
452 * If top is true generate a self-issued root CA, otherwise an
453 * intermediate CA and possibly its self-signed issuer.
455 * CA cert valid for +/- 30 days
457 if( !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)))
472 AUTHORITY_KEYID_free(akid);
474 EVP_PKEY_free(newkey);
476 ret = grow_chain(dane, !top && wrap_to_root ? UNTRUSTED : TRUSTED, cert);
483 wrap_cert(ssl_dane *dane, X509 *tacert, int depth)
486 dane->depth = depth + 1;
489 * If the TA certificate is self-issued, or need not be, use it directly.
490 * Otherwise, synthesize requisuite ancestors.
493 || X509_check_issued(tacert, tacert) == X509_V_OK)
494 return grow_chain(dane, TRUSTED, tacert);
496 if(wrap_issuer(dane, 0, tacert, depth, WRAP_MID))
497 return grow_chain(dane, UNTRUSTED, tacert);
502 ta_signed(ssl_dane *dane, X509 *cert, int depth)
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).
516 for (x = dane->certs; !done && x; x = x->next)
518 if(X509_check_issued(x->value, cert) == X509_V_OK)
520 if(!(pk = X509_get_pubkey(x->value)))
523 * The cert originally contained a valid pkey, which does
524 * not just vanish, so this is most likely a memory error.
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;
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.
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.
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.
553 * This may push errors onto the stack when the certificate signature is
554 * not of the right type or length, throw these away,
556 for(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;
566 set_trust_anchor(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
574 STACK_OF(X509) *in = ctx->untrusted; /* XXX: Accessor? */
576 if(!grow_chain(dane, UNTRUSTED, 0))
580 * Accept a degenerate case: depth 0 self-signed trust-anchor.
582 if(X509_check_issued(cert, cert) == X509_V_OK)
585 matched = match(dane->selectors[SSL_DANE_USAGE_TRUSTED_CA], cert, 0);
586 if(matched > 0 && !grow_chain(dane, TRUSTED, cert))
591 /* Make a shallow copy of the input untrusted chain. */
592 if(!(in = sk_X509_dup(in)))
594 DANEerr(DANE_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
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
604 * Caller ensures that the initial certificate is not self-signed.
606 for(n = sk_X509_num(in); n > 0; --n, ++depth)
608 for(i = 0; i < n; ++i)
609 if(X509_check_issued(sk_X509_value(in, i), cert) == X509_V_OK)
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.
619 /* Peer's chain contains an issuer ca. */
620 ca = sk_X509_delete(in, i);
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))
626 if(grow_chain(dane, UNTRUSTED, ca))
628 if(!X509_check_issued(ca, ca) == X509_V_OK)
630 /* Restart with issuer as subject */
634 /* Final self-signed element, skip ta_signed() check. */
640 else if(matched == MATCHED_CERT)
642 if(!wrap_cert(dane, ca, depth))
645 else if(matched == MATCHED_PKEY)
647 if( !(takey = X509_get_pubkey(ca))
648 || !wrap_issuer(dane, takey, cert, depth, WRAP_MID))
651 EVP_PKEY_free(takey);
653 DANEerr(DANE_F_SET_TRUST_ANCHOR, ERR_R_MALLOC_FAILURE);
660 /* Shallow free the duplicated input untrusted chain. */
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.
668 if(matched == 0 && cert)
669 matched = ta_signed(dane, cert, depth);
675 check_end_entity(X509_STORE_CTX *ctx, ssl_dane *dane, X509 *cert)
679 matched = match(dane->selectors[SSL_DANE_USAGE_FIXED_LEAF], cert, 0);
682 if( (ctx->chain = sk_X509_new_null())
683 && sk_X509_push(ctx->chain, cert))
684 CRYPTO_add(&cert->references, 1, CRYPTO_LOCK_X509);
687 DANEerr(DANE_F_CHECK_END_ENTITY, ERR_R_MALLOC_FAILURE);
694 match_name(const char *certid, ssl_dane *dane)
696 int multi = dane->multi;
697 dane_host_list hosts;
699 for(hosts = dane->hosts; hosts; hosts = hosts->next)
701 int match_subdomain = 0;
702 const char *domain = hosts->value;
707 if(*domain == '.' && domain[1] != '\0')
714 * Sub-domain match: certid is any sub-domain of hostname.
717 if( (idlen = strlen(certid)) > (domlen = strlen(domain)) + 1
718 && certid[idlen - domlen - 1] == '.'
719 && !strcasecmp(certid + (idlen - domlen), domain))
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.
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))
740 check_name(char *name, int len)
742 char *cp = name + len;
744 while(len > 0 && !*--cp)
745 --len; /* Ignore trailing NULs */
748 for(cp = name; *cp; cp++)
751 if (!((c >= 'a' && c <= 'z') ||
752 (c >= '0' && c <= '9') ||
753 (c >= 'A' && c <= 'Z') ||
754 (c == '.' || c == '-') ||
756 return 0; /* Only LDH, '.' and '*' */
758 if(cp - name != len) /* Guard against internal NULs */
764 parse_dns_name(const GENERAL_NAME *gn)
766 if(gn->type != GEN_DNS)
768 if(ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
770 return check_name((char *) ASN1_STRING_data(gn->d.ia5),
771 ASN1_STRING_length(gn->d.ia5));
775 parse_subject_name(X509 *cert)
777 X509_NAME *name = X509_get_subject_name(cert);
778 X509_NAME_ENTRY *entry;
779 ASN1_STRING *entry_str;
780 unsigned char *namebuf;
781 int nid = NID_commonName;
785 if(!name || (i = X509_NAME_get_index_by_NID(name, nid, -1)) < 0)
787 if(!(entry = X509_NAME_get_entry(name, i)))
789 if(!(entry_str = X509_NAME_ENTRY_get_data(entry)))
792 if((len = ASN1_STRING_to_UTF8(&namebuf, entry_str)) < 0)
794 if(len <= 0 || check_name((char *) namebuf, len) == 0)
796 OPENSSL_free(namebuf);
799 return (char *) namebuf;
803 name_check(ssl_dane *dane, X509 *cert)
806 BOOL got_altname = FALSE;
809 gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
812 int n = sk_GENERAL_NAME_num(gens);
815 for(i = 0; i < n; ++i)
817 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, i);
820 if(gn->type != GEN_DNS)
823 certid = parse_dns_name(gn);
824 if(certid && *certid)
826 if((matched = match_name(certid, dane)) == 0)
828 if(!(dane->mhost = OPENSSL_strdup(certid)))
833 GENERAL_NAMES_free(gens);
837 * XXX: Should the subjectName be skipped when *any* altnames are present,
838 * or only when DNS altnames are present?
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 */
850 verify_chain(X509_STORE_CTX *ctx)
852 dane_selector_list issuer_rrs;
853 dane_selector_list leaf_rrs;
854 int (*cb)(int, X509_STORE_CTX *) = ctx->verify_cb;
855 int ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
856 SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
857 ssl_dane *dane = SSL_get_ex_data(ssl, dane_idx);
858 X509 *cert = ctx->cert; /* XXX: accessor? */
860 int chain_length = sk_X509_num(ctx->chain);
862 issuer_rrs = dane->selectors[SSL_DANE_USAGE_LIMIT_ISSUER];
863 leaf_rrs = dane->selectors[SSL_DANE_USAGE_LIMIT_LEAF];
864 ctx->verify = dane->verify;
866 if((matched = name_check(dane, cert)) < 0)
868 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
874 ctx->error_depth = 0;
875 ctx->current_cert = cert;
876 X509_STORE_CTX_set_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH);
883 * Satisfy at least one usage 0 or 1 constraint, unless we've already
884 * matched a usage 2 trust anchor.
886 * XXX: internal_verify() doesn't callback with top certs that are not
887 * self-issued. This should be fixed in a future OpenSSL.
889 if(dane->roots && sk_X509_num(dane->roots))
891 #ifndef NO_CALLBACK_WORKAROUND
892 X509 *top = sk_X509_value(ctx->chain, dane->depth);
894 if(X509_check_issued(top, top) != X509_V_OK)
896 ctx->error_depth = dane->depth;
897 ctx->current_cert = top;
902 /* Pop synthetic trust-anchor ancestors off the chain! */
903 while (--chain_length > dane->depth)
904 X509_free(sk_X509_pop(ctx->chain));
906 else if(issuer_rrs || leaf_rrs)
908 int n = chain_length;
911 * Check for an EE match, then a CA match at depths > 0, and
912 * finally, if the EE cert is self-issued, for a depth 0 CA match.
915 matched = match(leaf_rrs, cert, 0);
916 while(!matched && issuer_rrs && --n >= 0)
918 X509 *xn = sk_X509_value(ctx->chain, n);
920 if(n > 0 || X509_check_issued(xn, xn) == X509_V_OK)
921 matched = match(issuer_rrs, xn, n);
926 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
932 ctx->current_cert = cert;
933 ctx->error_depth = 0;
934 X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_UNTRUSTED);
940 return ctx->verify(ctx);
944 verify_cert(X509_STORE_CTX *ctx, void *unused_ctx)
946 static int ssl_idx = -1;
949 int (*cb)(int, X509_STORE_CTX *) = ctx->verify_cb;
951 X509 *cert = ctx->cert; /* XXX: accessor? */
954 ssl_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
957 DANEerr(DANE_F_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
961 ssl = X509_STORE_CTX_get_ex_data(ctx, ssl_idx);
962 if(!(dane = SSL_get_ex_data(ssl, dane_idx)) || !cert)
963 return X509_verify_cert(ctx);
965 if(dane->selectors[SSL_DANE_USAGE_FIXED_LEAF])
967 if((matched = check_end_entity(ctx, dane, cert)) > 0)
969 ctx->error_depth = 0;
970 ctx->current_cert = cert;
975 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
980 if(dane->selectors[SSL_DANE_USAGE_TRUSTED_CA])
982 if((matched = set_trust_anchor(ctx, dane, cert)) < 0)
984 X509_STORE_CTX_set_error(ctx, X509_V_ERR_OUT_OF_MEM);
990 * Check that setting the untrusted chain updates the expected
991 * structure member at the expected offset.
993 X509_STORE_CTX_trusted_stack(ctx, dane->roots);
994 X509_STORE_CTX_set_chain(ctx, dane->chain);
995 OPENSSL_assert(ctx->untrusted == dane->chain);
1000 * Name checks and usage 0/1 constraint enforcement are delayed until
1001 * X509_verify_cert() builds the full chain and calls our verify_chain()
1004 dane->verify = ctx->verify;
1005 ctx->verify = verify_chain;
1007 return X509_verify_cert(ctx);
1011 list_alloc(size_t vsize)
1013 void *value = (void *) OPENSSL_malloc(vsize);
1018 DANEerr(DANE_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1021 if(!(l = (dane_list) OPENSSL_malloc(sizeof(*l))))
1023 OPENSSL_free(value);
1024 DANEerr(DANE_F_LIST_ALLOC, ERR_R_MALLOC_FAILURE);
1033 list_free(void *list, void (*f)(void *))
1038 for(head = (dane_list) list; head; head = next)
1041 if (f && head->value)
1048 dane_mtype_free(void *p)
1050 list_free(((dane_mtype) p)->data, OPENSSL_freeFunc);
1055 dane_selector_free(void *p)
1057 list_free(((dane_selector) p)->mtype, dane_mtype_free);
1065 Tidy up once the connection is finished with.
1068 ssl The ssl connection handle
1070 => Before calling SSL_free()
1071 tls_close() and tls_getc() [the error path] are the obvious places.
1072 Could we do it earlier - right after verification? In tls_client_start()
1073 right after SSL_connect() returns, in that case.
1078 DANESSL_cleanup(SSL *ssl)
1083 if(dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1085 (void) SSL_set_ex_data(ssl, dane_idx, 0);
1088 list_free(dane->hosts, OPENSSL_freeFunc);
1090 OPENSSL_free(dane->mhost);
1091 for(u = 0; u <= SSL_DANE_USAGE_LAST; ++u)
1092 if(dane->selectors[u])
1093 list_free(dane->selectors[u], dane_selector_free);
1095 list_free(dane->pkeys, pkey_free);
1097 list_free(dane->certs, cert_free);
1099 sk_X509_pop_free(dane->roots, X509_free);
1101 sk_X509_pop_free(dane->chain, X509_free);
1105 static dane_host_list
1106 host_list_init(const char **src)
1108 dane_host_list head = NULL;
1112 dane_host_list elem = (dane_host_list) OPENSSL_malloc(sizeof(*elem));
1115 list_free(head, OPENSSL_freeFunc);
1118 elem->value = OPENSSL_strdup(*src++);
1119 LINSERT(head, elem);
1129 Call this for each TLSA record found for the target, after the
1130 DANE setup has been done on the ssl connection handle.
1133 ssl Connection handle
1134 usage TLSA record field
1135 selector TLSA record field
1136 mdname ??? message digest name?
1137 data ??? TLSA record megalump?
1147 DANESSL_add_tlsa(SSL *ssl, uint8_t usage, uint8_t selector, const char *mdname,
1148 unsigned const char *data, size_t dlen)
1151 dane_selector_list s = 0;
1152 dane_mtype_list m = 0;
1153 dane_data_list d = 0;
1154 dane_cert_list xlist = 0;
1155 dane_pkey_list klist = 0;
1156 const EVP_MD *md = 0;
1158 if(dane_idx < 0 || !(dane = SSL_get_ex_data(ssl, dane_idx)))
1160 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_DANE_INIT);
1164 if(usage > SSL_DANE_USAGE_LAST)
1166 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_USAGE);
1169 if(selector > SSL_DANE_SELECTOR_LAST)
1171 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_SELECTOR);
1174 if(mdname && !(md = EVP_get_digestbyname(mdname)))
1176 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_DIGEST);
1181 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_NULL_DATA);
1184 if(mdname && dlen != EVP_MD_size(md))
1186 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_DATA_LENGTH);
1194 const unsigned char *p = data;
1196 #define xklistinit(lvar, ltype, var, freeFunc) do { \
1197 (lvar) = (ltype) OPENSSL_malloc(sizeof(*(lvar))); \
1199 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, ERR_R_MALLOC_FAILURE); \
1204 lvar->value = var; \
1206 #define xkfreeret(ret) do { \
1207 if (xlist) list_free(xlist, cert_free); \
1208 if (klist) list_free(klist, pkey_free); \
1214 case SSL_DANE_SELECTOR_CERT:
1215 if(!d2i_X509(&x, &p, dlen) || dlen != p - data)
1219 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_CERT);
1222 k = X509_get_pubkey(x);
1227 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_CERT_PKEY);
1230 if(usage == SSL_DANE_USAGE_TRUSTED_CA)
1231 xklistinit(xlist, dane_cert_list, x, X509_free);
1234 case SSL_DANE_SELECTOR_SPKI:
1235 if(!d2i_PUBKEY(&k, &p, dlen) || dlen != p - data)
1239 DANEerr(DANE_F_SSL_DANE_ADD_TLSA, DANE_R_BAD_PKEY);
1242 if(usage == SSL_DANE_USAGE_TRUSTED_CA)
1243 xklistinit(klist, dane_pkey_list, k, EVP_PKEY_free);
1248 /* Find insertion point and don't add duplicate elements. */
1249 for(s = dane->selectors[usage]; s; s = s->next)
1250 if(s->value->selector == selector)
1251 for(m = s->value->mtype; m; m = m->next)
1252 if(m->value->md == md)
1253 for(d = m->value->data; d; d = d->next)
1254 if( d->value->datalen == dlen
1255 && memcmp(d->value->data, data, dlen) == 0)
1258 if(!(d = (dane_data_list) list_alloc(sizeof(*d->value) + dlen)))
1260 d->value->datalen = dlen;
1261 memcpy(d->value->data, data, dlen);
1264 if(!(m = (dane_mtype_list) list_alloc(sizeof(*m->value))))
1266 list_free(d, OPENSSL_freeFunc);
1270 if((m->value->md = md) != 0)
1271 m->value->mdlen = dlen;
1274 if(!(s = (dane_selector_list) list_alloc(sizeof(*s->value))))
1276 list_free(m, dane_mtype_free);
1279 s->value->mtype = 0;
1280 s->value->selector = selector;
1281 LINSERT(dane->selectors[usage], s);
1283 LINSERT(s->value->mtype, m);
1285 LINSERT(m->value->data, d);
1288 LINSERT(dane->certs, xlist);
1290 LINSERT(dane->pkeys, klist);
1299 Call this once we have an ssl connection handle but before
1300 making the TLS connection.
1302 => In tls_client_start() after the call to SSL_new()
1303 and before the call to SSL_connect(). Exactly where
1304 probably does not matter.
1305 We probably want to keep our existing SNI handling;
1306 call this with NULL.
1309 ssl Connection handle
1310 sni_domain Optional peer server name
1311 hostnames ?? list of names - but what names?
1320 DANESSL_init(SSL *ssl, const char *sni_domain, const char **hostnames)
1324 #ifdef OPENSSL_INTERNAL
1325 SSL_CTX *sctx = SSL_get_SSL_CTX(ssl);
1327 if(sctx->app_verify_callback != verify_cert)
1329 DANEerr(DANE_F_SSL_DANE_INIT, DANE_R_SCTX_INIT);
1335 DANEerr(DANE_F_SSL_DANE_INIT, DANE_R_LIBRARY_INIT);
1340 if(sni_domain && !SSL_set_tlsext_host_name(ssl, sni_domain))
1343 if(!(dane = (ssl_dane *) OPENSSL_malloc(sizeof(ssl_dane))))
1345 DANEerr(DANE_F_SSL_DANE_INIT, ERR_R_MALLOC_FAILURE);
1348 if(!SSL_set_ex_data(ssl, dane_idx, dane))
1350 DANEerr(DANE_F_SSL_DANE_INIT, ERR_R_MALLOC_FAILURE);
1360 dane->mhost = 0; /* Future SSL control interface */
1361 dane->multi = 0; /* Future SSL control interface */
1364 for(i = 0; i <= SSL_DANE_USAGE_LAST; ++i)
1365 dane->selectors[i] = 0;
1367 if(hostnames && !(dane->hosts = host_list_init(hostnames)))
1369 DANEerr(DANE_F_SSL_DANE_INIT, ERR_R_MALLOC_FAILURE);
1370 DANESSL_cleanup(ssl);
1380 Call this once we have a context to work with, but
1381 before DANESSL_init()
1383 => in tls_client_start(), after tls_init() call gives us the ctx,
1384 if we decide we want to (policy) and can (TLSA records available)
1385 replacing (? what about fallback) everything from testing tls_verify_hosts
1386 down to just before calling SSL_new() for the conn handle.
1397 DANESSL_CTX_init(SSL_CTX *ctx)
1401 SSL_CTX_set_cert_verify_callback(ctx, verify_cert, 0);
1404 DANEerr(DANE_F_SSL_CTX_DANE_INIT, DANE_R_LIBRARY_INIT);
1409 init_once(volatile int *value, int (*init)(void), void (*postinit)(void))
1413 CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
1416 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1417 CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1427 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1429 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
1437 * Store library id in zeroth function slot, used to locate the library
1438 * name. This must be done before we load the error strings.
1440 #ifndef OPENSSL_NO_ERR
1441 dane_str_functs[0].error |= ERR_PACK(err_lib_dane, 0, 0);
1442 ERR_load_strings(err_lib_dane, dane_str_functs);
1443 ERR_load_strings(err_lib_dane, dane_str_reasons);
1447 * Register SHA-2 digests, if implemented and not already registered.
1449 #if defined(LN_sha256) && defined(NID_sha256) && !defined(OPENSSL_NO_SHA256)
1450 if(!EVP_get_digestbyname(LN_sha224)) EVP_add_digest(EVP_sha224());
1451 if(!EVP_get_digestbyname(LN_sha256)) EVP_add_digest(EVP_sha256());
1453 #if defined(LN_sha512) && defined(NID_sha512) && !defined(OPENSSL_NO_SHA512)
1454 if(!EVP_get_digestbyname(LN_sha384)) EVP_add_digest(EVP_sha384());
1455 if(!EVP_get_digestbyname(LN_sha512)) EVP_add_digest(EVP_sha512());
1459 * Register an SSL index for the connection-specific ssl_dane structure.
1460 * Using a separate index makes it possible to add DANE support to
1461 * existing OpenSSL releases that don't have a suitable pointer in the
1464 dane_idx = SSL_get_ex_new_index(0, 0, 0, 0, 0);
1471 Call this once. Probably early in startup will do; may need
1472 to be after SSL library init.
1477 DANESSL_library_init(void)
1479 if(err_lib_dane < 0)
1480 init_once(&err_lib_dane, ERR_get_next_error_library, dane_init);
1482 #if defined(LN_sha256)
1483 /* No DANE without SHA256 support */
1484 if(dane_idx >= 0 && EVP_get_digestbyname(LN_sha256) != 0)
1488 DANEerr(DANE_F_SSL_DANE_LIBRARY_INIT, DANE_R_DANE_SUPPORT);
1493 #endif /* OPENSSL_VERSION_NUMBER */