1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
63 #include "internal/cryptlib.h"
64 #include <openssl/crypto.h>
65 #include <openssl/lhash.h>
66 #include <openssl/buffer.h>
67 #include <openssl/evp.h>
68 #include <openssl/asn1.h>
69 #include <openssl/x509.h>
70 #include <openssl/x509v3.h>
71 #include <openssl/objects.h>
72 #include <internal/dane.h>
73 #include <internal/x509_int.h>
76 /* CRL score values */
78 /* No unhandled critical extensions */
80 #define CRL_SCORE_NOCRITICAL 0x100
82 /* certificate is within CRL scope */
84 #define CRL_SCORE_SCOPE 0x080
88 #define CRL_SCORE_TIME 0x040
90 /* Issuer name matches certificate */
92 #define CRL_SCORE_ISSUER_NAME 0x020
94 /* If this score or above CRL is probably valid */
96 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
98 /* CRL issuer is certificate issuer */
100 #define CRL_SCORE_ISSUER_CERT 0x018
102 /* CRL issuer is on certificate path */
104 #define CRL_SCORE_SAME_PATH 0x008
106 /* CRL issuer matches CRL AKID */
108 #define CRL_SCORE_AKID 0x004
110 /* Have a delta CRL with valid times */
112 #define CRL_SCORE_TIME_DELTA 0x002
114 static int build_chain(X509_STORE_CTX *ctx);
115 static int verify_chain(X509_STORE_CTX *ctx);
116 static int dane_verify(X509_STORE_CTX *ctx);
117 static int null_callback(int ok, X509_STORE_CTX *e);
118 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
119 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
120 static int check_chain_extensions(X509_STORE_CTX *ctx);
121 static int check_name_constraints(X509_STORE_CTX *ctx);
122 static int check_id(X509_STORE_CTX *ctx);
123 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
124 static int check_revocation(X509_STORE_CTX *ctx);
125 static int check_cert(X509_STORE_CTX *ctx);
126 static int check_policy(X509_STORE_CTX *ctx);
127 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
128 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
130 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
131 unsigned int *preasons, X509_CRL *crl, X509 *x);
132 static int get_crl_delta(X509_STORE_CTX *ctx,
133 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
134 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
135 int *pcrl_score, X509_CRL *base,
136 STACK_OF(X509_CRL) *crls);
137 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
139 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
140 unsigned int *preasons);
141 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
142 static int check_crl_chain(X509_STORE_CTX *ctx,
143 STACK_OF(X509) *cert_path,
144 STACK_OF(X509) *crl_path);
146 static int internal_verify(X509_STORE_CTX *ctx);
148 static int null_callback(int ok, X509_STORE_CTX *e)
153 /* Return 1 is a certificate is self signed */
154 static int cert_self_signed(X509 *x)
157 * FIXME: x509v3_cache_extensions() needs to detect more failures and not
158 * set EXFLAG_SET when that happens. Especially, if the failures are
159 * parse errors, rather than memory pressure!
161 X509_check_purpose(x, -1, 0);
162 if (x->ex_flags & EXFLAG_SS)
168 /* Given a certificate try and find an exact match in the store */
170 static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
172 STACK_OF(X509) *certs;
175 /* Lookup all certs with matching subject name */
176 certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
179 /* Look for exact match */
180 for (i = 0; i < sk_X509_num(certs); i++) {
181 xtmp = sk_X509_value(certs, i);
182 if (!X509_cmp(xtmp, x))
185 if (i < sk_X509_num(certs))
189 sk_X509_pop_free(certs, X509_free);
193 static int verify_chain(X509_STORE_CTX *ctx)
199 * Before either returning with an error, or continuing with CRL checks,
200 * instantiate chain public key parameters.
202 if ((ok = build_chain(ctx)) == 0 ||
203 (ok = check_chain_extensions(ctx)) == 0 ||
204 (ok = check_name_constraints(ctx)) == 0 ||
205 (ok = check_id(ctx)) == 0 || 1)
206 X509_get_pubkey_parameters(NULL, ctx->chain);
207 if (ok == 0 || (ok = ctx->check_revocation(ctx)) == 0)
210 err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
212 if (err != X509_V_OK) {
214 ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth);
215 if ((ok = ctx->verify_cb(0, ctx)) == 0)
219 /* Verify chain signatures and expiration times */
220 ok = (ctx->verify != NULL) ? ctx->verify(ctx) : internal_verify(ctx);
224 #ifndef OPENSSL_NO_RFC3779
225 /* RFC 3779 path validation, now that CRL check has been done */
226 if ((ok = v3_asid_validate_path(ctx)) == 0)
228 if ((ok = v3_addr_validate_path(ctx)) == 0)
232 /* If we get this far evaluate policies */
233 if (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)
234 ok = ctx->check_policy(ctx);
238 int X509_verify_cert(X509_STORE_CTX *ctx)
240 struct dane_st *dane = (struct dane_st *)ctx->dane;
242 if (ctx->cert == NULL) {
243 X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
247 if (ctx->chain != NULL) {
249 * This X509_STORE_CTX has already been used to verify a cert. We
250 * cannot do another one.
252 X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
257 * first we make sure the chain we are going to build is present and that
258 * the first entry is in place
260 if (((ctx->chain = sk_X509_new_null()) == NULL) ||
261 (!sk_X509_push(ctx->chain, ctx->cert))) {
262 X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
265 X509_up_ref(ctx->cert);
266 ctx->num_untrusted = 1;
269 * If dane->trecs is an empty stack, we'll fail, since the user enabled
270 * DANE. If none of the TLSA records were usable, and it makes sense to
271 * keep going with an unauthenticated handshake, they can handle that in
272 * the verify callback, or not set SSL_VERIFY_PEER.
274 if (DANETLS_ENABLED(dane))
275 return dane_verify(ctx);
276 return verify_chain(ctx);
280 * Given a STACK_OF(X509) find the issuer of cert (if any)
283 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
286 X509 *issuer, *rv = NULL;;
287 for (i = 0; i < sk_X509_num(sk); i++) {
288 issuer = sk_X509_value(sk, i);
289 if (ctx->check_issued(ctx, x, issuer)) {
291 if (x509_check_cert_time(ctx, rv, 1))
298 /* Given a possible certificate and issuer check them */
300 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
304 return cert_self_signed(x);
305 ret = X509_check_issued(issuer, x);
306 if (ret == X509_V_OK) {
309 /* Special case: single self signed certificate */
310 if (cert_self_signed(x) && sk_X509_num(ctx->chain) == 1)
312 for (i = 0; i < sk_X509_num(ctx->chain); i++) {
313 ch = sk_X509_value(ctx->chain, i);
314 if (ch == issuer || !X509_cmp(ch, issuer)) {
315 ret = X509_V_ERR_PATH_LOOP;
321 return (ret == X509_V_OK);
324 /* Alternative lookup method: look from a STACK stored in other_ctx */
326 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
328 *issuer = find_issuer(ctx, ctx->other_ctx, x);
330 X509_up_ref(*issuer);
336 static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx, X509_NAME *nm)
338 STACK_OF(X509) *sk = NULL;
341 for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
342 x = sk_X509_value(ctx->other_ctx, i);
343 if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
345 sk = sk_X509_new_null();
346 if (sk == NULL || sk_X509_push(sk, x) == 0) {
347 sk_X509_pop_free(sk, X509_free);
357 * Check EE or CA certificate purpose. For trusted certificates explicit local
358 * auxiliary trust can be used to override EKU-restrictions.
360 static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth,
363 int tr_ok = X509_TRUST_UNTRUSTED;
366 * For trusted certificates we want to see whether any auxiliary trust
367 * settings trump the purpose constraints.
369 * This is complicated by the fact that the trust ordinals in
370 * ctx->param->trust are entirely independent of the purpose ordinals in
371 * ctx->param->purpose!
373 * What connects them is their mutual initialization via calls from
374 * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets
375 * related values of both param->trust and param->purpose. It is however
376 * typically possible to infer associated trust values from a purpose value
377 * via the X509_PURPOSE API.
379 * Therefore, we can only check for trust overrides when the purpose we're
380 * checking is the same as ctx->param->purpose and ctx->param->trust is
383 if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
384 tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
387 case X509_TRUST_TRUSTED:
389 case X509_TRUST_REJECTED:
392 switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
398 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
404 ctx->error = X509_V_ERR_INVALID_PURPOSE;
405 ctx->error_depth = depth;
406 ctx->current_cert = x;
407 return ctx->verify_cb(0, ctx);
411 * Check a certificate chains extensions for consistency with the supplied
415 static int check_chain_extensions(X509_STORE_CTX *ctx)
417 int i, must_be_ca, plen = 0;
419 int proxy_path_length = 0;
421 int allow_proxy_certs;
422 int num = sk_X509_num(ctx->chain);
425 * must_be_ca can have 1 of 3 values:
426 * -1: we accept both CA and non-CA certificates, to allow direct
427 * use of self-signed certificates (which are marked as CA).
428 * 0: we only accept non-CA certificates. This is currently not
429 * used, but the possibility is present for future extensions.
430 * 1: we only accept CA certificates. This is currently used for
431 * all certificates in the chain except the leaf certificate.
435 /* CRL path validation */
437 allow_proxy_certs = 0;
438 purpose = X509_PURPOSE_CRL_SIGN;
441 ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
443 * A hack to keep people who don't want to modify their software
446 if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
447 allow_proxy_certs = 1;
448 purpose = ctx->param->purpose;
451 for (i = 0; i < num; i++) {
453 x = sk_X509_value(ctx->chain, i);
454 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
455 && (x->ex_flags & EXFLAG_CRITICAL)) {
456 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
457 ctx->error_depth = i;
458 ctx->current_cert = x;
459 if (!ctx->verify_cb(0, ctx))
462 if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
463 ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
464 ctx->error_depth = i;
465 ctx->current_cert = x;
466 if (!ctx->verify_cb(0, ctx))
469 ret = X509_check_ca(x);
470 switch (must_be_ca) {
472 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
473 && (ret != 1) && (ret != 0)) {
475 ctx->error = X509_V_ERR_INVALID_CA;
482 ctx->error = X509_V_ERR_INVALID_NON_CA;
488 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
491 ctx->error = X509_V_ERR_INVALID_CA;
497 ctx->error_depth = i;
498 ctx->current_cert = x;
499 if (!ctx->verify_cb(0, ctx))
503 if (!check_purpose(ctx, x, purpose, i, must_be_ca))
506 /* Check pathlen if not self issued */
507 if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
508 && (x->ex_pathlen != -1)
509 && (plen > (x->ex_pathlen + proxy_path_length + 1))) {
510 ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
511 ctx->error_depth = i;
512 ctx->current_cert = x;
513 if (!ctx->verify_cb(0, ctx))
516 /* Increment path length if not self issued */
517 if (!(x->ex_flags & EXFLAG_SI))
520 * If this certificate is a proxy certificate, the next certificate
521 * must be another proxy certificate or a EE certificate. If not,
522 * the next certificate must be a CA certificate.
524 if (x->ex_flags & EXFLAG_PROXY) {
525 if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
526 ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
527 ctx->error_depth = i;
528 ctx->current_cert = x;
529 if (!ctx->verify_cb(0, ctx))
540 static int check_name_constraints(X509_STORE_CTX *ctx)
544 /* Check name constraints for all certificates */
545 for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
546 x = sk_X509_value(ctx->chain, i);
547 /* Ignore self issued certs unless last in chain */
548 if (i && (x->ex_flags & EXFLAG_SI))
551 * Check against constraints for all certificates higher in chain
552 * including trust anchor. Trust anchor not strictly speaking needed
553 * but if it includes constraints it is to be assumed it expects them
556 for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
557 NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
559 rv = NAME_CONSTRAINTS_check(x, nc);
560 if (rv != X509_V_OK) {
562 ctx->error_depth = i;
563 ctx->current_cert = x;
564 if (!ctx->verify_cb(0, ctx))
573 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
575 ctx->error = errcode;
576 ctx->current_cert = ctx->cert;
577 ctx->error_depth = 0;
578 return ctx->verify_cb(0, ctx);
581 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
584 int n = sk_OPENSSL_STRING_num(vpm->hosts);
587 if (vpm->peername != NULL) {
588 OPENSSL_free(vpm->peername);
589 vpm->peername = NULL;
591 for (i = 0; i < n; ++i) {
592 name = sk_OPENSSL_STRING_value(vpm->hosts, i);
593 if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
599 static int check_id(X509_STORE_CTX *ctx)
601 X509_VERIFY_PARAM *vpm = ctx->param;
603 if (vpm->hosts && check_hosts(x, vpm) <= 0) {
604 if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
607 if (vpm->email && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) {
608 if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
611 if (vpm->ip && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) {
612 if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
618 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
623 struct dane_st *dane = (struct dane_st *)ctx->dane;
624 int num = sk_X509_num(ctx->chain);
628 * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2)
629 * match, we're done, otherwise we'll merely record the match depth.
631 if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) {
632 switch (trust = check_dane_issuer(ctx, num_untrusted)) {
633 case X509_TRUST_TRUSTED:
634 case X509_TRUST_REJECTED:
640 * Check trusted certificates in chain at depth num_untrusted and up.
641 * Note, that depths 0..num_untrusted-1 may also contain trusted
642 * certificates, but the caller is expected to have already checked those,
643 * and wants to incrementally check just any added since.
645 for (i = num_untrusted; i < num; i++) {
646 x = sk_X509_value(ctx->chain, i);
647 trust = X509_check_trust(x, ctx->param->trust, 0);
648 /* If explicitly trusted return trusted */
649 if (trust == X509_TRUST_TRUSTED)
651 if (trust == X509_TRUST_REJECTED)
656 * If we are looking at a trusted certificate, and accept partial chains,
657 * the chain is PKIX trusted.
659 if (num_untrusted < num) {
660 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
662 return X509_TRUST_UNTRUSTED;
665 if (num_untrusted == num && ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
667 * Last-resort call with no new trusted certificates, check the leaf
668 * for a direct trust store match.
671 x = sk_X509_value(ctx->chain, i);
672 mx = lookup_cert_match(ctx, x);
674 return X509_TRUST_UNTRUSTED;
677 * Check explicit auxiliary trust/reject settings. If none are set,
678 * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
680 trust = X509_check_trust(mx, ctx->param->trust, 0);
681 if (trust == X509_TRUST_REJECTED) {
686 /* Replace leaf with trusted match */
687 (void) sk_X509_set(ctx->chain, 0, mx);
689 ctx->num_untrusted = 0;
694 * If no trusted certs in chain at all return untrusted and allow
695 * standard (no issuer cert) etc errors to be indicated.
697 return X509_TRUST_UNTRUSTED;
700 ctx->error_depth = i;
701 ctx->current_cert = x;
702 ctx->error = X509_V_ERR_CERT_REJECTED;
703 ok = ctx->verify_cb(0, ctx);
705 return X509_TRUST_REJECTED;
706 return X509_TRUST_UNTRUSTED;
709 if (!DANETLS_ENABLED(dane))
710 return X509_TRUST_TRUSTED;
712 dane->pdpth = num_untrusted;
713 /* With DANE, PKIX alone is not trusted until we have both */
714 if (dane->mdpth >= 0)
715 return X509_TRUST_TRUSTED;
716 return X509_TRUST_UNTRUSTED;
719 static int check_revocation(X509_STORE_CTX *ctx)
721 int i = 0, last = 0, ok = 0;
722 if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
724 if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
725 last = sk_X509_num(ctx->chain) - 1;
727 /* If checking CRL paths this isn't the EE certificate */
732 for (i = 0; i <= last; i++) {
733 ctx->error_depth = i;
734 ok = check_cert(ctx);
741 static int check_cert(X509_STORE_CTX *ctx)
743 X509_CRL *crl = NULL, *dcrl = NULL;
745 int ok = 0, cnum = 0;
746 unsigned int last_reasons = 0;
747 cnum = ctx->error_depth;
748 x = sk_X509_value(ctx->chain, cnum);
749 ctx->current_cert = x;
750 ctx->current_issuer = NULL;
751 ctx->current_crl_score = 0;
752 ctx->current_reasons = 0;
753 while (ctx->current_reasons != CRLDP_ALL_REASONS) {
754 last_reasons = ctx->current_reasons;
755 /* Try to retrieve relevant CRL */
757 ok = ctx->get_crl(ctx, &crl, x);
759 ok = get_crl_delta(ctx, &crl, &dcrl, x);
761 * If error looking up CRL, nothing we can do except notify callback
764 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
765 ok = ctx->verify_cb(0, ctx);
768 ctx->current_crl = crl;
769 ok = ctx->check_crl(ctx, crl);
774 ok = ctx->check_crl(ctx, dcrl);
777 ok = ctx->cert_crl(ctx, dcrl, x);
783 /* Don't look in full CRL if delta reason is removefromCRL */
785 ok = ctx->cert_crl(ctx, crl, x);
795 * If reasons not updated we wont get anywhere by another iteration,
798 if (last_reasons == ctx->current_reasons) {
799 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
800 ok = ctx->verify_cb(0, ctx);
808 ctx->current_crl = NULL;
813 /* Check CRL times against values in X509_STORE_CTX */
815 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
820 ctx->current_crl = crl;
821 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
822 ptime = &ctx->param->check_time;
823 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
828 i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
832 ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
833 if (!ctx->verify_cb(0, ctx))
840 ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
841 if (!ctx->verify_cb(0, ctx))
845 if (X509_CRL_get_nextUpdate(crl)) {
846 i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
851 ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
852 if (!ctx->verify_cb(0, ctx))
855 /* Ignore expiry of base CRL is delta is valid */
856 if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
859 ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
860 if (!ctx->verify_cb(0, ctx))
866 ctx->current_crl = NULL;
871 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
872 X509 **pissuer, int *pscore, unsigned int *preasons,
873 STACK_OF(X509_CRL) *crls)
875 int i, crl_score, best_score = *pscore;
876 unsigned int reasons, best_reasons = 0;
877 X509 *x = ctx->current_cert;
878 X509_CRL *crl, *best_crl = NULL;
879 X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
881 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
882 crl = sk_X509_CRL_value(crls, i);
884 crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
886 if (crl_score > best_score) {
888 best_crl_issuer = crl_issuer;
889 best_score = crl_score;
890 best_reasons = reasons;
895 X509_CRL_free(*pcrl);
897 *pissuer = best_crl_issuer;
898 *pscore = best_score;
899 *preasons = best_reasons;
900 X509_CRL_up_ref(best_crl);
901 X509_CRL_free(*pdcrl);
903 get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
906 if (best_score >= CRL_SCORE_VALID)
913 * Compare two CRL extensions for delta checking purposes. They should be
914 * both present or both absent. If both present all fields must be identical.
917 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
919 ASN1_OCTET_STRING *exta, *extb;
921 i = X509_CRL_get_ext_by_NID(a, nid, -1);
923 /* Can't have multiple occurrences */
924 if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
926 exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
930 i = X509_CRL_get_ext_by_NID(b, nid, -1);
934 if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
936 extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
946 if (ASN1_OCTET_STRING_cmp(exta, extb))
952 /* See if a base and delta are compatible */
954 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
956 /* Delta CRL must be a delta */
957 if (!delta->base_crl_number)
959 /* Base must have a CRL number */
960 if (!base->crl_number)
962 /* Issuer names must match */
963 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
965 /* AKID and IDP must match */
966 if (!crl_extension_match(delta, base, NID_authority_key_identifier))
968 if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
970 /* Delta CRL base number must not exceed Full CRL number. */
971 if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
973 /* Delta CRL number must exceed full CRL number */
974 if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
980 * For a given base CRL find a delta... maybe extend to delta scoring or
981 * retrieve a chain of deltas...
984 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
985 X509_CRL *base, STACK_OF(X509_CRL) *crls)
989 if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
991 if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
993 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
994 delta = sk_X509_CRL_value(crls, i);
995 if (check_delta_base(delta, base)) {
996 if (check_crl_time(ctx, delta, 0))
997 *pscore |= CRL_SCORE_TIME_DELTA;
998 X509_CRL_up_ref(delta);
1007 * For a given CRL return how suitable it is for the supplied certificate
1008 * 'x'. The return value is a mask of several criteria. If the issuer is not
1009 * the certificate issuer this is returned in *pissuer. The reasons mask is
1010 * also used to determine if the CRL is suitable: if no new reasons the CRL
1011 * is rejected, otherwise reasons is updated.
1014 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1015 unsigned int *preasons, X509_CRL *crl, X509 *x)
1019 unsigned int tmp_reasons = *preasons, crl_reasons;
1021 /* First see if we can reject CRL straight away */
1023 /* Invalid IDP cannot be processed */
1024 if (crl->idp_flags & IDP_INVALID)
1026 /* Reason codes or indirect CRLs need extended CRL support */
1027 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1028 if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1030 } else if (crl->idp_flags & IDP_REASONS) {
1031 /* If no new reasons reject */
1032 if (!(crl->idp_reasons & ~tmp_reasons))
1035 /* Don't process deltas at this stage */
1036 else if (crl->base_crl_number)
1038 /* If issuer name doesn't match certificate need indirect CRL */
1039 if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1040 if (!(crl->idp_flags & IDP_INDIRECT))
1043 crl_score |= CRL_SCORE_ISSUER_NAME;
1045 if (!(crl->flags & EXFLAG_CRITICAL))
1046 crl_score |= CRL_SCORE_NOCRITICAL;
1049 if (check_crl_time(ctx, crl, 0))
1050 crl_score |= CRL_SCORE_TIME;
1052 /* Check authority key ID and locate certificate issuer */
1053 crl_akid_check(ctx, crl, pissuer, &crl_score);
1055 /* If we can't locate certificate issuer at this point forget it */
1057 if (!(crl_score & CRL_SCORE_AKID))
1060 /* Check cert for matching CRL distribution points */
1062 if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1063 /* If no new reasons reject */
1064 if (!(crl_reasons & ~tmp_reasons))
1066 tmp_reasons |= crl_reasons;
1067 crl_score |= CRL_SCORE_SCOPE;
1070 *preasons = tmp_reasons;
1076 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1077 X509 **pissuer, int *pcrl_score)
1079 X509 *crl_issuer = NULL;
1080 X509_NAME *cnm = X509_CRL_get_issuer(crl);
1081 int cidx = ctx->error_depth;
1084 if (cidx != sk_X509_num(ctx->chain) - 1)
1087 crl_issuer = sk_X509_value(ctx->chain, cidx);
1089 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1090 if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1091 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1092 *pissuer = crl_issuer;
1097 for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1098 crl_issuer = sk_X509_value(ctx->chain, cidx);
1099 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1101 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1102 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1103 *pissuer = crl_issuer;
1108 /* Anything else needs extended CRL support */
1110 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1114 * Otherwise the CRL issuer is not on the path. Look for it in the set of
1115 * untrusted certificates.
1117 for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1118 crl_issuer = sk_X509_value(ctx->untrusted, i);
1119 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1121 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1122 *pissuer = crl_issuer;
1123 *pcrl_score |= CRL_SCORE_AKID;
1130 * Check the path of a CRL issuer certificate. This creates a new
1131 * X509_STORE_CTX and populates it with most of the parameters from the
1132 * parent. This could be optimised somewhat since a lot of path checking will
1133 * be duplicated by the parent, but this will rarely be used in practice.
1136 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1138 X509_STORE_CTX crl_ctx;
1140 /* Don't allow recursive CRL path validation */
1143 if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
1146 crl_ctx.crls = ctx->crls;
1147 /* Copy verify params across */
1148 X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1150 crl_ctx.parent = ctx;
1151 crl_ctx.verify_cb = ctx->verify_cb;
1153 /* Verify CRL issuer */
1154 ret = X509_verify_cert(&crl_ctx);
1159 /* Check chain is acceptable */
1161 ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1163 X509_STORE_CTX_cleanup(&crl_ctx);
1168 * RFC3280 says nothing about the relationship between CRL path and
1169 * certificate path, which could lead to situations where a certificate could
1170 * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1171 * strict and states that the two paths must end in the same trust anchor,
1172 * though some discussions remain... until this is resolved we use the
1176 static int check_crl_chain(X509_STORE_CTX *ctx,
1177 STACK_OF(X509) *cert_path,
1178 STACK_OF(X509) *crl_path)
1180 X509 *cert_ta, *crl_ta;
1181 cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1182 crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1183 if (!X509_cmp(cert_ta, crl_ta))
1189 * Check for match between two dist point names: three separate cases.
1190 * 1. Both are relative names and compare X509_NAME types.
1191 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1192 * 3. Both are full names and compare two GENERAL_NAMES.
1193 * 4. One is NULL: automatic match.
1196 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1198 X509_NAME *nm = NULL;
1199 GENERAL_NAMES *gens = NULL;
1200 GENERAL_NAME *gena, *genb;
1207 /* Case 1: two X509_NAME */
1211 if (!X509_NAME_cmp(a->dpname, b->dpname))
1216 /* Case 2: set name and GENERAL_NAMES appropriately */
1218 gens = b->name.fullname;
1219 } else if (b->type == 1) {
1222 /* Case 2: set name and GENERAL_NAMES appropriately */
1223 gens = a->name.fullname;
1227 /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1229 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1230 gena = sk_GENERAL_NAME_value(gens, i);
1231 if (gena->type != GEN_DIRNAME)
1233 if (!X509_NAME_cmp(nm, gena->d.directoryName))
1239 /* Else case 3: two GENERAL_NAMES */
1241 for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1242 gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1243 for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1244 genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1245 if (!GENERAL_NAME_cmp(gena, genb))
1254 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1257 X509_NAME *nm = X509_CRL_get_issuer(crl);
1258 /* If no CRLissuer return is successful iff don't need a match */
1260 return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1261 for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1262 GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1263 if (gen->type != GEN_DIRNAME)
1265 if (!X509_NAME_cmp(gen->d.directoryName, nm))
1271 /* Check CRLDP and IDP */
1273 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1274 unsigned int *preasons)
1277 if (crl->idp_flags & IDP_ONLYATTR)
1279 if (x->ex_flags & EXFLAG_CA) {
1280 if (crl->idp_flags & IDP_ONLYUSER)
1283 if (crl->idp_flags & IDP_ONLYCA)
1286 *preasons = crl->idp_reasons;
1287 for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1288 DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1289 if (crldp_check_crlissuer(dp, crl, crl_score)) {
1290 if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1291 *preasons &= dp->dp_reasons;
1296 if ((!crl->idp || !crl->idp->distpoint)
1297 && (crl_score & CRL_SCORE_ISSUER_NAME))
1303 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1304 * to find a delta CRL too
1307 static int get_crl_delta(X509_STORE_CTX *ctx,
1308 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1311 X509 *issuer = NULL;
1313 unsigned int reasons;
1314 X509_CRL *crl = NULL, *dcrl = NULL;
1315 STACK_OF(X509_CRL) *skcrl;
1316 X509_NAME *nm = X509_get_issuer_name(x);
1317 reasons = ctx->current_reasons;
1318 ok = get_crl_sk(ctx, &crl, &dcrl,
1319 &issuer, &crl_score, &reasons, ctx->crls);
1324 /* Lookup CRLs from store */
1326 skcrl = ctx->lookup_crls(ctx, nm);
1328 /* If no CRLs found and a near match from get_crl_sk use that */
1332 get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1334 sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1338 /* If we got any kind of CRL use it and return success */
1340 ctx->current_issuer = issuer;
1341 ctx->current_crl_score = crl_score;
1342 ctx->current_reasons = reasons;
1351 /* Check CRL validity */
1352 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1354 X509 *issuer = NULL;
1355 EVP_PKEY *ikey = NULL;
1356 int ok = 0, chnum, cnum;
1357 cnum = ctx->error_depth;
1358 chnum = sk_X509_num(ctx->chain) - 1;
1359 /* if we have an alternative CRL issuer cert use that */
1360 if (ctx->current_issuer)
1361 issuer = ctx->current_issuer;
1364 * Else find CRL issuer: if not last certificate then issuer is next
1365 * certificate in chain.
1367 else if (cnum < chnum)
1368 issuer = sk_X509_value(ctx->chain, cnum + 1);
1370 issuer = sk_X509_value(ctx->chain, chnum);
1371 /* If not self signed, can't check signature */
1372 if (!ctx->check_issued(ctx, issuer, issuer)) {
1373 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1374 ok = ctx->verify_cb(0, ctx);
1382 * Skip most tests for deltas because they have already been done
1384 if (!crl->base_crl_number) {
1385 /* Check for cRLSign bit if keyUsage present */
1386 if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1387 !(issuer->ex_kusage & KU_CRL_SIGN)) {
1388 ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1389 ok = ctx->verify_cb(0, ctx);
1394 if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1395 ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1396 ok = ctx->verify_cb(0, ctx);
1401 if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1402 if (check_crl_path(ctx, ctx->current_issuer) <= 0) {
1403 ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1404 ok = ctx->verify_cb(0, ctx);
1410 if (crl->idp_flags & IDP_INVALID) {
1411 ctx->error = X509_V_ERR_INVALID_EXTENSION;
1412 ok = ctx->verify_cb(0, ctx);
1419 if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1420 ok = check_crl_time(ctx, crl, 1);
1425 /* Attempt to get issuer certificate public key */
1426 ikey = X509_get0_pubkey(issuer);
1429 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1430 ok = ctx->verify_cb(0, ctx);
1435 rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1436 if (rv != X509_V_OK) {
1438 ok = ctx->verify_cb(0, ctx);
1442 /* Verify CRL signature */
1443 if (X509_CRL_verify(crl, ikey) <= 0) {
1444 ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1445 ok = ctx->verify_cb(0, ctx);
1458 /* Check certificate against CRL */
1459 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1464 * The rules changed for this... previously if a CRL contained unhandled
1465 * critical extensions it could still be used to indicate a certificate
1466 * was revoked. This has since been changed since critical extension can
1467 * change the meaning of CRL entries.
1469 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
1470 && (crl->flags & EXFLAG_CRITICAL)) {
1471 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1472 ok = ctx->verify_cb(0, ctx);
1477 * Look for serial number of certificate in CRL If found make sure reason
1478 * is not removeFromCRL.
1480 if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1481 if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1483 ctx->error = X509_V_ERR_CERT_REVOKED;
1484 ok = ctx->verify_cb(0, ctx);
1492 static int check_policy(X509_STORE_CTX *ctx)
1499 * With DANE, the trust anchor might be a bare public key, not a
1500 * certificate! In that case our chain does not have the trust anchor
1501 * certificate as a top-most element. This comports well with RFC5280
1502 * chain verification, since there too, the trust anchor is not part of the
1503 * chain to be verified. In particular, X509_policy_check() does not look
1504 * at the TA cert, but assumes that it is present as the top-most chain
1505 * element. We therefore temporarily push a NULL cert onto the chain if it
1506 * was verified via a bare public key, and pop it off right after the
1507 * X509_policy_check() call.
1509 if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
1510 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1513 ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1514 ctx->param->policies, ctx->param->flags);
1515 if (ctx->bare_ta_signed)
1516 sk_X509_pop(ctx->chain);
1518 if (ret == X509_PCY_TREE_INTERNAL) {
1519 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1522 /* Invalid or inconsistent extensions */
1523 if (ret == X509_PCY_TREE_INVALID) {
1525 * Locate certificates with bad extensions and notify callback.
1529 for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1530 x = sk_X509_value(ctx->chain, i);
1531 if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1533 ctx->current_cert = x;
1534 ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1535 if (!ctx->verify_cb(0, ctx))
1540 if (ret == X509_PCY_TREE_FAILURE) {
1541 ctx->current_cert = NULL;
1542 ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1543 return ctx->verify_cb(0, ctx);
1545 if (ret != X509_PCY_TREE_VALID) {
1546 X509err(X509_F_CHECK_POLICY, ERR_R_INTERNAL_ERROR);
1550 if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1551 ctx->current_cert = NULL;
1552 ctx->error = X509_V_OK;
1553 if (!ctx->verify_cb(2, ctx))
1560 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet)
1565 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1566 ptime = &ctx->param->check_time;
1567 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1572 i = X509_cmp_time(X509_get_notBefore(x), ptime);
1576 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
1577 ctx->current_cert = x;
1578 if (!ctx->verify_cb(0, ctx))
1585 ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
1586 ctx->current_cert = x;
1587 if (!ctx->verify_cb(0, ctx))
1591 i = X509_cmp_time(X509_get_notAfter(x), ptime);
1595 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
1596 ctx->current_cert = x;
1597 if (!ctx->verify_cb(0, ctx))
1604 ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
1605 ctx->current_cert = x;
1606 if (!ctx->verify_cb(0, ctx))
1613 static int internal_verify(X509_STORE_CTX *ctx)
1617 EVP_PKEY *pkey = NULL;
1619 n = sk_X509_num(ctx->chain) - 1;
1620 ctx->error_depth = n;
1621 xi = sk_X509_value(ctx->chain, n);
1624 * With DANE-verified bare public key TA signatures, it remains only to
1625 * check the timestamps of the top certificate. We report the issuer as
1626 * NULL, since all we have is a bare key.
1628 if (ctx->bare_ta_signed) {
1634 if (ctx->check_issued(ctx, xi, xi))
1637 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1642 ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
1643 ctx->current_cert = xi;
1644 ok = ctx->verify_cb(0, ctx);
1648 ctx->error_depth = n;
1649 xs = sk_X509_value(ctx->chain, n);
1654 * Do not clear ctx->error=0, it must be "sticky", only the user's callback
1655 * is allowed to reset errors (at its own peril).
1658 ctx->error_depth = n;
1661 * Skip signature check for self signed certificates unless
1662 * explicitly asked for. It doesn't add any security and just wastes
1665 if (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)) {
1666 if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1667 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1668 ctx->current_cert = xi;
1669 ok = ctx->verify_cb(0, ctx);
1672 } else if (X509_verify(xs, pkey) <= 0) {
1673 ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1674 ctx->current_cert = xs;
1675 ok = ctx->verify_cb(0, ctx);
1682 ok = x509_check_cert_time(ctx, xs, 0);
1686 /* The last error (if any) is still in the error value */
1687 ctx->current_issuer = xi;
1688 ctx->current_cert = xs;
1689 ok = ctx->verify_cb(1, ctx);
1696 xs = sk_X509_value(ctx->chain, n);
1704 int X509_cmp_current_time(const ASN1_TIME *ctm)
1706 return X509_cmp_time(ctm, NULL);
1709 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1714 char buff1[24], buff2[24], *p;
1715 int i, j, remaining;
1718 remaining = ctm->length;
1719 str = (char *)ctm->data;
1721 * Note that the following (historical) code allows much more slack in the
1722 * time format than RFC5280. In RFC5280, the representation is fixed:
1723 * UTCTime: YYMMDDHHMMSSZ
1724 * GeneralizedTime: YYYYMMDDHHMMSSZ
1726 if (ctm->type == V_ASN1_UTCTIME) {
1727 /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1728 int min_length = sizeof("YYMMDDHHMMZ") - 1;
1729 int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1730 if (remaining < min_length || remaining > max_length)
1737 /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1738 int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1739 int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1740 if (remaining < min_length || remaining > max_length)
1748 if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1759 * Skip any (up to three) fractional seconds...
1760 * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1761 * Can we just kill them altogether?
1763 if (remaining && *str == '.') {
1766 for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1767 if (*str < '0' || *str > '9')
1776 /* We now need either a terminating 'Z' or an offset. */
1785 if ((*str != '+') && (*str != '-'))
1787 /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1790 if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1791 str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1793 offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1794 offset += (str[3] - '0') * 10 + (str[4] - '0');
1798 atm.type = ctm->type;
1800 atm.length = sizeof(buff2);
1801 atm.data = (unsigned char *)buff2;
1803 if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1806 if (ctm->type == V_ASN1_UTCTIME) {
1807 i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1809 i += 100; /* cf. RFC 2459 */
1810 j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1819 i = strcmp(buff1, buff2);
1820 if (i == 0) /* wait a second then return younger :-) */
1826 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1828 return X509_time_adj(s, adj, NULL);
1831 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1833 return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1836 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1837 int offset_day, long offset_sec, time_t *in_tm)
1846 if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1847 if (s->type == V_ASN1_UTCTIME)
1848 return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1849 if (s->type == V_ASN1_GENERALIZEDTIME)
1850 return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1852 return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1855 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1857 EVP_PKEY *ktmp = NULL, *ktmp2;
1860 if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1863 for (i = 0; i < sk_X509_num(chain); i++) {
1864 ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1866 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1867 X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1870 if (!EVP_PKEY_missing_parameters(ktmp))
1874 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1875 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1879 /* first, populate the other certs */
1880 for (j = i - 1; j >= 0; j--) {
1881 ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1882 EVP_PKEY_copy_parameters(ktmp2, ktmp);
1886 EVP_PKEY_copy_parameters(pkey, ktmp);
1890 /* Make a delta CRL as the diff between two full CRLs */
1892 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1893 EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1895 X509_CRL *crl = NULL;
1897 STACK_OF(X509_REVOKED) *revs = NULL;
1898 /* CRLs can't be delta already */
1899 if (base->base_crl_number || newer->base_crl_number) {
1900 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1903 /* Base and new CRL must have a CRL number */
1904 if (!base->crl_number || !newer->crl_number) {
1905 X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1908 /* Issuer names must match */
1909 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
1910 X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
1913 /* AKID and IDP must match */
1914 if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1915 X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
1918 if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1919 X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
1922 /* Newer CRL number must exceed full CRL number */
1923 if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1924 X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
1927 /* CRLs must verify */
1928 if (skey && (X509_CRL_verify(base, skey) <= 0 ||
1929 X509_CRL_verify(newer, skey) <= 0)) {
1930 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
1933 /* Create new CRL */
1934 crl = X509_CRL_new();
1935 if (crl == NULL || !X509_CRL_set_version(crl, 1))
1937 /* Set issuer name */
1938 if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
1941 if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer)))
1943 if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer)))
1946 /* Set base CRL number: must be critical */
1948 if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
1952 * Copy extensions across from newest CRL to delta: this will set CRL
1953 * number to correct value too.
1956 for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
1957 X509_EXTENSION *ext;
1958 ext = X509_CRL_get_ext(newer, i);
1959 if (!X509_CRL_add_ext(crl, ext, -1))
1963 /* Go through revoked entries, copying as needed */
1965 revs = X509_CRL_get_REVOKED(newer);
1967 for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
1968 X509_REVOKED *rvn, *rvtmp;
1969 rvn = sk_X509_REVOKED_value(revs, i);
1971 * Add only if not also in base. TODO: need something cleverer here
1972 * for some more complex CRLs covering multiple CAs.
1974 if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
1975 rvtmp = X509_REVOKED_dup(rvn);
1978 if (!X509_CRL_add0_revoked(crl, rvtmp)) {
1979 X509_REVOKED_free(rvtmp);
1984 /* TODO: optionally prune deleted entries */
1986 if (skey && md && !X509_CRL_sign(crl, skey, md))
1992 X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
1997 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1999 return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2002 void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
2004 return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2007 int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
2012 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2017 int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
2019 return ctx->error_depth;
2022 X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
2024 return ctx->current_cert;
2027 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
2032 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
2036 return X509_chain_up_ref(ctx->chain);
2039 X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
2041 return ctx->current_issuer;
2044 X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
2046 return ctx->current_crl;
2049 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
2054 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2059 void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2061 ctx->untrusted = sk;
2064 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2069 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2072 * XXX: Why isn't this function always used to set the associated trust?
2073 * Should there even be a VPM->trust field at all? Or should the trust
2074 * always be inferred from the purpose by X509_STORE_CTX_init().
2076 return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2079 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2082 * XXX: See above, this function would only be needed when the default
2083 * trust for the purpose needs an override in a corner case.
2085 return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2089 * This function is used to set the X509_STORE_CTX purpose and trust values.
2090 * This is intended to be used when another structure has its own trust and
2091 * purpose values which (if set) will be inherited by the ctx. If they aren't
2092 * set then we will usually have a default purpose in mind which should then
2093 * be used to set the trust value. An example of this is SSL use: an SSL
2094 * structure will have its own purpose and trust settings which the
2095 * application can set: if they aren't set then we use the default of SSL
2099 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2100 int purpose, int trust)
2103 /* If purpose not set use default */
2105 purpose = def_purpose;
2106 /* If we have a purpose then check it is valid */
2109 idx = X509_PURPOSE_get_by_id(purpose);
2111 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2112 X509_R_UNKNOWN_PURPOSE_ID);
2115 ptmp = X509_PURPOSE_get0(idx);
2116 if (ptmp->trust == X509_TRUST_DEFAULT) {
2117 idx = X509_PURPOSE_get_by_id(def_purpose);
2119 * XXX: In the two callers above def_purpose is always 0, which is
2120 * not a known value, so idx will always be -1. How is the
2121 * X509_TRUST_DEFAULT case actually supposed to be handled?
2124 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2125 X509_R_UNKNOWN_PURPOSE_ID);
2128 ptmp = X509_PURPOSE_get0(idx);
2130 /* If trust not set then get from purpose default */
2132 trust = ptmp->trust;
2135 idx = X509_TRUST_get_by_id(trust);
2137 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2138 X509_R_UNKNOWN_TRUST_ID);
2143 if (purpose && !ctx->param->purpose)
2144 ctx->param->purpose = purpose;
2145 if (trust && !ctx->param->trust)
2146 ctx->param->trust = trust;
2150 X509_STORE_CTX *X509_STORE_CTX_new(void)
2152 X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2155 X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
2161 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2165 X509_STORE_CTX_cleanup(ctx);
2169 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2170 STACK_OF(X509) *chain)
2175 ctx->current_method = 0;
2177 ctx->untrusted = chain;
2179 ctx->num_untrusted = 0;
2180 ctx->other_ctx = NULL;
2184 ctx->explicit_policy = 0;
2185 ctx->error_depth = 0;
2186 ctx->current_cert = NULL;
2187 ctx->current_issuer = NULL;
2188 ctx->current_crl = NULL;
2189 ctx->current_crl_score = 0;
2190 ctx->current_reasons = 0;
2194 ctx->bare_ta_signed = 0;
2195 /* Zero ex_data to make sure we're cleanup-safe */
2196 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2199 ctx->verify_cb = store->verify_cb;
2200 /* Seems to always be 0 in OpenSSL, else must be idempotent */
2201 ctx->cleanup = store->cleanup;
2205 if (store && store->check_issued)
2206 ctx->check_issued = store->check_issued;
2208 ctx->check_issued = check_issued;
2210 if (store && store->get_issuer)
2211 ctx->get_issuer = store->get_issuer;
2213 ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2215 if (store && store->verify_cb)
2216 ctx->verify_cb = store->verify_cb;
2218 ctx->verify_cb = null_callback;
2220 if (store && store->verify)
2221 ctx->verify = store->verify;
2223 ctx->verify = internal_verify;
2225 if (store && store->check_revocation)
2226 ctx->check_revocation = store->check_revocation;
2228 ctx->check_revocation = check_revocation;
2230 if (store && store->get_crl)
2231 ctx->get_crl = store->get_crl;
2233 ctx->get_crl = NULL;
2235 if (store && store->check_crl)
2236 ctx->check_crl = store->check_crl;
2238 ctx->check_crl = check_crl;
2240 if (store && store->cert_crl)
2241 ctx->cert_crl = store->cert_crl;
2243 ctx->cert_crl = cert_crl;
2245 if (store && store->lookup_certs)
2246 ctx->lookup_certs = store->lookup_certs;
2248 ctx->lookup_certs = X509_STORE_get1_certs;
2250 if (store && store->lookup_crls)
2251 ctx->lookup_crls = store->lookup_crls;
2253 ctx->lookup_crls = X509_STORE_get1_crls;
2255 ctx->check_policy = check_policy;
2257 ctx->param = X509_VERIFY_PARAM_new();
2258 if (ctx->param == NULL) {
2259 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2264 * Inherit callbacks and flags from X509_STORE if not set use defaults.
2267 ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2269 ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2272 ret = X509_VERIFY_PARAM_inherit(ctx->param,
2273 X509_VERIFY_PARAM_lookup("default"));
2276 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2281 * XXX: For now, continue to inherit trust from VPM, but infer from the
2282 * purpose if this still yields the default value.
2284 if (ctx->param->trust == X509_TRUST_DEFAULT) {
2285 int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2286 X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2289 ctx->param->trust = X509_PURPOSE_get_trust(xp);
2292 if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2295 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2299 * On error clean up allocated storage, if the store context was not
2300 * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2302 X509_STORE_CTX_cleanup(ctx);
2307 * Set alternative lookup method: just a STACK of trusted certificates. This
2308 * avoids X509_STORE nastiness where it isn't needed.
2311 void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2313 ctx->other_ctx = sk;
2314 ctx->get_issuer = get_issuer_sk;
2315 ctx->lookup_certs = lookup_certs_sk;
2318 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2321 * We need to be idempotent because, unfortunately, free() also calls
2322 * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2323 * calls cleanup() for the same object twice! Thus we must zero the
2324 * pointers below after they're freed!
2326 /* Seems to always be 0 in OpenSSL, do this at most once. */
2327 if (ctx->cleanup != NULL) {
2329 ctx->cleanup = NULL;
2331 if (ctx->param != NULL) {
2332 if (ctx->parent == NULL)
2333 X509_VERIFY_PARAM_free(ctx->param);
2336 X509_policy_tree_free(ctx->tree);
2338 sk_X509_pop_free(ctx->chain, X509_free);
2340 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2341 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2344 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2346 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2349 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2351 X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2354 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2357 X509_VERIFY_PARAM_set_time(ctx->param, t);
2360 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2361 int (*verify_cb) (int, X509_STORE_CTX *))
2363 ctx->verify_cb = verify_cb;
2366 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2371 int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2373 return ctx->explicit_policy;
2376 int X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx)
2378 return ctx->num_untrusted;
2381 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2383 const X509_VERIFY_PARAM *param;
2384 param = X509_VERIFY_PARAM_lookup(name);
2387 return X509_VERIFY_PARAM_inherit(ctx->param, param);
2390 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2395 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2397 X509_VERIFY_PARAM_free(ctx->param);
2401 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, struct dane_st *dane)
2406 static unsigned char *dane_i2d(
2409 unsigned int *i2dlen)
2411 unsigned char *buf = NULL;
2415 * Extract ASN.1 DER form of certificate or public key.
2418 case DANETLS_SELECTOR_CERT:
2419 len = i2d_X509(cert, &buf);
2421 case DANETLS_SELECTOR_SPKI:
2422 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2425 X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2429 if (len < 0 || buf == NULL) {
2430 X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2434 *i2dlen = (unsigned int)len;
2438 #define DANETLS_NONE 256 /* impossible uint8_t */
2440 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2442 struct dane_st *dane = (struct dane_st *)ctx->dane;
2443 unsigned usage = DANETLS_NONE;
2444 unsigned selector = DANETLS_NONE;
2445 unsigned ordinal = DANETLS_NONE;
2446 unsigned mtype = DANETLS_NONE;
2447 unsigned char *i2dbuf = NULL;
2448 unsigned int i2dlen = 0;
2449 unsigned char mdbuf[EVP_MAX_MD_SIZE];
2450 unsigned char *cmpbuf = NULL;
2451 unsigned int cmplen = 0;
2455 danetls_record *t = NULL;
2458 mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2461 * The trust store is not applicable with DANE-TA(2)
2463 if (depth >= ctx->num_untrusted)
2464 mask &= DANETLS_PKIX_MASK;
2467 * If we've previously matched a PKIX-?? record, no need to test any
2468 * further PKIX-?? records, it remains to just build the PKIX chain.
2469 * Had the match been a DANE-?? record, we'd be done already.
2471 if (dane->mdpth >= 0)
2472 mask &= ~DANETLS_PKIX_MASK;
2475 * https://tools.ietf.org/html/rfc7671#section-5.1
2476 * https://tools.ietf.org/html/rfc7671#section-5.2
2477 * https://tools.ietf.org/html/rfc7671#section-5.3
2478 * https://tools.ietf.org/html/rfc7671#section-5.4
2480 * We handle DANE-EE(3) records first as they require no chain building
2481 * and no expiration or hostname checks. We also process digests with
2482 * higher ordinals first and ignore lower priorities except Full(0) which
2483 * is always processed (last). If none match, we then process PKIX-EE(1).
2485 * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2486 * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2487 * priorities. See twin comment in ssl/ssl_lib.c.
2489 * We expect that most TLSA RRsets will have just a single usage, so we
2490 * don't go out of our way to cache multiple selector-specific i2d buffers
2491 * across usages, but if the selector happens to remain the same as switch
2492 * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2493 * records would result in us generating each of the certificate and public
2494 * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2495 * or multiple "3 0 1" records.
2497 * As soon as we find a match at any given depth, we stop, because either
2498 * we've matched a DANE-?? record and the peer is authenticated, or, after
2499 * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
2500 * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2502 recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2503 for (i = 0; matched == 0 && i < recnum; ++i) {
2504 t = sk_danetls_record_value(dane->trecs, i);
2505 if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2507 if (t->usage != usage) {
2510 /* Reset digest agility for each usage/selector pair */
2511 mtype = DANETLS_NONE;
2512 ordinal = dane->dctx->mdord[t->mtype];
2514 if (t->selector != selector) {
2515 selector = t->selector;
2517 /* Update per-selector state */
2518 OPENSSL_free(i2dbuf);
2519 i2dbuf = dane_i2d(cert, selector, &i2dlen);
2523 /* Reset digest agility for each usage/selector pair */
2524 mtype = DANETLS_NONE;
2525 ordinal = dane->dctx->mdord[t->mtype];
2526 } else if (t->mtype != DANETLS_MATCHING_FULL) {
2530 * <https://tools.ietf.org/html/rfc7671#section-9>
2532 * For a fixed selector, after processing all records with the
2533 * highest mtype ordinal, ignore all mtypes with lower ordinals
2534 * other than "Full".
2536 if (dane->dctx->mdord[t->mtype] < ordinal)
2541 * Each time we hit a (new selector or) mtype, re-compute the relevant
2542 * digest, more complex caching is not worth the code space.
2544 if (t->mtype != mtype) {
2545 const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2551 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2559 * Squirrel away the certificate and depth if we have a match. Any
2560 * DANE match is dispositive, but with PKIX we still need to build a
2563 if (cmplen == t->dlen &&
2564 memcmp(cmpbuf, t->data, cmplen) == 0) {
2565 if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2567 if (matched || dane->mdpth < 0) {
2568 dane->mdpth = depth;
2570 OPENSSL_free(dane->mcert);
2578 /* Clear the one-element DER cache */
2579 OPENSSL_free(i2dbuf);
2583 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2585 struct dane_st *dane = (struct dane_st *)ctx->dane;
2589 if (!DANETLS_HAS_TA(dane) || depth == 0)
2590 return X509_TRUST_UNTRUSTED;
2593 * Record any DANE trust anchor matches, for the first depth to test, if
2594 * there's one at that depth. (This'll be false for length 1 chains looking
2595 * for an exact match for the leaf certificate).
2597 cert = sk_X509_value(ctx->chain, depth);
2598 if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2599 return X509_TRUST_REJECTED;
2601 ctx->num_untrusted = depth - 1;
2602 return X509_TRUST_TRUSTED;
2605 return X509_TRUST_UNTRUSTED;
2608 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2610 struct dane_st *dane = (struct dane_st *)ctx->dane;
2612 int num = ctx->num_untrusted;
2613 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2614 int recnum = sk_danetls_record_num(dane->trecs);
2617 for (i = 0; i < recnum; ++i) {
2618 t = sk_danetls_record_value(dane->trecs, i);
2619 if (t->usage != DANETLS_USAGE_DANE_TA ||
2620 t->selector != DANETLS_SELECTOR_SPKI ||
2621 t->mtype != DANETLS_MATCHING_FULL ||
2622 X509_verify(cert, t->spki) <= 0)
2625 /* Clear any PKIX-?? matches that failed to extend to a full chain */
2626 X509_free(dane->mcert);
2629 /* Record match via a bare TA public key */
2630 ctx->bare_ta_signed = 1;
2631 dane->mdpth = num - 1;
2634 /* Prune any excess chain certificates */
2635 num = sk_X509_num(ctx->chain);
2636 for (; num > ctx->num_untrusted; --num)
2637 X509_free(sk_X509_pop(ctx->chain));
2639 return X509_TRUST_TRUSTED;
2642 return X509_TRUST_UNTRUSTED;
2645 static void dane_reset(struct dane_st *dane)
2648 * Reset state to verify another chain, or clear after failure.
2650 X509_free(dane->mcert);
2657 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
2659 int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
2661 if (err == X509_V_OK)
2663 ctx->current_cert = cert;
2664 ctx->error_depth = 0;
2666 return ctx->verify_cb(0, ctx);
2669 static int dane_verify(X509_STORE_CTX *ctx)
2671 X509 *cert = ctx->cert;
2672 struct dane_st *dane = (struct dane_st *)ctx->dane;
2678 matched = dane_match(ctx, ctx->cert, 0);
2679 done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2682 X509_get_pubkey_parameters(NULL, ctx->chain);
2685 if (!check_leaf_suiteb(ctx, cert))
2687 ctx->error_depth = 0;
2688 ctx->current_cert = cert;
2689 return ctx->verify_cb(1, ctx);
2693 ctx->error_depth = 0;
2694 ctx->current_cert = cert;
2695 ctx->error = X509_V_ERR_OUT_OF_MEM;
2700 /* Fail early, TA-based success is not possible */
2701 if (!check_leaf_suiteb(ctx, cert))
2703 ctx->current_cert = cert;
2704 ctx->error_depth = 0;
2705 ctx->error = X509_V_ERR_DANE_NO_MATCH;
2706 return ctx->verify_cb(0, ctx);
2710 * Chain verification for usages 0/1/2. TLSA record matching of depth > 0
2711 * certificates happens in-line with building the rest of the chain.
2713 return verify_chain(ctx);
2716 static int build_chain(X509_STORE_CTX *ctx)
2718 struct dane_st *dane = (struct dane_st *)ctx->dane;
2719 int num = sk_X509_num(ctx->chain);
2720 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2721 int ss = cert_self_signed(cert);
2722 STACK_OF(X509) *sktmp = NULL;
2723 unsigned int search;
2724 int may_trusted = 0;
2725 int may_alternate = 0;
2726 int trust = X509_TRUST_UNTRUSTED;
2727 int alt_untrusted = 0;
2732 /* Our chain starts with a single untrusted element. */
2733 OPENSSL_assert(num == 1 && ctx->num_untrusted == num);
2735 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
2736 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
2737 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
2739 * Set up search policy, untrusted if possible, trusted-first if enabled.
2740 * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2741 * trust_store, otherwise we might look there first. If not trusted-first,
2742 * and alternate chains are not disabled, try building an alternate chain
2743 * if no luck with untrusted first.
2745 search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2746 if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2747 if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2748 search |= S_DOTRUSTED;
2749 else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2755 * Shallow-copy the stack of untrusted certificates (with TLS, this is
2756 * typically the content of the peer's certificate message) so can make
2757 * multiple passes over it, while free to remove elements as we go.
2759 if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
2760 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2764 /* Include any untrusted full certificates from DNS */
2765 if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
2766 for (i = 0; i < sk_X509_num(dane->certs); ++i) {
2767 if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
2768 sk_X509_free(sktmp);
2769 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2776 * Still absurdly large, but arithmetically safe, a lower hard upper bound
2777 * might be reasonable.
2779 if (ctx->param->depth > INT_MAX/2)
2780 ctx->param->depth = INT_MAX/2;
2783 * Try to Extend the chain until we reach an ultimately trusted issuer.
2784 * Build chains up to one longer the limit, later fail if we hit the limit,
2785 * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
2787 depth = ctx->param->depth + 1;
2789 while (search != 0) {
2794 * Look in the trust store if enabled for first lookup, or we've run
2795 * out of untrusted issuers and search here is not disabled. When
2796 * we exceed the depth limit, we simulate absence of a match.
2798 if ((search & S_DOTRUSTED) != 0) {
2799 STACK_OF(X509) *hide = ctx->chain;
2801 i = num = sk_X509_num(ctx->chain);
2802 if ((search & S_DOALTERNATE) != 0) {
2804 * As high up the chain as we can, look for an alternative
2805 * trusted issuer of an untrusted certificate that currently
2806 * has an untrusted issuer. We use the alt_untrusted variable
2807 * to track how far up the chain we find the first match. It
2808 * is only if and when we find a match, that we prune the chain
2809 * and reset ctx->num_untrusted to the reduced count of
2810 * untrusted certificates. While we're searching for such a
2811 * match (which may never be found), it is neither safe nor
2812 * wise to preemptively modify either the chain or
2813 * ctx->num_untrusted.
2815 * Note, like ctx->num_untrusted, alt_untrusted is a count of
2816 * untrusted certificates, not a "depth".
2820 x = sk_X509_value(ctx->chain, i-1);
2822 /* Suppress duplicate suppression */
2824 ok = (depth < num) ? 0 : ctx->get_issuer(&xtmp, ctx, x);
2828 trust = X509_TRUST_REJECTED;
2835 * Alternative trusted issuer for a mid-chain untrusted cert?
2836 * Pop the untrusted cert's successors and retry. We might now
2837 * be able to complete a valid chain via the trust store. Note
2838 * that despite the current trust-store match we might still
2839 * fail complete the chain to a suitable trust-anchor, in which
2840 * case we may prune some more untrusted certificates and try
2841 * again. Thus the S_DOALTERNATE bit may yet be turned on
2842 * again with an even shorter untrusted chain!
2844 * If in the process we threw away our matching PKIX-TA trust
2845 * anchor, reset DANE trust. We might find a suitable trusted
2846 * certificate among the ones from the trust store.
2848 if ((search & S_DOALTERNATE) != 0) {
2849 OPENSSL_assert(num > i && i > 0 && ss == 0);
2850 search &= ~S_DOALTERNATE;
2851 for (; num > i; --num)
2852 X509_free(sk_X509_pop(ctx->chain));
2853 ctx->num_untrusted = num;
2855 if (DANETLS_ENABLED(dane) &&
2856 dane->mdpth >= ctx->num_untrusted) {
2858 X509_free(dane->mcert);
2861 if (DANETLS_ENABLED(dane) &&
2862 dane->pdpth >= ctx->num_untrusted)
2867 * Self-signed untrusted certificates get replaced by their
2868 * trusted matching issuer. Otherwise, grow the chain.
2871 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2873 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2874 trust = X509_TRUST_REJECTED;
2878 ss = cert_self_signed(x);
2879 } else if (num == ctx->num_untrusted) {
2881 * We have a self-signed certificate that has the same
2882 * subject name (and perhaps keyid and/or serial number) as
2883 * a trust-anchor. We must have an exact match to avoid
2884 * possible impersonation via key substitution etc.
2886 if (X509_cmp(x, xtmp) != 0) {
2887 /* Self-signed untrusted mimic. */
2892 ctx->num_untrusted = --num;
2893 (void) sk_X509_set(ctx->chain, num, x = xtmp);
2898 * We've added a new trusted certificate to the chain, recheck
2899 * trust. If not done, and not self-signed look deeper.
2900 * Whether or not we're doing "trusted first", we no longer
2901 * look for untrusted certificates from the peer's chain.
2903 * At this point ctx->num_trusted and num must reflect the
2904 * correct number of untrusted certificates, since the DANE
2905 * logic in check_trust() depends on distinguishing CAs from
2906 * "the wire" from CAs from the trust store. In particular, the
2907 * certificate at depth "num" should be the new trusted
2908 * certificate with ctx->num_untrusted <= num.
2911 OPENSSL_assert(ctx->num_untrusted <= num);
2912 search &= ~S_DOUNTRUSTED;
2913 switch (trust = check_trust(ctx, num)) {
2914 case X509_TRUST_TRUSTED:
2915 case X509_TRUST_REJECTED:
2925 * No dispositive decision, and either self-signed or no match, if
2926 * we were doing untrusted-first, and alt-chains are not disabled,
2927 * do that, by repeatedly losing one untrusted element at a time,
2928 * and trying to extend the shorted chain.
2930 if ((search & S_DOUNTRUSTED) == 0) {
2931 /* Continue search for a trusted issuer of a shorter chain? */
2932 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
2934 /* Still no luck and no fallbacks left? */
2935 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
2936 ctx->num_untrusted < 2)
2938 /* Search for a trusted issuer of a shorter chain */
2939 search |= S_DOALTERNATE;
2940 alt_untrusted = ctx->num_untrusted - 1;
2946 * Extend chain with peer-provided certificates
2948 if ((search & S_DOUNTRUSTED) != 0) {
2949 num = sk_X509_num(ctx->chain);
2950 OPENSSL_assert(num == ctx->num_untrusted);
2951 x = sk_X509_value(ctx->chain, num-1);
2952 xtmp = (depth < num) ? NULL : find_issuer(ctx, sktmp, x);
2955 * Once we run out of untrusted issuers, we stop looking for more
2956 * and start looking only in the trust store if enabled.
2959 search &= ~S_DOUNTRUSTED;
2961 search |= S_DOTRUSTED;
2965 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2966 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2967 trust = X509_TRUST_REJECTED;
2972 ++ctx->num_untrusted;
2973 ss = cert_self_signed(xtmp);
2976 * Not strictly necessary, but saves cycles looking at the same
2977 * certificates over and over.
2979 (void) sk_X509_delete_ptr(sktmp, x);
2982 * Check for DANE-TA trust of the topmost untrusted certificate.
2984 switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
2985 case X509_TRUST_TRUSTED:
2986 case X509_TRUST_REJECTED:
2992 sk_X509_free(sktmp);
2995 * Last chance to make a trusted chain, either bare DANE-TA public-key
2996 * signers, or else direct leaf PKIX trust.
2998 num = sk_X509_num(ctx->chain);
3000 if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3001 trust = check_dane_pkeys(ctx);
3002 if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3003 trust = check_trust(ctx, num);
3007 case X509_TRUST_TRUSTED:
3009 case X509_TRUST_REJECTED:
3011 case X509_TRUST_UNTRUSTED:
3013 num = sk_X509_num(ctx->chain);
3014 ctx->current_cert = sk_X509_value(ctx->chain, num - 1);
3015 ctx->error_depth = num-1;
3017 ctx->error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
3018 else if (DANETLS_ENABLED(dane) &&
3019 (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
3020 ctx->error = X509_V_ERR_DANE_NO_MATCH;
3021 else if (ss && sk_X509_num(ctx->chain) == 1)
3022 ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
3024 ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
3025 else if (ctx->num_untrusted == num)
3026 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
3028 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
3029 return ctx->verify_cb(0, ctx);