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 if (ret == X509_V_OK)
323 /* If we haven't asked for issuer errors don't set ctx */
324 if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
328 ctx->current_cert = x;
329 ctx->current_issuer = issuer;
330 return ctx->verify_cb(0, ctx);
333 /* Alternative lookup method: look from a STACK stored in other_ctx */
335 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
337 *issuer = find_issuer(ctx, ctx->other_ctx, x);
339 X509_up_ref(*issuer);
345 static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx, X509_NAME *nm)
347 STACK_OF(X509) *sk = NULL;
350 for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
351 x = sk_X509_value(ctx->other_ctx, i);
352 if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
354 sk = sk_X509_new_null();
355 if (sk == NULL || sk_X509_push(sk, x) == 0) {
356 sk_X509_pop_free(sk, X509_free);
366 * Check a certificate chains extensions for consistency with the supplied
370 static int check_chain_extensions(X509_STORE_CTX *ctx)
372 int i, ok = 0, must_be_ca, plen = 0;
374 int proxy_path_length = 0;
376 int allow_proxy_certs;
379 * must_be_ca can have 1 of 3 values:
380 * -1: we accept both CA and non-CA certificates, to allow direct
381 * use of self-signed certificates (which are marked as CA).
382 * 0: we only accept non-CA certificates. This is currently not
383 * used, but the possibility is present for future extensions.
384 * 1: we only accept CA certificates. This is currently used for
385 * all certificates in the chain except the leaf certificate.
389 /* CRL path validation */
391 allow_proxy_certs = 0;
392 purpose = X509_PURPOSE_CRL_SIGN;
395 ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
397 * A hack to keep people who don't want to modify their software
400 if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
401 allow_proxy_certs = 1;
402 purpose = ctx->param->purpose;
405 /* Check all untrusted certificates */
406 for (i = 0; i == 0 || i < ctx->num_untrusted; i++) {
408 x = sk_X509_value(ctx->chain, i);
409 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
410 && (x->ex_flags & EXFLAG_CRITICAL)) {
411 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
412 ctx->error_depth = i;
413 ctx->current_cert = x;
414 ok = ctx->verify_cb(0, ctx);
418 if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
419 ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
420 ctx->error_depth = i;
421 ctx->current_cert = x;
422 ok = ctx->verify_cb(0, ctx);
426 ret = X509_check_ca(x);
427 switch (must_be_ca) {
429 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
430 && (ret != 1) && (ret != 0)) {
432 ctx->error = X509_V_ERR_INVALID_CA;
439 ctx->error = X509_V_ERR_INVALID_NON_CA;
445 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
448 ctx->error = X509_V_ERR_INVALID_CA;
454 ctx->error_depth = i;
455 ctx->current_cert = x;
456 ok = ctx->verify_cb(0, ctx);
460 if (ctx->param->purpose > 0) {
461 ret = X509_check_purpose(x, purpose, must_be_ca > 0);
463 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
465 ctx->error = X509_V_ERR_INVALID_PURPOSE;
466 ctx->error_depth = i;
467 ctx->current_cert = x;
468 ok = ctx->verify_cb(0, ctx);
473 /* Check pathlen if not self issued */
474 if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
475 && (x->ex_pathlen != -1)
476 && (plen > (x->ex_pathlen + proxy_path_length + 1))) {
477 ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
478 ctx->error_depth = i;
479 ctx->current_cert = x;
480 ok = ctx->verify_cb(0, ctx);
484 /* Increment path length if not self issued */
485 if (!(x->ex_flags & EXFLAG_SI))
488 * If this certificate is a proxy certificate, the next certificate
489 * must be another proxy certificate or a EE certificate. If not,
490 * the next certificate must be a CA certificate.
492 if (x->ex_flags & EXFLAG_PROXY) {
493 if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
494 ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
495 ctx->error_depth = i;
496 ctx->current_cert = x;
497 ok = ctx->verify_cb(0, ctx);
511 static int check_name_constraints(X509_STORE_CTX *ctx)
515 /* Check name constraints for all certificates */
516 for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
517 x = sk_X509_value(ctx->chain, i);
518 /* Ignore self issued certs unless last in chain */
519 if (i && (x->ex_flags & EXFLAG_SI))
522 * Check against constraints for all certificates higher in chain
523 * including trust anchor. Trust anchor not strictly speaking needed
524 * but if it includes constraints it is to be assumed it expects them
527 for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
528 NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
530 rv = NAME_CONSTRAINTS_check(x, nc);
531 if (rv != X509_V_OK) {
533 ctx->error_depth = i;
534 ctx->current_cert = x;
535 if (!ctx->verify_cb(0, ctx))
544 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
546 ctx->error = errcode;
547 ctx->current_cert = ctx->cert;
548 ctx->error_depth = 0;
549 return ctx->verify_cb(0, ctx);
552 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
555 int n = sk_OPENSSL_STRING_num(vpm->hosts);
558 if (vpm->peername != NULL) {
559 OPENSSL_free(vpm->peername);
560 vpm->peername = NULL;
562 for (i = 0; i < n; ++i) {
563 name = sk_OPENSSL_STRING_value(vpm->hosts, i);
564 if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
570 static int check_id(X509_STORE_CTX *ctx)
572 X509_VERIFY_PARAM *vpm = ctx->param;
574 if (vpm->hosts && check_hosts(x, vpm) <= 0) {
575 if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
578 if (vpm->email && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) {
579 if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
582 if (vpm->ip && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) {
583 if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
589 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
594 struct dane_st *dane = (struct dane_st *)ctx->dane;
595 int num = sk_X509_num(ctx->chain);
599 * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2)
600 * match, we're done, otherwise we'll merely record the match depth.
602 if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) {
603 switch (trust = check_dane_issuer(ctx, num_untrusted)) {
604 case X509_TRUST_TRUSTED:
605 case X509_TRUST_REJECTED:
611 * Check trusted certificates in chain at depth num_untrusted and up.
612 * Note, that depths 0..num_untrusted-1 may also contain trusted
613 * certificates, but the caller is expected to have already checked those,
614 * and wants to incrementally check just any added since.
616 for (i = num_untrusted; i < num; i++) {
617 x = sk_X509_value(ctx->chain, i);
618 trust = X509_check_trust(x, ctx->param->trust, 0);
619 /* If explicitly trusted return trusted */
620 if (trust == X509_TRUST_TRUSTED)
622 if (trust == X509_TRUST_REJECTED)
627 * If we are looking at a trusted certificate, and accept partial chains,
628 * the chain is PKIX trusted.
630 if (num_untrusted < num) {
631 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
633 return X509_TRUST_UNTRUSTED;
636 if (num_untrusted == num && ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
638 * Last-resort call with no new trusted certificates, check the leaf
639 * for a direct trust store match.
642 x = sk_X509_value(ctx->chain, i);
643 mx = lookup_cert_match(ctx, x);
645 return X509_TRUST_UNTRUSTED;
648 * Check explicit auxiliary trust/reject settings. If none are set,
649 * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
651 trust = X509_check_trust(mx, ctx->param->trust, 0);
652 if (trust == X509_TRUST_REJECTED) {
657 /* Replace leaf with trusted match */
658 (void) sk_X509_set(ctx->chain, 0, mx);
660 ctx->num_untrusted = 0;
665 * If no trusted certs in chain at all return untrusted and allow
666 * standard (no issuer cert) etc errors to be indicated.
668 return X509_TRUST_UNTRUSTED;
671 ctx->error_depth = i;
672 ctx->current_cert = x;
673 ctx->error = X509_V_ERR_CERT_REJECTED;
674 ok = ctx->verify_cb(0, ctx);
676 return X509_TRUST_REJECTED;
677 return X509_TRUST_UNTRUSTED;
680 if (!DANETLS_ENABLED(dane))
681 return X509_TRUST_TRUSTED;
683 dane->pdpth = num_untrusted;
684 /* With DANE, PKIX alone is not trusted until we have both */
685 if (dane->mdpth >= 0)
686 return X509_TRUST_TRUSTED;
687 return X509_TRUST_UNTRUSTED;
690 static int check_revocation(X509_STORE_CTX *ctx)
692 int i = 0, last = 0, ok = 0;
693 if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
695 if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
696 last = sk_X509_num(ctx->chain) - 1;
698 /* If checking CRL paths this isn't the EE certificate */
703 for (i = 0; i <= last; i++) {
704 ctx->error_depth = i;
705 ok = check_cert(ctx);
712 static int check_cert(X509_STORE_CTX *ctx)
714 X509_CRL *crl = NULL, *dcrl = NULL;
716 int ok = 0, cnum = 0;
717 unsigned int last_reasons = 0;
718 cnum = ctx->error_depth;
719 x = sk_X509_value(ctx->chain, cnum);
720 ctx->current_cert = x;
721 ctx->current_issuer = NULL;
722 ctx->current_crl_score = 0;
723 ctx->current_reasons = 0;
724 while (ctx->current_reasons != CRLDP_ALL_REASONS) {
725 last_reasons = ctx->current_reasons;
726 /* Try to retrieve relevant CRL */
728 ok = ctx->get_crl(ctx, &crl, x);
730 ok = get_crl_delta(ctx, &crl, &dcrl, x);
732 * If error looking up CRL, nothing we can do except notify callback
735 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
736 ok = ctx->verify_cb(0, ctx);
739 ctx->current_crl = crl;
740 ok = ctx->check_crl(ctx, crl);
745 ok = ctx->check_crl(ctx, dcrl);
748 ok = ctx->cert_crl(ctx, dcrl, x);
754 /* Don't look in full CRL if delta reason is removefromCRL */
756 ok = ctx->cert_crl(ctx, crl, x);
766 * If reasons not updated we wont get anywhere by another iteration,
769 if (last_reasons == ctx->current_reasons) {
770 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
771 ok = ctx->verify_cb(0, ctx);
779 ctx->current_crl = NULL;
784 /* Check CRL times against values in X509_STORE_CTX */
786 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
791 ctx->current_crl = crl;
792 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
793 ptime = &ctx->param->check_time;
794 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
799 i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
803 ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
804 if (!ctx->verify_cb(0, ctx))
811 ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
812 if (!ctx->verify_cb(0, ctx))
816 if (X509_CRL_get_nextUpdate(crl)) {
817 i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
822 ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
823 if (!ctx->verify_cb(0, ctx))
826 /* Ignore expiry of base CRL is delta is valid */
827 if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
830 ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
831 if (!ctx->verify_cb(0, ctx))
837 ctx->current_crl = NULL;
842 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
843 X509 **pissuer, int *pscore, unsigned int *preasons,
844 STACK_OF(X509_CRL) *crls)
846 int i, crl_score, best_score = *pscore;
847 unsigned int reasons, best_reasons = 0;
848 X509 *x = ctx->current_cert;
849 X509_CRL *crl, *best_crl = NULL;
850 X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
852 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
853 crl = sk_X509_CRL_value(crls, i);
855 crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
857 if (crl_score > best_score) {
859 best_crl_issuer = crl_issuer;
860 best_score = crl_score;
861 best_reasons = reasons;
866 X509_CRL_free(*pcrl);
868 *pissuer = best_crl_issuer;
869 *pscore = best_score;
870 *preasons = best_reasons;
871 X509_CRL_up_ref(best_crl);
872 X509_CRL_free(*pdcrl);
874 get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
877 if (best_score >= CRL_SCORE_VALID)
884 * Compare two CRL extensions for delta checking purposes. They should be
885 * both present or both absent. If both present all fields must be identical.
888 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
890 ASN1_OCTET_STRING *exta, *extb;
892 i = X509_CRL_get_ext_by_NID(a, nid, -1);
894 /* Can't have multiple occurrences */
895 if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
897 exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
901 i = X509_CRL_get_ext_by_NID(b, nid, -1);
905 if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
907 extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
917 if (ASN1_OCTET_STRING_cmp(exta, extb))
923 /* See if a base and delta are compatible */
925 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
927 /* Delta CRL must be a delta */
928 if (!delta->base_crl_number)
930 /* Base must have a CRL number */
931 if (!base->crl_number)
933 /* Issuer names must match */
934 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
936 /* AKID and IDP must match */
937 if (!crl_extension_match(delta, base, NID_authority_key_identifier))
939 if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
941 /* Delta CRL base number must not exceed Full CRL number. */
942 if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
944 /* Delta CRL number must exceed full CRL number */
945 if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
951 * For a given base CRL find a delta... maybe extend to delta scoring or
952 * retrieve a chain of deltas...
955 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
956 X509_CRL *base, STACK_OF(X509_CRL) *crls)
960 if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
962 if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
964 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
965 delta = sk_X509_CRL_value(crls, i);
966 if (check_delta_base(delta, base)) {
967 if (check_crl_time(ctx, delta, 0))
968 *pscore |= CRL_SCORE_TIME_DELTA;
969 X509_CRL_up_ref(delta);
978 * For a given CRL return how suitable it is for the supplied certificate
979 * 'x'. The return value is a mask of several criteria. If the issuer is not
980 * the certificate issuer this is returned in *pissuer. The reasons mask is
981 * also used to determine if the CRL is suitable: if no new reasons the CRL
982 * is rejected, otherwise reasons is updated.
985 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
986 unsigned int *preasons, X509_CRL *crl, X509 *x)
990 unsigned int tmp_reasons = *preasons, crl_reasons;
992 /* First see if we can reject CRL straight away */
994 /* Invalid IDP cannot be processed */
995 if (crl->idp_flags & IDP_INVALID)
997 /* Reason codes or indirect CRLs need extended CRL support */
998 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
999 if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1001 } else if (crl->idp_flags & IDP_REASONS) {
1002 /* If no new reasons reject */
1003 if (!(crl->idp_reasons & ~tmp_reasons))
1006 /* Don't process deltas at this stage */
1007 else if (crl->base_crl_number)
1009 /* If issuer name doesn't match certificate need indirect CRL */
1010 if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1011 if (!(crl->idp_flags & IDP_INDIRECT))
1014 crl_score |= CRL_SCORE_ISSUER_NAME;
1016 if (!(crl->flags & EXFLAG_CRITICAL))
1017 crl_score |= CRL_SCORE_NOCRITICAL;
1020 if (check_crl_time(ctx, crl, 0))
1021 crl_score |= CRL_SCORE_TIME;
1023 /* Check authority key ID and locate certificate issuer */
1024 crl_akid_check(ctx, crl, pissuer, &crl_score);
1026 /* If we can't locate certificate issuer at this point forget it */
1028 if (!(crl_score & CRL_SCORE_AKID))
1031 /* Check cert for matching CRL distribution points */
1033 if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1034 /* If no new reasons reject */
1035 if (!(crl_reasons & ~tmp_reasons))
1037 tmp_reasons |= crl_reasons;
1038 crl_score |= CRL_SCORE_SCOPE;
1041 *preasons = tmp_reasons;
1047 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1048 X509 **pissuer, int *pcrl_score)
1050 X509 *crl_issuer = NULL;
1051 X509_NAME *cnm = X509_CRL_get_issuer(crl);
1052 int cidx = ctx->error_depth;
1055 if (cidx != sk_X509_num(ctx->chain) - 1)
1058 crl_issuer = sk_X509_value(ctx->chain, cidx);
1060 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1061 if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1062 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1063 *pissuer = crl_issuer;
1068 for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1069 crl_issuer = sk_X509_value(ctx->chain, cidx);
1070 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1072 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1073 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1074 *pissuer = crl_issuer;
1079 /* Anything else needs extended CRL support */
1081 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1085 * Otherwise the CRL issuer is not on the path. Look for it in the set of
1086 * untrusted certificates.
1088 for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1089 crl_issuer = sk_X509_value(ctx->untrusted, i);
1090 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1092 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1093 *pissuer = crl_issuer;
1094 *pcrl_score |= CRL_SCORE_AKID;
1101 * Check the path of a CRL issuer certificate. This creates a new
1102 * X509_STORE_CTX and populates it with most of the parameters from the
1103 * parent. This could be optimised somewhat since a lot of path checking will
1104 * be duplicated by the parent, but this will rarely be used in practice.
1107 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1109 X509_STORE_CTX crl_ctx;
1111 /* Don't allow recursive CRL path validation */
1114 if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
1117 crl_ctx.crls = ctx->crls;
1118 /* Copy verify params across */
1119 X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1121 crl_ctx.parent = ctx;
1122 crl_ctx.verify_cb = ctx->verify_cb;
1124 /* Verify CRL issuer */
1125 ret = X509_verify_cert(&crl_ctx);
1130 /* Check chain is acceptable */
1132 ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1134 X509_STORE_CTX_cleanup(&crl_ctx);
1139 * RFC3280 says nothing about the relationship between CRL path and
1140 * certificate path, which could lead to situations where a certificate could
1141 * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1142 * strict and states that the two paths must end in the same trust anchor,
1143 * though some discussions remain... until this is resolved we use the
1147 static int check_crl_chain(X509_STORE_CTX *ctx,
1148 STACK_OF(X509) *cert_path,
1149 STACK_OF(X509) *crl_path)
1151 X509 *cert_ta, *crl_ta;
1152 cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1153 crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1154 if (!X509_cmp(cert_ta, crl_ta))
1160 * Check for match between two dist point names: three separate cases.
1161 * 1. Both are relative names and compare X509_NAME types.
1162 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1163 * 3. Both are full names and compare two GENERAL_NAMES.
1164 * 4. One is NULL: automatic match.
1167 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1169 X509_NAME *nm = NULL;
1170 GENERAL_NAMES *gens = NULL;
1171 GENERAL_NAME *gena, *genb;
1178 /* Case 1: two X509_NAME */
1182 if (!X509_NAME_cmp(a->dpname, b->dpname))
1187 /* Case 2: set name and GENERAL_NAMES appropriately */
1189 gens = b->name.fullname;
1190 } else if (b->type == 1) {
1193 /* Case 2: set name and GENERAL_NAMES appropriately */
1194 gens = a->name.fullname;
1198 /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1200 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1201 gena = sk_GENERAL_NAME_value(gens, i);
1202 if (gena->type != GEN_DIRNAME)
1204 if (!X509_NAME_cmp(nm, gena->d.directoryName))
1210 /* Else case 3: two GENERAL_NAMES */
1212 for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1213 gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1214 for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1215 genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1216 if (!GENERAL_NAME_cmp(gena, genb))
1225 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1228 X509_NAME *nm = X509_CRL_get_issuer(crl);
1229 /* If no CRLissuer return is successful iff don't need a match */
1231 return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1232 for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1233 GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1234 if (gen->type != GEN_DIRNAME)
1236 if (!X509_NAME_cmp(gen->d.directoryName, nm))
1242 /* Check CRLDP and IDP */
1244 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1245 unsigned int *preasons)
1248 if (crl->idp_flags & IDP_ONLYATTR)
1250 if (x->ex_flags & EXFLAG_CA) {
1251 if (crl->idp_flags & IDP_ONLYUSER)
1254 if (crl->idp_flags & IDP_ONLYCA)
1257 *preasons = crl->idp_reasons;
1258 for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1259 DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1260 if (crldp_check_crlissuer(dp, crl, crl_score)) {
1261 if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1262 *preasons &= dp->dp_reasons;
1267 if ((!crl->idp || !crl->idp->distpoint)
1268 && (crl_score & CRL_SCORE_ISSUER_NAME))
1274 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1275 * to find a delta CRL too
1278 static int get_crl_delta(X509_STORE_CTX *ctx,
1279 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1282 X509 *issuer = NULL;
1284 unsigned int reasons;
1285 X509_CRL *crl = NULL, *dcrl = NULL;
1286 STACK_OF(X509_CRL) *skcrl;
1287 X509_NAME *nm = X509_get_issuer_name(x);
1288 reasons = ctx->current_reasons;
1289 ok = get_crl_sk(ctx, &crl, &dcrl,
1290 &issuer, &crl_score, &reasons, ctx->crls);
1295 /* Lookup CRLs from store */
1297 skcrl = ctx->lookup_crls(ctx, nm);
1299 /* If no CRLs found and a near match from get_crl_sk use that */
1303 get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1305 sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1309 /* If we got any kind of CRL use it and return success */
1311 ctx->current_issuer = issuer;
1312 ctx->current_crl_score = crl_score;
1313 ctx->current_reasons = reasons;
1322 /* Check CRL validity */
1323 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1325 X509 *issuer = NULL;
1326 EVP_PKEY *ikey = NULL;
1327 int ok = 0, chnum, cnum;
1328 cnum = ctx->error_depth;
1329 chnum = sk_X509_num(ctx->chain) - 1;
1330 /* if we have an alternative CRL issuer cert use that */
1331 if (ctx->current_issuer)
1332 issuer = ctx->current_issuer;
1335 * Else find CRL issuer: if not last certificate then issuer is next
1336 * certificate in chain.
1338 else if (cnum < chnum)
1339 issuer = sk_X509_value(ctx->chain, cnum + 1);
1341 issuer = sk_X509_value(ctx->chain, chnum);
1342 /* If not self signed, can't check signature */
1343 if (!ctx->check_issued(ctx, issuer, issuer)) {
1344 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1345 ok = ctx->verify_cb(0, ctx);
1353 * Skip most tests for deltas because they have already been done
1355 if (!crl->base_crl_number) {
1356 /* Check for cRLSign bit if keyUsage present */
1357 if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1358 !(issuer->ex_kusage & KU_CRL_SIGN)) {
1359 ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1360 ok = ctx->verify_cb(0, ctx);
1365 if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1366 ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1367 ok = ctx->verify_cb(0, ctx);
1372 if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1373 if (check_crl_path(ctx, ctx->current_issuer) <= 0) {
1374 ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1375 ok = ctx->verify_cb(0, ctx);
1381 if (crl->idp_flags & IDP_INVALID) {
1382 ctx->error = X509_V_ERR_INVALID_EXTENSION;
1383 ok = ctx->verify_cb(0, ctx);
1390 if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1391 ok = check_crl_time(ctx, crl, 1);
1396 /* Attempt to get issuer certificate public key */
1397 ikey = X509_get0_pubkey(issuer);
1400 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1401 ok = ctx->verify_cb(0, ctx);
1406 rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1407 if (rv != X509_V_OK) {
1409 ok = ctx->verify_cb(0, ctx);
1413 /* Verify CRL signature */
1414 if (X509_CRL_verify(crl, ikey) <= 0) {
1415 ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1416 ok = ctx->verify_cb(0, ctx);
1429 /* Check certificate against CRL */
1430 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1435 * The rules changed for this... previously if a CRL contained unhandled
1436 * critical extensions it could still be used to indicate a certificate
1437 * was revoked. This has since been changed since critical extension can
1438 * change the meaning of CRL entries.
1440 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
1441 && (crl->flags & EXFLAG_CRITICAL)) {
1442 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1443 ok = ctx->verify_cb(0, ctx);
1448 * Look for serial number of certificate in CRL If found make sure reason
1449 * is not removeFromCRL.
1451 if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1452 if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1454 ctx->error = X509_V_ERR_CERT_REVOKED;
1455 ok = ctx->verify_cb(0, ctx);
1463 static int check_policy(X509_STORE_CTX *ctx)
1468 ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1469 ctx->param->policies, ctx->param->flags);
1471 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1474 /* Invalid or inconsistent extensions */
1477 * Locate certificates with bad extensions and notify callback.
1481 for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1482 x = sk_X509_value(ctx->chain, i);
1483 if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1485 ctx->current_cert = x;
1486 ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1487 if (!ctx->verify_cb(0, ctx))
1493 ctx->current_cert = NULL;
1494 ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1495 return ctx->verify_cb(0, ctx);
1498 if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1499 ctx->current_cert = NULL;
1500 ctx->error = X509_V_OK;
1501 if (!ctx->verify_cb(2, ctx))
1508 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet)
1513 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1514 ptime = &ctx->param->check_time;
1515 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1520 i = X509_cmp_time(X509_get_notBefore(x), ptime);
1524 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
1525 ctx->current_cert = x;
1526 if (!ctx->verify_cb(0, ctx))
1533 ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
1534 ctx->current_cert = x;
1535 if (!ctx->verify_cb(0, ctx))
1539 i = X509_cmp_time(X509_get_notAfter(x), ptime);
1543 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
1544 ctx->current_cert = x;
1545 if (!ctx->verify_cb(0, ctx))
1552 ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
1553 ctx->current_cert = x;
1554 if (!ctx->verify_cb(0, ctx))
1561 static int internal_verify(X509_STORE_CTX *ctx)
1565 EVP_PKEY *pkey = NULL;
1567 n = sk_X509_num(ctx->chain) - 1;
1568 ctx->error_depth = n;
1569 xi = sk_X509_value(ctx->chain, n);
1572 * With DANE-verified bare public key TA signatures, it remains only to
1573 * check the timestamps of the top certificate. We report the issuer as
1574 * NULL, since all we have is a bare key.
1576 if (ctx->bare_ta_signed) {
1582 if (ctx->check_issued(ctx, xi, xi))
1585 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1590 ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
1591 ctx->current_cert = xi;
1592 ok = ctx->verify_cb(0, ctx);
1596 ctx->error_depth = n;
1597 xs = sk_X509_value(ctx->chain, n);
1602 * Do not clear ctx->error=0, it must be "sticky", only the user's callback
1603 * is allowed to reset errors (at its own peril).
1606 ctx->error_depth = n;
1609 * Skip signature check for self signed certificates unless
1610 * explicitly asked for. It doesn't add any security and just wastes
1613 if (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)) {
1614 if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1615 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1616 ctx->current_cert = xi;
1617 ok = ctx->verify_cb(0, ctx);
1620 } else if (X509_verify(xs, pkey) <= 0) {
1621 ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1622 ctx->current_cert = xs;
1623 ok = ctx->verify_cb(0, ctx);
1630 ok = x509_check_cert_time(ctx, xs, 0);
1634 /* The last error (if any) is still in the error value */
1635 ctx->current_issuer = xi;
1636 ctx->current_cert = xs;
1637 ok = ctx->verify_cb(1, ctx);
1644 xs = sk_X509_value(ctx->chain, n);
1652 int X509_cmp_current_time(const ASN1_TIME *ctm)
1654 return X509_cmp_time(ctm, NULL);
1657 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1662 char buff1[24], buff2[24], *p;
1663 int i, j, remaining;
1666 remaining = ctm->length;
1667 str = (char *)ctm->data;
1669 * Note that the following (historical) code allows much more slack in the
1670 * time format than RFC5280. In RFC5280, the representation is fixed:
1671 * UTCTime: YYMMDDHHMMSSZ
1672 * GeneralizedTime: YYYYMMDDHHMMSSZ
1674 if (ctm->type == V_ASN1_UTCTIME) {
1675 /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1676 int min_length = sizeof("YYMMDDHHMMZ") - 1;
1677 int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1678 if (remaining < min_length || remaining > max_length)
1685 /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1686 int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1687 int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1688 if (remaining < min_length || remaining > max_length)
1696 if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1707 * Skip any (up to three) fractional seconds...
1708 * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1709 * Can we just kill them altogether?
1711 if (remaining && *str == '.') {
1714 for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1715 if (*str < '0' || *str > '9')
1724 /* We now need either a terminating 'Z' or an offset. */
1733 if ((*str != '+') && (*str != '-'))
1735 /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1738 if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1739 str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1741 offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1742 offset += (str[3] - '0') * 10 + (str[4] - '0');
1746 atm.type = ctm->type;
1748 atm.length = sizeof(buff2);
1749 atm.data = (unsigned char *)buff2;
1751 if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1754 if (ctm->type == V_ASN1_UTCTIME) {
1755 i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1757 i += 100; /* cf. RFC 2459 */
1758 j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1767 i = strcmp(buff1, buff2);
1768 if (i == 0) /* wait a second then return younger :-) */
1774 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1776 return X509_time_adj(s, adj, NULL);
1779 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1781 return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1784 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1785 int offset_day, long offset_sec, time_t *in_tm)
1794 if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1795 if (s->type == V_ASN1_UTCTIME)
1796 return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1797 if (s->type == V_ASN1_GENERALIZEDTIME)
1798 return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1800 return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1803 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1805 EVP_PKEY *ktmp = NULL, *ktmp2;
1808 if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1811 for (i = 0; i < sk_X509_num(chain); i++) {
1812 ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1814 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1815 X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1818 if (!EVP_PKEY_missing_parameters(ktmp))
1822 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1823 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1827 /* first, populate the other certs */
1828 for (j = i - 1; j >= 0; j--) {
1829 ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1830 EVP_PKEY_copy_parameters(ktmp2, ktmp);
1834 EVP_PKEY_copy_parameters(pkey, ktmp);
1838 /* Make a delta CRL as the diff between two full CRLs */
1840 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1841 EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1843 X509_CRL *crl = NULL;
1845 STACK_OF(X509_REVOKED) *revs = NULL;
1846 /* CRLs can't be delta already */
1847 if (base->base_crl_number || newer->base_crl_number) {
1848 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1851 /* Base and new CRL must have a CRL number */
1852 if (!base->crl_number || !newer->crl_number) {
1853 X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1856 /* Issuer names must match */
1857 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
1858 X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
1861 /* AKID and IDP must match */
1862 if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1863 X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
1866 if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1867 X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
1870 /* Newer CRL number must exceed full CRL number */
1871 if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1872 X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
1875 /* CRLs must verify */
1876 if (skey && (X509_CRL_verify(base, skey) <= 0 ||
1877 X509_CRL_verify(newer, skey) <= 0)) {
1878 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
1881 /* Create new CRL */
1882 crl = X509_CRL_new();
1883 if (crl == NULL || !X509_CRL_set_version(crl, 1))
1885 /* Set issuer name */
1886 if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
1889 if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer)))
1891 if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer)))
1894 /* Set base CRL number: must be critical */
1896 if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
1900 * Copy extensions across from newest CRL to delta: this will set CRL
1901 * number to correct value too.
1904 for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
1905 X509_EXTENSION *ext;
1906 ext = X509_CRL_get_ext(newer, i);
1907 if (!X509_CRL_add_ext(crl, ext, -1))
1911 /* Go through revoked entries, copying as needed */
1913 revs = X509_CRL_get_REVOKED(newer);
1915 for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
1916 X509_REVOKED *rvn, *rvtmp;
1917 rvn = sk_X509_REVOKED_value(revs, i);
1919 * Add only if not also in base. TODO: need something cleverer here
1920 * for some more complex CRLs covering multiple CAs.
1922 if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
1923 rvtmp = X509_REVOKED_dup(rvn);
1926 if (!X509_CRL_add0_revoked(crl, rvtmp)) {
1927 X509_REVOKED_free(rvtmp);
1932 /* TODO: optionally prune deleted entries */
1934 if (skey && md && !X509_CRL_sign(crl, skey, md))
1940 X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
1945 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1947 return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1950 void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1952 return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1955 int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1960 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1965 int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1967 return ctx->error_depth;
1970 X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1972 return ctx->current_cert;
1975 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1980 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1984 return X509_chain_up_ref(ctx->chain);
1987 X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
1989 return ctx->current_issuer;
1992 X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
1994 return ctx->current_crl;
1997 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
2002 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2007 void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2009 ctx->untrusted = sk;
2012 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2017 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2019 return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2022 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2024 return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2028 * This function is used to set the X509_STORE_CTX purpose and trust values.
2029 * This is intended to be used when another structure has its own trust and
2030 * purpose values which (if set) will be inherited by the ctx. If they aren't
2031 * set then we will usually have a default purpose in mind which should then
2032 * be used to set the trust value. An example of this is SSL use: an SSL
2033 * structure will have its own purpose and trust settings which the
2034 * application can set: if they aren't set then we use the default of SSL
2038 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2039 int purpose, int trust)
2042 /* If purpose not set use default */
2044 purpose = def_purpose;
2045 /* If we have a purpose then check it is valid */
2048 idx = X509_PURPOSE_get_by_id(purpose);
2050 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2051 X509_R_UNKNOWN_PURPOSE_ID);
2054 ptmp = X509_PURPOSE_get0(idx);
2055 if (ptmp->trust == X509_TRUST_DEFAULT) {
2056 idx = X509_PURPOSE_get_by_id(def_purpose);
2058 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2059 X509_R_UNKNOWN_PURPOSE_ID);
2062 ptmp = X509_PURPOSE_get0(idx);
2064 /* If trust not set then get from purpose default */
2066 trust = ptmp->trust;
2069 idx = X509_TRUST_get_by_id(trust);
2071 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2072 X509_R_UNKNOWN_TRUST_ID);
2077 if (purpose && !ctx->param->purpose)
2078 ctx->param->purpose = purpose;
2079 if (trust && !ctx->param->trust)
2080 ctx->param->trust = trust;
2084 X509_STORE_CTX *X509_STORE_CTX_new(void)
2086 X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2089 X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
2095 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2099 X509_STORE_CTX_cleanup(ctx);
2103 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2104 STACK_OF(X509) *chain)
2109 ctx->current_method = 0;
2111 ctx->untrusted = chain;
2113 ctx->num_untrusted = 0;
2114 ctx->other_ctx = NULL;
2118 ctx->explicit_policy = 0;
2119 ctx->error_depth = 0;
2120 ctx->current_cert = NULL;
2121 ctx->current_issuer = NULL;
2122 ctx->current_crl = NULL;
2123 ctx->current_crl_score = 0;
2124 ctx->current_reasons = 0;
2128 ctx->bare_ta_signed = 0;
2129 /* Zero ex_data to make sure we're cleanup-safe */
2130 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2133 ctx->verify_cb = store->verify_cb;
2134 /* Seems to always be 0 in OpenSSL, else must be idempotent */
2135 ctx->cleanup = store->cleanup;
2139 if (store && store->check_issued)
2140 ctx->check_issued = store->check_issued;
2142 ctx->check_issued = check_issued;
2144 if (store && store->get_issuer)
2145 ctx->get_issuer = store->get_issuer;
2147 ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2149 if (store && store->verify_cb)
2150 ctx->verify_cb = store->verify_cb;
2152 ctx->verify_cb = null_callback;
2154 if (store && store->verify)
2155 ctx->verify = store->verify;
2157 ctx->verify = internal_verify;
2159 if (store && store->check_revocation)
2160 ctx->check_revocation = store->check_revocation;
2162 ctx->check_revocation = check_revocation;
2164 if (store && store->get_crl)
2165 ctx->get_crl = store->get_crl;
2167 ctx->get_crl = NULL;
2169 if (store && store->check_crl)
2170 ctx->check_crl = store->check_crl;
2172 ctx->check_crl = check_crl;
2174 if (store && store->cert_crl)
2175 ctx->cert_crl = store->cert_crl;
2177 ctx->cert_crl = cert_crl;
2179 if (store && store->lookup_certs)
2180 ctx->lookup_certs = store->lookup_certs;
2182 ctx->lookup_certs = X509_STORE_get1_certs;
2184 if (store && store->lookup_crls)
2185 ctx->lookup_crls = store->lookup_crls;
2187 ctx->lookup_crls = X509_STORE_get1_crls;
2189 ctx->check_policy = check_policy;
2191 ctx->param = X509_VERIFY_PARAM_new();
2192 if (ctx->param == NULL) {
2193 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2198 * Inherit callbacks and flags from X509_STORE if not set use defaults.
2201 ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2203 ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2206 ret = X509_VERIFY_PARAM_inherit(ctx->param,
2207 X509_VERIFY_PARAM_lookup("default"));
2210 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2214 if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2217 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2221 * On error clean up allocated storage, if the store context was not
2222 * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2224 X509_STORE_CTX_cleanup(ctx);
2229 * Set alternative lookup method: just a STACK of trusted certificates. This
2230 * avoids X509_STORE nastiness where it isn't needed.
2233 void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2235 ctx->other_ctx = sk;
2236 ctx->get_issuer = get_issuer_sk;
2237 ctx->lookup_certs = lookup_certs_sk;
2240 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2243 * We need to be idempotent because, unfortunately, free() also calls
2244 * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2245 * calls cleanup() for the same object twice! Thus we must zero the
2246 * pointers below after they're freed!
2248 /* Seems to always be 0 in OpenSSL, do this at most once. */
2249 if (ctx->cleanup != NULL) {
2251 ctx->cleanup = NULL;
2253 if (ctx->param != NULL) {
2254 if (ctx->parent == NULL)
2255 X509_VERIFY_PARAM_free(ctx->param);
2258 X509_policy_tree_free(ctx->tree);
2260 sk_X509_pop_free(ctx->chain, X509_free);
2262 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2263 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2266 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2268 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2271 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2273 X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2276 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2279 X509_VERIFY_PARAM_set_time(ctx->param, t);
2282 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2283 int (*verify_cb) (int, X509_STORE_CTX *))
2285 ctx->verify_cb = verify_cb;
2288 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2293 int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2295 return ctx->explicit_policy;
2298 int X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx)
2300 return ctx->num_untrusted;
2303 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2305 const X509_VERIFY_PARAM *param;
2306 param = X509_VERIFY_PARAM_lookup(name);
2309 return X509_VERIFY_PARAM_inherit(ctx->param, param);
2312 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2317 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2319 X509_VERIFY_PARAM_free(ctx->param);
2323 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, struct dane_st *dane)
2328 static unsigned char *dane_i2d(
2331 unsigned int *i2dlen)
2333 unsigned char *buf = NULL;
2337 * Extract ASN.1 DER form of certificate or public key.
2340 case DANETLS_SELECTOR_CERT:
2341 len = i2d_X509(cert, &buf);
2343 case DANETLS_SELECTOR_SPKI:
2344 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2347 X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2351 if (len < 0 || buf == NULL) {
2352 X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2356 *i2dlen = (unsigned int)len;
2360 #define DANETLS_NONE 256 /* impossible uint8_t */
2362 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2364 struct dane_st *dane = (struct dane_st *)ctx->dane;
2365 unsigned usage = DANETLS_NONE;
2366 unsigned selector = DANETLS_NONE;
2367 unsigned ordinal = DANETLS_NONE;
2368 unsigned mtype = DANETLS_NONE;
2369 unsigned char *i2dbuf = NULL;
2370 unsigned int i2dlen = 0;
2371 unsigned char mdbuf[EVP_MAX_MD_SIZE];
2372 unsigned char *cmpbuf = NULL;
2373 unsigned int cmplen = 0;
2377 danetls_record *t = NULL;
2380 mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2383 * The trust store is not applicable with DANE-TA(2)
2385 if (depth >= ctx->num_untrusted)
2386 mask &= DANETLS_PKIX_MASK;
2389 * If we've previously matched a PKIX-?? record, no need to test any
2390 * furher PKIX-?? records, it remains to just build the PKIX chain.
2391 * Had the match been a DANE-?? record, we'd be done already.
2393 if (dane->mdpth >= 0)
2394 mask &= ~DANETLS_PKIX_MASK;
2397 * https://tools.ietf.org/html/rfc7671#section-5.1
2398 * https://tools.ietf.org/html/rfc7671#section-5.2
2399 * https://tools.ietf.org/html/rfc7671#section-5.3
2400 * https://tools.ietf.org/html/rfc7671#section-5.4
2402 * We handle DANE-EE(3) records first as they require no chain building
2403 * and no expiration or hostname checks. We also process digests with
2404 * higher ordinals first and ignore lower priorities except Full(0) which
2405 * is always processed (last). If none match, we then process PKIX-EE(1).
2407 * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2408 * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2409 * priorities. See twin comment in ssl/ssl_lib.c.
2411 * We expect that most TLSA RRsets will have just a single usage, so we
2412 * don't go out of our way to cache multiple selector-specific i2d buffers
2413 * across usages, but if the selector happens to remain the same as switch
2414 * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2415 * records would result in us generating each of the certificate and public
2416 * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2417 * or multiple "3 0 1" records.
2419 * As soon as we find a match at any given depth, we stop, because either
2420 * we've matched a DANE-?? record and the peer is authenticated, or, after
2421 * exhausing all DANE-?? records, we've matched a PKIX-?? record, which is
2422 * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2424 recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2425 for (i = 0; matched == 0 && i < recnum; ++i) {
2426 t = sk_danetls_record_value(dane->trecs, i);
2427 if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2429 if (t->usage != usage) {
2432 /* Reset digest agility for each usage/selector pair */
2433 mtype = DANETLS_NONE;
2434 ordinal = dane->dctx->mdord[t->mtype];
2436 if (t->selector != selector) {
2437 selector = t->selector;
2439 /* Update per-selector state */
2440 OPENSSL_free(i2dbuf);
2441 i2dbuf = dane_i2d(cert, selector, &i2dlen);
2445 /* Reset digest agility for each usage/selector pair */
2446 mtype = DANETLS_NONE;
2447 ordinal = dane->dctx->mdord[t->mtype];
2448 } else if (t->mtype != DANETLS_MATCHING_FULL) {
2452 * <https://tools.ietf.org/html/rfc7671#section-9>
2454 * For a fixed selector, after processing all records with the
2455 * highest mtype ordinal, ignore all mtypes with lower ordinals
2456 * other than "Full".
2458 if (dane->dctx->mdord[t->mtype] < ordinal)
2463 * Each time we hit a (new selector or) mtype, re-compute the relevant
2464 * digest, more complex caching is not worth the code space.
2466 if (t->mtype != mtype) {
2467 const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2473 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2481 * Squirrel away the certificate and depth if we have a match. Any
2482 * DANE match is dispositive, but with PKIX we still need to build a
2485 if (cmplen == t->dlen &&
2486 memcmp(cmpbuf, t->data, cmplen) == 0) {
2487 if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2489 if (matched || dane->mdpth < 0) {
2490 dane->mdpth = depth;
2492 OPENSSL_free(dane->mcert);
2500 /* Clear the one-element DER cache */
2501 OPENSSL_free(i2dbuf);
2505 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2507 struct dane_st *dane = (struct dane_st *)ctx->dane;
2511 if (!DANETLS_HAS_TA(dane) || depth == 0)
2512 return X509_TRUST_UNTRUSTED;
2515 * Record any DANE trust anchor matches, for the first depth to test, if
2516 * there's one at that depth. (This'll be false for length 1 chains looking
2517 * for an exact match for the leaf certificate).
2519 cert = sk_X509_value(ctx->chain, depth);
2520 if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2521 return X509_TRUST_REJECTED;
2523 ctx->num_untrusted = depth - 1;
2524 return X509_TRUST_TRUSTED;
2527 return X509_TRUST_UNTRUSTED;
2530 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2532 struct dane_st *dane = (struct dane_st *)ctx->dane;
2534 int num = ctx->num_untrusted;
2535 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2536 int recnum = sk_danetls_record_num(dane->trecs);
2539 for (i = 0; i < recnum; ++i) {
2540 t = sk_danetls_record_value(dane->trecs, i);
2541 if (t->usage != DANETLS_USAGE_DANE_TA ||
2542 t->selector != DANETLS_SELECTOR_SPKI ||
2543 t->mtype != DANETLS_MATCHING_FULL ||
2544 X509_verify(cert, t->spki) <= 0)
2547 /* Clear PKIX-?? matches that failed to panned out to a full chain */
2548 X509_free(dane->mcert);
2551 /* Record match via a bare TA public key */
2552 ctx->bare_ta_signed = 1;
2553 dane->mdpth = num - 1;
2556 /* Prune any excess chain certificates */
2557 num = sk_X509_num(ctx->chain);
2558 for (; num > ctx->num_untrusted; --num)
2559 X509_free(sk_X509_pop(ctx->chain));
2561 return X509_TRUST_TRUSTED;
2564 return X509_TRUST_UNTRUSTED;
2567 static void dane_reset(struct dane_st *dane)
2570 * Reset state to verify another chain, or clear after failure.
2572 X509_free(dane->mcert);
2579 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
2581 int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
2583 if (err == X509_V_OK)
2585 ctx->current_cert = cert;
2586 ctx->error_depth = 0;
2588 return ctx->verify_cb(0, ctx);
2591 static int dane_verify(X509_STORE_CTX *ctx)
2593 X509 *cert = ctx->cert;
2594 struct dane_st *dane = (struct dane_st *)ctx->dane;
2600 matched = dane_match(ctx, ctx->cert, 0);
2601 done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2604 X509_get_pubkey_parameters(NULL, ctx->chain);
2607 if (!check_leaf_suiteb(ctx, cert))
2609 ctx->error_depth = 0;
2610 ctx->current_cert = cert;
2611 return ctx->verify_cb(1, ctx);
2615 ctx->error_depth = 0;
2616 ctx->current_cert = cert;
2617 ctx->error = X509_V_ERR_OUT_OF_MEM;
2622 /* Fail early, TA-based success is not possible */
2623 if (!check_leaf_suiteb(ctx, cert))
2625 ctx->current_cert = cert;
2626 ctx->error_depth = 0;
2627 ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2628 return ctx->verify_cb(0, ctx);
2632 * Chain verification for usages 0/1/2. TLSA record matching of depth > 0
2633 * certificates happens in-line with building the rest of the chain.
2635 return verify_chain(ctx);
2638 static int build_chain(X509_STORE_CTX *ctx)
2640 struct dane_st *dane = (struct dane_st *)ctx->dane;
2641 int num = sk_X509_num(ctx->chain);
2642 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2643 int ss = cert_self_signed(cert);
2644 STACK_OF(X509) *sktmp = NULL;
2645 unsigned int search;
2646 int may_trusted = 0;
2647 int may_alternate = 0;
2648 int trust = X509_TRUST_UNTRUSTED;
2649 int alt_untrusted = 0;
2654 /* Our chain starts with a single untrusted element. */
2655 OPENSSL_assert(num == 1 && ctx->num_untrusted == num);
2657 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
2658 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
2659 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
2661 * Set up search policy, untrusted if possible, trusted-first if enabled.
2662 * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2663 * trust_store, otherwise we might look there first. If not trusted-first,
2664 * and alternate chains are not disabled, try building an alternate chain
2665 * if no luck with untrusted first.
2667 search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2668 if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2669 if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2670 search |= S_DOTRUSTED;
2671 else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2677 * Shallow-copy the stack of untrusted certificates (with TLS, this is
2678 * typically the content of the peer's certificate message) so can make
2679 * multiple passes over it, while free to remove elements as we go.
2681 if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
2682 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2686 /* Include any untrusted full certificates from DNS */
2687 if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
2688 for (i = 0; i < sk_X509_num(dane->certs); ++i) {
2689 if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
2690 sk_X509_free(sktmp);
2691 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2698 * Still absurdly large, but arithmetically safe, a lower hard upper bound
2699 * might be reasonable.
2701 if (ctx->param->depth > INT_MAX/2)
2702 ctx->param->depth = INT_MAX/2;
2705 * Try to Extend the chain until we reach an ultimately trusted issuer.
2706 * Build chains up to one longer the limit, later fail if we hit the limit,
2707 * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
2709 depth = ctx->param->depth + 1;
2711 while (search != 0) {
2716 * Look in the trust store if enabled for first lookup, or we've run
2717 * out of untrusted issuers and search here is not disabled. When
2718 * we exceed the depth limit, we simulate absence of a match.
2720 if ((search & S_DOTRUSTED) != 0) {
2721 STACK_OF(X509) *hide = ctx->chain;
2723 i = num = sk_X509_num(ctx->chain);
2724 if ((search & S_DOALTERNATE) != 0) {
2726 * As high up the chain as we can, look for an alternative
2727 * trusted issuer of an untrusted certificate that currently
2728 * has an untrusted issuer. We use the alt_untrusted variable
2729 * to track how far up the chain we find the first match. It
2730 * is only if and when we find a match, that we prune the chain
2731 * and reset ctx->num_untrusted to the reduced count of
2732 * untrusted certificates. While we're searching for such a
2733 * match (which may never be found), it is neither safe nor
2734 * wise to preemptively modify either the chain or
2735 * ctx->num_untrusted.
2737 * Note, like ctx->num_untrusted, alt_untrusted is a count of
2738 * untrusted certificates, not a "depth".
2742 x = sk_X509_value(ctx->chain, i-1);
2744 /* Suppress duplicate suppression */
2746 ok = (depth < num) ? 0 : ctx->get_issuer(&xtmp, ctx, x);
2750 trust = X509_TRUST_REJECTED;
2757 * Alternative trusted issuer for a mid-chain untrusted cert?
2758 * Pop the untrusted cert's successors and retry. We might now
2759 * be able to complete a valid chain via the trust store. Note
2760 * that despite the current trust-store match we might still
2761 * fail complete the chain to a suitable trust-anchor, in which
2762 * case we may prune some more untrusted certificates and try
2763 * again. Thus the S_DOALTERNATE bit may yet be turned on
2764 * again with an even shorter untrusted chain!
2766 * If in the process we threw away our matching PKIX-TA trust
2767 * anchor, reset DANE trust. We might find a suitable trusted
2768 * certificate among the ones from the trust store.
2770 if ((search & S_DOALTERNATE) != 0) {
2771 OPENSSL_assert(num > i && i > 0 && ss == 0);
2772 search &= ~S_DOALTERNATE;
2773 for (; num > i; --num)
2774 X509_free(sk_X509_pop(ctx->chain));
2775 ctx->num_untrusted = num;
2777 if (DANETLS_ENABLED(dane) &&
2778 dane->mdpth >= ctx->num_untrusted) {
2780 X509_free(dane->mcert);
2783 if (DANETLS_ENABLED(dane) &&
2784 dane->pdpth >= ctx->num_untrusted)
2789 * Self-signed untrusted certificates get replaced by their
2790 * trusted matching issuer. Otherwise, grow the chain.
2793 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2795 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2796 trust = X509_TRUST_REJECTED;
2800 ss = cert_self_signed(x);
2801 } else if (num == ctx->num_untrusted) {
2803 * We have a self-signed certificate that has the same
2804 * subject name (and perhaps keyid and/or serial number) as
2805 * a trust-anchor. We must have an exact match to avoid
2806 * possible impersonation via key substitution etc.
2808 if (X509_cmp(x, xtmp) != 0) {
2809 /* Self-signed untrusted mimic. */
2814 ctx->num_untrusted = --num;
2815 (void) sk_X509_set(ctx->chain, num, x = xtmp);
2820 * We've added a new trusted certificate to the chain, recheck
2821 * trust. If not done, and not self-signed look deeper.
2822 * Whether or not we're doing "trusted first", we no longer
2823 * look for untrusted certificates from the peer's chain.
2825 * At this point ctx->num_trusted and num must reflect the
2826 * correct number of untrusted certificates, since the DANE
2827 * logic in check_trust() depends on distinguishing CAs from
2828 * "the wire" from CAs from the trust store. In particular, the
2829 * certificate at depth "num" should be the new trusted
2830 * certificate with ctx->num_untrusted <= num.
2833 OPENSSL_assert(ctx->num_untrusted <= num);
2834 search &= ~S_DOUNTRUSTED;
2835 switch (trust = check_trust(ctx, num)) {
2836 case X509_TRUST_TRUSTED:
2837 case X509_TRUST_REJECTED:
2847 * No dispositive decision, and either self-signed or no match, if
2848 * we were doing untrusted-first, and alt-chains are not disabled,
2849 * do that, by repeatedly losing one untrusted element at a time,
2850 * and trying to extend the shorted chain.
2852 if ((search & S_DOUNTRUSTED) == 0) {
2853 /* Continue search for a trusted issuer of a shorter chain? */
2854 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
2856 /* Still no luck and no fallbacks left? */
2857 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
2858 ctx->num_untrusted < 2)
2860 /* Search for a trusted issuer of a shorter chain */
2861 search |= S_DOALTERNATE;
2862 alt_untrusted = ctx->num_untrusted - 1;
2868 * Extend chain with peer-provided certificates
2870 if ((search & S_DOUNTRUSTED) != 0) {
2871 num = sk_X509_num(ctx->chain);
2872 OPENSSL_assert(num == ctx->num_untrusted);
2873 x = sk_X509_value(ctx->chain, num-1);
2874 xtmp = (depth < num) ? NULL : find_issuer(ctx, sktmp, x);
2877 * Once we run out of untrusted issuers, we stop looking for more
2878 * and start looking only in the trust store if enabled.
2881 search &= ~S_DOUNTRUSTED;
2883 search |= S_DOTRUSTED;
2887 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2888 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2889 trust = X509_TRUST_REJECTED;
2894 ++ctx->num_untrusted;
2895 ss = cert_self_signed(xtmp);
2898 * Not strictly necessary, but saves cycles looking at the same
2899 * certificates over and over.
2901 (void) sk_X509_delete_ptr(sktmp, x);
2904 * Check for DANE-TA trust of the topmost untrusted certificate.
2906 switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
2907 case X509_TRUST_TRUSTED:
2908 case X509_TRUST_REJECTED:
2914 sk_X509_free(sktmp);
2917 * Last chance to make a trusted chain, either bare DANE-TA public-key
2918 * signers, or else direct leaf PKIX trust.
2920 num = sk_X509_num(ctx->chain);
2922 if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
2923 trust = check_dane_pkeys(ctx);
2924 if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
2925 trust = check_trust(ctx, num);
2929 case X509_TRUST_TRUSTED:
2931 case X509_TRUST_REJECTED:
2933 case X509_TRUST_UNTRUSTED:
2935 num = sk_X509_num(ctx->chain);
2936 ctx->current_cert = sk_X509_value(ctx->chain, num - 1);
2937 ctx->error_depth = num-1;
2939 ctx->error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
2940 else if (DANETLS_ENABLED(dane) &&
2941 (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
2942 ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2943 else if (ss && sk_X509_num(ctx->chain) == 1)
2944 ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
2946 ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2947 else if (ctx->num_untrusted == num)
2948 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
2950 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2951 if (DANETLS_ENABLED(dane))
2953 return ctx->verify_cb(0, ctx);