1 /* crypto/x509/x509_vfy.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
64 #include "internal/cryptlib.h"
65 #include <openssl/crypto.h>
66 #include <openssl/lhash.h>
67 #include <openssl/buffer.h>
68 #include <openssl/evp.h>
69 #include <openssl/asn1.h>
70 #include <openssl/x509.h>
71 #include <openssl/x509v3.h>
72 #include <openssl/objects.h>
73 #include <internal/dane.h>
74 #include <internal/x509_int.h>
77 /* CRL score values */
79 /* No unhandled critical extensions */
81 #define CRL_SCORE_NOCRITICAL 0x100
83 /* certificate is within CRL scope */
85 #define CRL_SCORE_SCOPE 0x080
89 #define CRL_SCORE_TIME 0x040
91 /* Issuer name matches certificate */
93 #define CRL_SCORE_ISSUER_NAME 0x020
95 /* If this score or above CRL is probably valid */
97 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
99 /* CRL issuer is certificate issuer */
101 #define CRL_SCORE_ISSUER_CERT 0x018
103 /* CRL issuer is on certificate path */
105 #define CRL_SCORE_SAME_PATH 0x008
107 /* CRL issuer matches CRL AKID */
109 #define CRL_SCORE_AKID 0x004
111 /* Have a delta CRL with valid times */
113 #define CRL_SCORE_TIME_DELTA 0x002
115 static int build_chain(X509_STORE_CTX *ctx);
116 static int verify_chain(X509_STORE_CTX *ctx);
117 static int dane_verify(X509_STORE_CTX *ctx);
118 static int null_callback(int ok, X509_STORE_CTX *e);
119 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
120 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
121 static int check_chain_extensions(X509_STORE_CTX *ctx);
122 static int check_name_constraints(X509_STORE_CTX *ctx);
123 static int check_id(X509_STORE_CTX *ctx);
124 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
125 static int check_revocation(X509_STORE_CTX *ctx);
126 static int check_cert(X509_STORE_CTX *ctx);
127 static int check_policy(X509_STORE_CTX *ctx);
128 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
129 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
131 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
132 unsigned int *preasons, X509_CRL *crl, X509 *x);
133 static int get_crl_delta(X509_STORE_CTX *ctx,
134 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
135 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
136 int *pcrl_score, X509_CRL *base,
137 STACK_OF(X509_CRL) *crls);
138 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
140 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
141 unsigned int *preasons);
142 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
143 static int check_crl_chain(X509_STORE_CTX *ctx,
144 STACK_OF(X509) *cert_path,
145 STACK_OF(X509) *crl_path);
147 static int internal_verify(X509_STORE_CTX *ctx);
149 static int null_callback(int ok, X509_STORE_CTX *e)
154 /* Return 1 is a certificate is self signed */
155 static int cert_self_signed(X509 *x)
158 * FIXME: x509v3_cache_extensions() needs to detect more failures and not
159 * set EXFLAG_SET when that happens. Especially, if the failures are
160 * parse errors, rather than memory pressure!
162 X509_check_purpose(x, -1, 0);
163 if (x->ex_flags & EXFLAG_SS)
169 /* Given a certificate try and find an exact match in the store */
171 static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
173 STACK_OF(X509) *certs;
176 /* Lookup all certs with matching subject name */
177 certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
180 /* Look for exact match */
181 for (i = 0; i < sk_X509_num(certs); i++) {
182 xtmp = sk_X509_value(certs, i);
183 if (!X509_cmp(xtmp, x))
186 if (i < sk_X509_num(certs))
190 sk_X509_pop_free(certs, X509_free);
194 static int verify_chain(X509_STORE_CTX *ctx)
196 int (*cb) (int xok, X509_STORE_CTX *xctx) = ctx->verify_cb;
201 * Before either returning with an error, or continuing with CRL checks,
202 * instantiate chain public key parameters.
204 if ((ok = build_chain(ctx)) == 0 ||
205 (ok = check_chain_extensions(ctx)) == 0 ||
206 (ok = check_name_constraints(ctx)) == 0 ||
207 (ok = check_id(ctx)) == 0 || 1)
208 X509_get_pubkey_parameters(NULL, ctx->chain);
209 if (ok == 0 || (ok = ctx->check_revocation(ctx)) == 0)
212 err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
214 if (err != X509_V_OK) {
216 ctx->current_cert = sk_X509_value(ctx->chain, ctx->error_depth);
217 if ((ok = cb(0, ctx)) == 0)
221 /* Verify chain signatures and expiration times */
222 ok = (ctx->verify != NULL) ? ctx->verify(ctx) : internal_verify(ctx);
226 #ifndef OPENSSL_NO_RFC3779
227 /* RFC 3779 path validation, now that CRL check has been done */
228 if ((ok = v3_asid_validate_path(ctx)) == 0)
230 if ((ok = v3_addr_validate_path(ctx)) == 0)
234 /* If we get this far evaluate policies */
235 if (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)
236 ok = ctx->check_policy(ctx);
240 int X509_verify_cert(X509_STORE_CTX *ctx)
242 struct dane_st *dane = (struct dane_st *)ctx->dane;
244 if (ctx->cert == NULL) {
245 X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
249 if (ctx->chain != NULL) {
251 * This X509_STORE_CTX has already been used to verify a cert. We
252 * cannot do another one.
254 X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
259 * first we make sure the chain we are going to build is present and that
260 * the first entry is in place
262 if (((ctx->chain = sk_X509_new_null()) == NULL) ||
263 (!sk_X509_push(ctx->chain, ctx->cert))) {
264 X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
267 X509_up_ref(ctx->cert);
268 ctx->num_untrusted = 1;
271 * If dane->trecs is an empty stack, we'll fail, since the user enabled
272 * DANE. If none of the TLSA records were usable, and it makes sense to
273 * keep going with an unauthenticated handshake, they can handle that in
274 * the verify callback, or not set SSL_VERIFY_PEER.
276 if (DANETLS_ENABLED(dane))
277 return dane_verify(ctx);
278 return verify_chain(ctx);
282 * Given a STACK_OF(X509) find the issuer of cert (if any)
285 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
288 X509 *issuer, *rv = NULL;;
289 for (i = 0; i < sk_X509_num(sk); i++) {
290 issuer = sk_X509_value(sk, i);
291 if (ctx->check_issued(ctx, x, issuer)) {
293 if (x509_check_cert_time(ctx, rv, 1))
300 /* Given a possible certificate and issuer check them */
302 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
306 return cert_self_signed(x);
307 ret = X509_check_issued(issuer, x);
308 if (ret == X509_V_OK) {
311 /* Special case: single self signed certificate */
312 if (cert_self_signed(x) && sk_X509_num(ctx->chain) == 1)
314 for (i = 0; i < sk_X509_num(ctx->chain); i++) {
315 ch = sk_X509_value(ctx->chain, i);
316 if (ch == issuer || !X509_cmp(ch, issuer)) {
317 ret = X509_V_ERR_PATH_LOOP;
323 if (ret == X509_V_OK)
325 /* If we haven't asked for issuer errors don't set ctx */
326 if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
330 ctx->current_cert = x;
331 ctx->current_issuer = issuer;
332 return ctx->verify_cb(0, ctx);
335 /* Alternative lookup method: look from a STACK stored in other_ctx */
337 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
339 *issuer = find_issuer(ctx, ctx->other_ctx, x);
341 X509_up_ref(*issuer);
348 * Check a certificate chains extensions for consistency with the supplied
352 static int check_chain_extensions(X509_STORE_CTX *ctx)
354 int i, ok = 0, must_be_ca, plen = 0;
356 int (*cb) (int xok, X509_STORE_CTX *xctx);
357 int proxy_path_length = 0;
359 int allow_proxy_certs;
363 * must_be_ca can have 1 of 3 values:
364 * -1: we accept both CA and non-CA certificates, to allow direct
365 * use of self-signed certificates (which are marked as CA).
366 * 0: we only accept non-CA certificates. This is currently not
367 * used, but the possibility is present for future extensions.
368 * 1: we only accept CA certificates. This is currently used for
369 * all certificates in the chain except the leaf certificate.
373 /* CRL path validation */
375 allow_proxy_certs = 0;
376 purpose = X509_PURPOSE_CRL_SIGN;
379 ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
381 * A hack to keep people who don't want to modify their software
384 if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
385 allow_proxy_certs = 1;
386 purpose = ctx->param->purpose;
389 /* Check all untrusted certificates */
390 for (i = 0; i == 0 || i < ctx->num_untrusted; i++) {
392 x = sk_X509_value(ctx->chain, i);
393 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
394 && (x->ex_flags & EXFLAG_CRITICAL)) {
395 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
396 ctx->error_depth = i;
397 ctx->current_cert = x;
402 if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
403 ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
404 ctx->error_depth = i;
405 ctx->current_cert = x;
410 ret = X509_check_ca(x);
411 switch (must_be_ca) {
413 if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
414 && (ret != 1) && (ret != 0)) {
416 ctx->error = X509_V_ERR_INVALID_CA;
423 ctx->error = X509_V_ERR_INVALID_NON_CA;
429 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
432 ctx->error = X509_V_ERR_INVALID_CA;
438 ctx->error_depth = i;
439 ctx->current_cert = x;
444 if (ctx->param->purpose > 0) {
445 ret = X509_check_purpose(x, purpose, must_be_ca > 0);
447 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
449 ctx->error = X509_V_ERR_INVALID_PURPOSE;
450 ctx->error_depth = i;
451 ctx->current_cert = x;
457 /* Check pathlen if not self issued */
458 if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
459 && (x->ex_pathlen != -1)
460 && (plen > (x->ex_pathlen + proxy_path_length + 1))) {
461 ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
462 ctx->error_depth = i;
463 ctx->current_cert = x;
468 /* Increment path length if not self issued */
469 if (!(x->ex_flags & EXFLAG_SI))
472 * If this certificate is a proxy certificate, the next certificate
473 * must be another proxy certificate or a EE certificate. If not,
474 * the next certificate must be a CA certificate.
476 if (x->ex_flags & EXFLAG_PROXY) {
477 if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
478 ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
479 ctx->error_depth = i;
480 ctx->current_cert = x;
495 static int check_name_constraints(X509_STORE_CTX *ctx)
499 /* Check name constraints for all certificates */
500 for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
501 x = sk_X509_value(ctx->chain, i);
502 /* Ignore self issued certs unless last in chain */
503 if (i && (x->ex_flags & EXFLAG_SI))
506 * Check against constraints for all certificates higher in chain
507 * including trust anchor. Trust anchor not strictly speaking needed
508 * but if it includes constraints it is to be assumed it expects them
511 for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
512 NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
514 rv = NAME_CONSTRAINTS_check(x, nc);
515 if (rv != X509_V_OK) {
517 ctx->error_depth = i;
518 ctx->current_cert = x;
519 if (!ctx->verify_cb(0, ctx))
528 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
530 ctx->error = errcode;
531 ctx->current_cert = ctx->cert;
532 ctx->error_depth = 0;
533 return ctx->verify_cb(0, ctx);
536 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
539 int n = sk_OPENSSL_STRING_num(vpm->hosts);
542 if (vpm->peername != NULL) {
543 OPENSSL_free(vpm->peername);
544 vpm->peername = NULL;
546 for (i = 0; i < n; ++i) {
547 name = sk_OPENSSL_STRING_value(vpm->hosts, i);
548 if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
554 static int check_id(X509_STORE_CTX *ctx)
556 X509_VERIFY_PARAM *vpm = ctx->param;
558 if (vpm->hosts && check_hosts(x, vpm) <= 0) {
559 if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
562 if (vpm->email && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) {
563 if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
566 if (vpm->ip && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) {
567 if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
573 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
578 int (*cb) (int xok, X509_STORE_CTX *xctx) = ctx->verify_cb;
579 struct dane_st *dane = (struct dane_st *)ctx->dane;
580 int num = sk_X509_num(ctx->chain);
583 if (DANETLS_HAS_TA(dane) && num_untrusted > 0) {
584 switch (trust = check_dane_issuer(ctx, num_untrusted)) {
585 case X509_TRUST_TRUSTED:
586 case X509_TRUST_REJECTED:
592 * Check trusted certificates in chain at depth num_untrusted and up.
593 * Note, that depths 0..num_untrusted-1 may also contain trusted
594 * certificates, but the caller is expected to have already checked those,
595 * and wants to incrementally check just any added since.
597 for (i = num_untrusted; i < num; i++) {
598 x = sk_X509_value(ctx->chain, i);
599 trust = X509_check_trust(x, ctx->param->trust, 0);
600 /* If explicitly trusted return trusted */
601 if (trust == X509_TRUST_TRUSTED)
603 if (trust == X509_TRUST_REJECTED)
608 * If we are looking at a trusted certificate, and accept partial chains,
609 * the chain is PKIX trusted.
611 if (num_untrusted < num) {
612 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
614 return X509_TRUST_UNTRUSTED;
617 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
619 * Last-resort call with no new trusted certificates, check the leaf
620 * for a direct trust store match.
622 x = sk_X509_value(ctx->chain, 0);
623 mx = lookup_cert_match(ctx, x);
625 return X509_TRUST_UNTRUSTED;
628 * Check explicit auxiliary trust/reject settings. If none are set,
629 * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
631 trust = X509_check_trust(mx, ctx->param->trust, 0);
632 if (trust == X509_TRUST_REJECTED) {
637 /* Replace leaf with trusted match */
638 (void) sk_X509_set(ctx->chain, 0, mx);
640 ctx->num_untrusted = 0;
645 * If no trusted certs in chain at all return untrusted and allow
646 * standard (no issuer cert) etc errors to be indicated.
648 return X509_TRUST_UNTRUSTED;
651 ctx->error_depth = i;
652 ctx->current_cert = x;
653 ctx->error = X509_V_ERR_CERT_REJECTED;
656 return X509_TRUST_REJECTED;
657 return X509_TRUST_UNTRUSTED;
660 if (!DANETLS_ENABLED(dane))
661 return X509_TRUST_TRUSTED;
663 dane->pdpth = num_untrusted;
664 /* With DANE, PKIX alone is not trusted until we have both */
665 if (dane->mdpth >= 0)
666 return X509_TRUST_TRUSTED;
667 return X509_TRUST_UNTRUSTED;
670 static int check_revocation(X509_STORE_CTX *ctx)
672 int i = 0, last = 0, ok = 0;
673 if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
675 if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
676 last = sk_X509_num(ctx->chain) - 1;
678 /* If checking CRL paths this isn't the EE certificate */
683 for (i = 0; i <= last; i++) {
684 ctx->error_depth = i;
685 ok = check_cert(ctx);
692 static int check_cert(X509_STORE_CTX *ctx)
694 X509_CRL *crl = NULL, *dcrl = NULL;
696 int ok = 0, cnum = 0;
697 unsigned int last_reasons = 0;
698 cnum = ctx->error_depth;
699 x = sk_X509_value(ctx->chain, cnum);
700 ctx->current_cert = x;
701 ctx->current_issuer = NULL;
702 ctx->current_crl_score = 0;
703 ctx->current_reasons = 0;
704 while (ctx->current_reasons != CRLDP_ALL_REASONS) {
705 last_reasons = ctx->current_reasons;
706 /* Try to retrieve relevant CRL */
708 ok = ctx->get_crl(ctx, &crl, x);
710 ok = get_crl_delta(ctx, &crl, &dcrl, x);
712 * If error looking up CRL, nothing we can do except notify callback
715 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
716 ok = ctx->verify_cb(0, ctx);
719 ctx->current_crl = crl;
720 ok = ctx->check_crl(ctx, crl);
725 ok = ctx->check_crl(ctx, dcrl);
728 ok = ctx->cert_crl(ctx, dcrl, x);
734 /* Don't look in full CRL if delta reason is removefromCRL */
736 ok = ctx->cert_crl(ctx, crl, x);
746 * If reasons not updated we wont get anywhere by another iteration,
749 if (last_reasons == ctx->current_reasons) {
750 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
751 ok = ctx->verify_cb(0, ctx);
759 ctx->current_crl = NULL;
764 /* Check CRL times against values in X509_STORE_CTX */
766 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
771 ctx->current_crl = crl;
772 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
773 ptime = &ctx->param->check_time;
774 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
779 i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
783 ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
784 if (!ctx->verify_cb(0, ctx))
791 ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
792 if (!ctx->verify_cb(0, ctx))
796 if (X509_CRL_get_nextUpdate(crl)) {
797 i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
802 ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
803 if (!ctx->verify_cb(0, ctx))
806 /* Ignore expiry of base CRL is delta is valid */
807 if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
810 ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
811 if (!ctx->verify_cb(0, ctx))
817 ctx->current_crl = NULL;
822 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
823 X509 **pissuer, int *pscore, unsigned int *preasons,
824 STACK_OF(X509_CRL) *crls)
826 int i, crl_score, best_score = *pscore;
827 unsigned int reasons, best_reasons = 0;
828 X509 *x = ctx->current_cert;
829 X509_CRL *crl, *best_crl = NULL;
830 X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
832 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
833 crl = sk_X509_CRL_value(crls, i);
835 crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
837 if (crl_score > best_score) {
839 best_crl_issuer = crl_issuer;
840 best_score = crl_score;
841 best_reasons = reasons;
846 X509_CRL_free(*pcrl);
848 *pissuer = best_crl_issuer;
849 *pscore = best_score;
850 *preasons = best_reasons;
851 X509_CRL_up_ref(best_crl);
852 X509_CRL_free(*pdcrl);
854 get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
857 if (best_score >= CRL_SCORE_VALID)
864 * Compare two CRL extensions for delta checking purposes. They should be
865 * both present or both absent. If both present all fields must be identical.
868 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
870 ASN1_OCTET_STRING *exta, *extb;
872 i = X509_CRL_get_ext_by_NID(a, nid, -1);
874 /* Can't have multiple occurrences */
875 if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
877 exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
881 i = X509_CRL_get_ext_by_NID(b, nid, -1);
885 if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
887 extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
897 if (ASN1_OCTET_STRING_cmp(exta, extb))
903 /* See if a base and delta are compatible */
905 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
907 /* Delta CRL must be a delta */
908 if (!delta->base_crl_number)
910 /* Base must have a CRL number */
911 if (!base->crl_number)
913 /* Issuer names must match */
914 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
916 /* AKID and IDP must match */
917 if (!crl_extension_match(delta, base, NID_authority_key_identifier))
919 if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
921 /* Delta CRL base number must not exceed Full CRL number. */
922 if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
924 /* Delta CRL number must exceed full CRL number */
925 if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
931 * For a given base CRL find a delta... maybe extend to delta scoring or
932 * retrieve a chain of deltas...
935 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
936 X509_CRL *base, STACK_OF(X509_CRL) *crls)
940 if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
942 if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
944 for (i = 0; i < sk_X509_CRL_num(crls); i++) {
945 delta = sk_X509_CRL_value(crls, i);
946 if (check_delta_base(delta, base)) {
947 if (check_crl_time(ctx, delta, 0))
948 *pscore |= CRL_SCORE_TIME_DELTA;
949 X509_CRL_up_ref(delta);
958 * For a given CRL return how suitable it is for the supplied certificate
959 * 'x'. The return value is a mask of several criteria. If the issuer is not
960 * the certificate issuer this is returned in *pissuer. The reasons mask is
961 * also used to determine if the CRL is suitable: if no new reasons the CRL
962 * is rejected, otherwise reasons is updated.
965 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
966 unsigned int *preasons, X509_CRL *crl, X509 *x)
970 unsigned int tmp_reasons = *preasons, crl_reasons;
972 /* First see if we can reject CRL straight away */
974 /* Invalid IDP cannot be processed */
975 if (crl->idp_flags & IDP_INVALID)
977 /* Reason codes or indirect CRLs need extended CRL support */
978 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
979 if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
981 } else if (crl->idp_flags & IDP_REASONS) {
982 /* If no new reasons reject */
983 if (!(crl->idp_reasons & ~tmp_reasons))
986 /* Don't process deltas at this stage */
987 else if (crl->base_crl_number)
989 /* If issuer name doesn't match certificate need indirect CRL */
990 if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
991 if (!(crl->idp_flags & IDP_INDIRECT))
994 crl_score |= CRL_SCORE_ISSUER_NAME;
996 if (!(crl->flags & EXFLAG_CRITICAL))
997 crl_score |= CRL_SCORE_NOCRITICAL;
1000 if (check_crl_time(ctx, crl, 0))
1001 crl_score |= CRL_SCORE_TIME;
1003 /* Check authority key ID and locate certificate issuer */
1004 crl_akid_check(ctx, crl, pissuer, &crl_score);
1006 /* If we can't locate certificate issuer at this point forget it */
1008 if (!(crl_score & CRL_SCORE_AKID))
1011 /* Check cert for matching CRL distribution points */
1013 if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1014 /* If no new reasons reject */
1015 if (!(crl_reasons & ~tmp_reasons))
1017 tmp_reasons |= crl_reasons;
1018 crl_score |= CRL_SCORE_SCOPE;
1021 *preasons = tmp_reasons;
1027 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1028 X509 **pissuer, int *pcrl_score)
1030 X509 *crl_issuer = NULL;
1031 X509_NAME *cnm = X509_CRL_get_issuer(crl);
1032 int cidx = ctx->error_depth;
1035 if (cidx != sk_X509_num(ctx->chain) - 1)
1038 crl_issuer = sk_X509_value(ctx->chain, cidx);
1040 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1041 if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1042 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1043 *pissuer = crl_issuer;
1048 for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1049 crl_issuer = sk_X509_value(ctx->chain, cidx);
1050 if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1052 if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1053 *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1054 *pissuer = crl_issuer;
1059 /* Anything else needs extended CRL support */
1061 if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1065 * Otherwise the CRL issuer is not on the path. Look for it in the set of
1066 * untrusted certificates.
1068 for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1069 crl_issuer = sk_X509_value(ctx->untrusted, i);
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 *pissuer = crl_issuer;
1074 *pcrl_score |= CRL_SCORE_AKID;
1081 * Check the path of a CRL issuer certificate. This creates a new
1082 * X509_STORE_CTX and populates it with most of the parameters from the
1083 * parent. This could be optimised somewhat since a lot of path checking will
1084 * be duplicated by the parent, but this will rarely be used in practice.
1087 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1089 X509_STORE_CTX crl_ctx;
1091 /* Don't allow recursive CRL path validation */
1094 if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
1097 crl_ctx.crls = ctx->crls;
1098 /* Copy verify params across */
1099 X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1101 crl_ctx.parent = ctx;
1102 crl_ctx.verify_cb = ctx->verify_cb;
1104 /* Verify CRL issuer */
1105 ret = X509_verify_cert(&crl_ctx);
1110 /* Check chain is acceptable */
1112 ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1114 X509_STORE_CTX_cleanup(&crl_ctx);
1119 * RFC3280 says nothing about the relationship between CRL path and
1120 * certificate path, which could lead to situations where a certificate could
1121 * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1122 * strict and states that the two paths must end in the same trust anchor,
1123 * though some discussions remain... until this is resolved we use the
1127 static int check_crl_chain(X509_STORE_CTX *ctx,
1128 STACK_OF(X509) *cert_path,
1129 STACK_OF(X509) *crl_path)
1131 X509 *cert_ta, *crl_ta;
1132 cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1133 crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1134 if (!X509_cmp(cert_ta, crl_ta))
1140 * Check for match between two dist point names: three separate cases.
1141 * 1. Both are relative names and compare X509_NAME types.
1142 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1143 * 3. Both are full names and compare two GENERAL_NAMES.
1144 * 4. One is NULL: automatic match.
1147 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1149 X509_NAME *nm = NULL;
1150 GENERAL_NAMES *gens = NULL;
1151 GENERAL_NAME *gena, *genb;
1158 /* Case 1: two X509_NAME */
1162 if (!X509_NAME_cmp(a->dpname, b->dpname))
1167 /* Case 2: set name and GENERAL_NAMES appropriately */
1169 gens = b->name.fullname;
1170 } else if (b->type == 1) {
1173 /* Case 2: set name and GENERAL_NAMES appropriately */
1174 gens = a->name.fullname;
1178 /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1180 for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1181 gena = sk_GENERAL_NAME_value(gens, i);
1182 if (gena->type != GEN_DIRNAME)
1184 if (!X509_NAME_cmp(nm, gena->d.directoryName))
1190 /* Else case 3: two GENERAL_NAMES */
1192 for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1193 gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1194 for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1195 genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1196 if (!GENERAL_NAME_cmp(gena, genb))
1205 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1208 X509_NAME *nm = X509_CRL_get_issuer(crl);
1209 /* If no CRLissuer return is successful iff don't need a match */
1211 return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1212 for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1213 GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1214 if (gen->type != GEN_DIRNAME)
1216 if (!X509_NAME_cmp(gen->d.directoryName, nm))
1222 /* Check CRLDP and IDP */
1224 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1225 unsigned int *preasons)
1228 if (crl->idp_flags & IDP_ONLYATTR)
1230 if (x->ex_flags & EXFLAG_CA) {
1231 if (crl->idp_flags & IDP_ONLYUSER)
1234 if (crl->idp_flags & IDP_ONLYCA)
1237 *preasons = crl->idp_reasons;
1238 for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1239 DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1240 if (crldp_check_crlissuer(dp, crl, crl_score)) {
1241 if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1242 *preasons &= dp->dp_reasons;
1247 if ((!crl->idp || !crl->idp->distpoint)
1248 && (crl_score & CRL_SCORE_ISSUER_NAME))
1254 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1255 * to find a delta CRL too
1258 static int get_crl_delta(X509_STORE_CTX *ctx,
1259 X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1262 X509 *issuer = NULL;
1264 unsigned int reasons;
1265 X509_CRL *crl = NULL, *dcrl = NULL;
1266 STACK_OF(X509_CRL) *skcrl;
1267 X509_NAME *nm = X509_get_issuer_name(x);
1268 reasons = ctx->current_reasons;
1269 ok = get_crl_sk(ctx, &crl, &dcrl,
1270 &issuer, &crl_score, &reasons, ctx->crls);
1275 /* Lookup CRLs from store */
1277 skcrl = ctx->lookup_crls(ctx, nm);
1279 /* If no CRLs found and a near match from get_crl_sk use that */
1283 get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1285 sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1289 /* If we got any kind of CRL use it and return success */
1291 ctx->current_issuer = issuer;
1292 ctx->current_crl_score = crl_score;
1293 ctx->current_reasons = reasons;
1302 /* Check CRL validity */
1303 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1305 X509 *issuer = NULL;
1306 EVP_PKEY *ikey = NULL;
1307 int ok = 0, chnum, cnum;
1308 cnum = ctx->error_depth;
1309 chnum = sk_X509_num(ctx->chain) - 1;
1310 /* if we have an alternative CRL issuer cert use that */
1311 if (ctx->current_issuer)
1312 issuer = ctx->current_issuer;
1315 * Else find CRL issuer: if not last certificate then issuer is next
1316 * certificate in chain.
1318 else if (cnum < chnum)
1319 issuer = sk_X509_value(ctx->chain, cnum + 1);
1321 issuer = sk_X509_value(ctx->chain, chnum);
1322 /* If not self signed, can't check signature */
1323 if (!ctx->check_issued(ctx, issuer, issuer)) {
1324 ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1325 ok = ctx->verify_cb(0, ctx);
1333 * Skip most tests for deltas because they have already been done
1335 if (!crl->base_crl_number) {
1336 /* Check for cRLSign bit if keyUsage present */
1337 if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1338 !(issuer->ex_kusage & KU_CRL_SIGN)) {
1339 ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1340 ok = ctx->verify_cb(0, ctx);
1345 if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1346 ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1347 ok = ctx->verify_cb(0, ctx);
1352 if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1353 if (check_crl_path(ctx, ctx->current_issuer) <= 0) {
1354 ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1355 ok = ctx->verify_cb(0, ctx);
1361 if (crl->idp_flags & IDP_INVALID) {
1362 ctx->error = X509_V_ERR_INVALID_EXTENSION;
1363 ok = ctx->verify_cb(0, ctx);
1370 if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1371 ok = check_crl_time(ctx, crl, 1);
1376 /* Attempt to get issuer certificate public key */
1377 ikey = X509_get0_pubkey(issuer);
1380 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1381 ok = ctx->verify_cb(0, ctx);
1386 rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1387 if (rv != X509_V_OK) {
1389 ok = ctx->verify_cb(0, ctx);
1393 /* Verify CRL signature */
1394 if (X509_CRL_verify(crl, ikey) <= 0) {
1395 ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1396 ok = ctx->verify_cb(0, ctx);
1409 /* Check certificate against CRL */
1410 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1415 * The rules changed for this... previously if a CRL contained unhandled
1416 * critical extensions it could still be used to indicate a certificate
1417 * was revoked. This has since been changed since critical extension can
1418 * change the meaning of CRL entries.
1420 if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
1421 && (crl->flags & EXFLAG_CRITICAL)) {
1422 ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
1423 ok = ctx->verify_cb(0, ctx);
1428 * Look for serial number of certificate in CRL If found make sure reason
1429 * is not removeFromCRL.
1431 if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1432 if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1434 ctx->error = X509_V_ERR_CERT_REVOKED;
1435 ok = ctx->verify_cb(0, ctx);
1443 static int check_policy(X509_STORE_CTX *ctx)
1448 ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1449 ctx->param->policies, ctx->param->flags);
1451 X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1454 /* Invalid or inconsistent extensions */
1457 * Locate certificates with bad extensions and notify callback.
1461 for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1462 x = sk_X509_value(ctx->chain, i);
1463 if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1465 ctx->current_cert = x;
1466 ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1467 if (!ctx->verify_cb(0, ctx))
1473 ctx->current_cert = NULL;
1474 ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1475 return ctx->verify_cb(0, ctx);
1478 if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1479 ctx->current_cert = NULL;
1480 ctx->error = X509_V_OK;
1481 if (!ctx->verify_cb(2, ctx))
1488 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int quiet)
1493 if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1494 ptime = &ctx->param->check_time;
1495 else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1500 i = X509_cmp_time(X509_get_notBefore(x), ptime);
1504 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
1505 ctx->current_cert = x;
1506 if (!ctx->verify_cb(0, ctx))
1513 ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
1514 ctx->current_cert = x;
1515 if (!ctx->verify_cb(0, ctx))
1519 i = X509_cmp_time(X509_get_notAfter(x), ptime);
1523 ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
1524 ctx->current_cert = x;
1525 if (!ctx->verify_cb(0, ctx))
1532 ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
1533 ctx->current_cert = x;
1534 if (!ctx->verify_cb(0, ctx))
1541 static int internal_verify(X509_STORE_CTX *ctx)
1545 EVP_PKEY *pkey = NULL;
1546 int (*cb) (int xok, X509_STORE_CTX *xctx);
1548 cb = ctx->verify_cb;
1550 n = sk_X509_num(ctx->chain) - 1;
1551 ctx->error_depth = n;
1552 xi = sk_X509_value(ctx->chain, n);
1555 * With DANE-verified bare public key TA signatures, it remains only to
1556 * check the timestamps of the top certificate. We report the issuer as
1557 * NULL, since all we have is a bare key.
1559 if (ctx->bare_ta_signed) {
1565 if (ctx->check_issued(ctx, xi, xi))
1568 if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1573 ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
1574 ctx->current_cert = xi;
1579 ctx->error_depth = n;
1580 xs = sk_X509_value(ctx->chain, n);
1585 * Do not clear ctx->error=0, it must be "sticky", only the user's callback
1586 * is allowed to reset errors (at its own peril).
1589 ctx->error_depth = n;
1592 * Skip signature check for self signed certificates unless
1593 * explicitly asked for. It doesn't add any security and just wastes
1598 || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1599 if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1600 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1601 ctx->current_cert = xi;
1602 ok = (*cb) (0, ctx);
1605 } else if (X509_verify(xs, pkey) <= 0) {
1606 ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1607 ctx->current_cert = xs;
1608 ok = (*cb) (0, ctx);
1617 ok = x509_check_cert_time(ctx, xs, 0);
1621 /* The last error (if any) is still in the error value */
1622 ctx->current_issuer = xi;
1623 ctx->current_cert = xs;
1624 ok = (*cb) (1, ctx);
1631 xs = sk_X509_value(ctx->chain, n);
1639 int X509_cmp_current_time(const ASN1_TIME *ctm)
1641 return X509_cmp_time(ctm, NULL);
1644 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1649 char buff1[24], buff2[24], *p;
1650 int i, j, remaining;
1653 remaining = ctm->length;
1654 str = (char *)ctm->data;
1656 * Note that the following (historical) code allows much more slack in the
1657 * time format than RFC5280. In RFC5280, the representation is fixed:
1658 * UTCTime: YYMMDDHHMMSSZ
1659 * GeneralizedTime: YYYYMMDDHHMMSSZ
1661 if (ctm->type == V_ASN1_UTCTIME) {
1662 /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1663 int min_length = sizeof("YYMMDDHHMMZ") - 1;
1664 int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1665 if (remaining < min_length || remaining > max_length)
1672 /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1673 int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1674 int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1675 if (remaining < min_length || remaining > max_length)
1683 if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1694 * Skip any (up to three) fractional seconds...
1695 * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1696 * Can we just kill them altogether?
1698 if (remaining && *str == '.') {
1701 for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1702 if (*str < '0' || *str > '9')
1711 /* We now need either a terminating 'Z' or an offset. */
1720 if ((*str != '+') && (*str != '-'))
1722 /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1725 if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1726 str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1728 offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1729 offset += (str[3] - '0') * 10 + (str[4] - '0');
1733 atm.type = ctm->type;
1735 atm.length = sizeof(buff2);
1736 atm.data = (unsigned char *)buff2;
1738 if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1741 if (ctm->type == V_ASN1_UTCTIME) {
1742 i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1744 i += 100; /* cf. RFC 2459 */
1745 j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1754 i = strcmp(buff1, buff2);
1755 if (i == 0) /* wait a second then return younger :-) */
1761 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1763 return X509_time_adj(s, adj, NULL);
1766 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1768 return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1771 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1772 int offset_day, long offset_sec, time_t *in_tm)
1781 if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1782 if (s->type == V_ASN1_UTCTIME)
1783 return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1784 if (s->type == V_ASN1_GENERALIZEDTIME)
1785 return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1787 return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1790 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1792 EVP_PKEY *ktmp = NULL, *ktmp2;
1795 if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1798 for (i = 0; i < sk_X509_num(chain); i++) {
1799 ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1801 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1802 X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1805 if (!EVP_PKEY_missing_parameters(ktmp))
1809 X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1810 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1814 /* first, populate the other certs */
1815 for (j = i - 1; j >= 0; j--) {
1816 ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1817 EVP_PKEY_copy_parameters(ktmp2, ktmp);
1821 EVP_PKEY_copy_parameters(pkey, ktmp);
1825 /* Make a delta CRL as the diff between two full CRLs */
1827 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1828 EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1830 X509_CRL *crl = NULL;
1832 STACK_OF(X509_REVOKED) *revs = NULL;
1833 /* CRLs can't be delta already */
1834 if (base->base_crl_number || newer->base_crl_number) {
1835 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1838 /* Base and new CRL must have a CRL number */
1839 if (!base->crl_number || !newer->crl_number) {
1840 X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1843 /* Issuer names must match */
1844 if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
1845 X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
1848 /* AKID and IDP must match */
1849 if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
1850 X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
1853 if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
1854 X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
1857 /* Newer CRL number must exceed full CRL number */
1858 if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
1859 X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
1862 /* CRLs must verify */
1863 if (skey && (X509_CRL_verify(base, skey) <= 0 ||
1864 X509_CRL_verify(newer, skey) <= 0)) {
1865 X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
1868 /* Create new CRL */
1869 crl = X509_CRL_new();
1870 if (crl == NULL || !X509_CRL_set_version(crl, 1))
1872 /* Set issuer name */
1873 if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
1876 if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer)))
1878 if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer)))
1881 /* Set base CRL number: must be critical */
1883 if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
1887 * Copy extensions across from newest CRL to delta: this will set CRL
1888 * number to correct value too.
1891 for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
1892 X509_EXTENSION *ext;
1893 ext = X509_CRL_get_ext(newer, i);
1894 if (!X509_CRL_add_ext(crl, ext, -1))
1898 /* Go through revoked entries, copying as needed */
1900 revs = X509_CRL_get_REVOKED(newer);
1902 for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
1903 X509_REVOKED *rvn, *rvtmp;
1904 rvn = sk_X509_REVOKED_value(revs, i);
1906 * Add only if not also in base. TODO: need something cleverer here
1907 * for some more complex CRLs covering multiple CAs.
1909 if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
1910 rvtmp = X509_REVOKED_dup(rvn);
1913 if (!X509_CRL_add0_revoked(crl, rvtmp)) {
1914 X509_REVOKED_free(rvtmp);
1919 /* TODO: optionally prune deleted entries */
1921 if (skey && md && !X509_CRL_sign(crl, skey, md))
1927 X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
1932 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1934 return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1937 void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1939 return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1942 int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1947 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1952 int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1954 return ctx->error_depth;
1957 X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1959 return ctx->current_cert;
1962 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1967 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1971 return X509_chain_up_ref(ctx->chain);
1974 X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
1976 return ctx->current_issuer;
1979 X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
1981 return ctx->current_crl;
1984 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
1989 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
1994 void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
1996 ctx->untrusted = sk;
1999 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2004 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2006 return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2009 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2011 return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2015 * This function is used to set the X509_STORE_CTX purpose and trust values.
2016 * This is intended to be used when another structure has its own trust and
2017 * purpose values which (if set) will be inherited by the ctx. If they aren't
2018 * set then we will usually have a default purpose in mind which should then
2019 * be used to set the trust value. An example of this is SSL use: an SSL
2020 * structure will have its own purpose and trust settings which the
2021 * application can set: if they aren't set then we use the default of SSL
2025 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2026 int purpose, int trust)
2029 /* If purpose not set use default */
2031 purpose = def_purpose;
2032 /* If we have a purpose then check it is valid */
2035 idx = X509_PURPOSE_get_by_id(purpose);
2037 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2038 X509_R_UNKNOWN_PURPOSE_ID);
2041 ptmp = X509_PURPOSE_get0(idx);
2042 if (ptmp->trust == X509_TRUST_DEFAULT) {
2043 idx = X509_PURPOSE_get_by_id(def_purpose);
2045 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2046 X509_R_UNKNOWN_PURPOSE_ID);
2049 ptmp = X509_PURPOSE_get0(idx);
2051 /* If trust not set then get from purpose default */
2053 trust = ptmp->trust;
2056 idx = X509_TRUST_get_by_id(trust);
2058 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2059 X509_R_UNKNOWN_TRUST_ID);
2064 if (purpose && !ctx->param->purpose)
2065 ctx->param->purpose = purpose;
2066 if (trust && !ctx->param->trust)
2067 ctx->param->trust = trust;
2071 X509_STORE_CTX *X509_STORE_CTX_new(void)
2073 X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2076 X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
2082 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2086 X509_STORE_CTX_cleanup(ctx);
2090 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2091 STACK_OF(X509) *chain)
2096 ctx->current_method = 0;
2098 ctx->untrusted = chain;
2100 ctx->num_untrusted = 0;
2101 ctx->other_ctx = NULL;
2105 ctx->explicit_policy = 0;
2106 ctx->error_depth = 0;
2107 ctx->current_cert = NULL;
2108 ctx->current_issuer = NULL;
2109 ctx->current_crl = NULL;
2110 ctx->current_crl_score = 0;
2111 ctx->current_reasons = 0;
2115 ctx->bare_ta_signed = 0;
2116 /* Zero ex_data to make sure we're cleanup-safe */
2117 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2120 ctx->verify_cb = store->verify_cb;
2121 /* Seems to always be 0 in OpenSSL, else must be idempotent */
2122 ctx->cleanup = store->cleanup;
2126 if (store && store->check_issued)
2127 ctx->check_issued = store->check_issued;
2129 ctx->check_issued = check_issued;
2131 if (store && store->get_issuer)
2132 ctx->get_issuer = store->get_issuer;
2134 ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2136 if (store && store->verify_cb)
2137 ctx->verify_cb = store->verify_cb;
2139 ctx->verify_cb = null_callback;
2141 if (store && store->verify)
2142 ctx->verify = store->verify;
2144 ctx->verify = internal_verify;
2146 if (store && store->check_revocation)
2147 ctx->check_revocation = store->check_revocation;
2149 ctx->check_revocation = check_revocation;
2151 if (store && store->get_crl)
2152 ctx->get_crl = store->get_crl;
2154 if (store && store->check_crl)
2155 ctx->check_crl = store->check_crl;
2157 ctx->check_crl = check_crl;
2159 if (store && store->cert_crl)
2160 ctx->cert_crl = store->cert_crl;
2162 ctx->cert_crl = cert_crl;
2164 if (store && store->lookup_certs)
2165 ctx->lookup_certs = store->lookup_certs;
2167 ctx->lookup_certs = X509_STORE_get1_certs;
2169 if (store && store->lookup_crls)
2170 ctx->lookup_crls = store->lookup_crls;
2172 ctx->lookup_crls = X509_STORE_get1_crls;
2174 ctx->check_policy = check_policy;
2176 ctx->param = X509_VERIFY_PARAM_new();
2177 if (ctx->param == NULL) {
2178 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2183 * Inherit callbacks and flags from X509_STORE if not set use defaults.
2186 ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2188 ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2191 ret = X509_VERIFY_PARAM_inherit(ctx->param,
2192 X509_VERIFY_PARAM_lookup("default"));
2195 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2199 if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2202 X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2206 * On error clean up allocated storage, if the store context was not
2207 * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2209 X509_STORE_CTX_cleanup(ctx);
2214 * Set alternative lookup method: just a STACK of trusted certificates. This
2215 * avoids X509_STORE nastiness where it isn't needed.
2218 void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2220 ctx->other_ctx = sk;
2221 ctx->get_issuer = get_issuer_sk;
2224 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2227 * We need to be idempotent because, unfortunately, free() also calls
2228 * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2229 * calls cleanup() for the same object twice! Thus we must zero the
2230 * pointers below after they're freed!
2232 /* Seems to always be 0 in OpenSSL, do this at most once. */
2233 if (ctx->cleanup != NULL) {
2235 ctx->cleanup = NULL;
2237 if (ctx->param != NULL) {
2238 if (ctx->parent == NULL)
2239 X509_VERIFY_PARAM_free(ctx->param);
2242 X509_policy_tree_free(ctx->tree);
2244 sk_X509_pop_free(ctx->chain, X509_free);
2246 CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2247 memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2250 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2252 X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2255 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2257 X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2260 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2263 X509_VERIFY_PARAM_set_time(ctx->param, t);
2266 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2267 int (*verify_cb) (int, X509_STORE_CTX *))
2269 ctx->verify_cb = verify_cb;
2272 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2277 int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2279 return ctx->explicit_policy;
2282 int X509_STORE_CTX_get_num_untrusted(X509_STORE_CTX *ctx)
2284 return ctx->num_untrusted;
2287 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2289 const X509_VERIFY_PARAM *param;
2290 param = X509_VERIFY_PARAM_lookup(name);
2293 return X509_VERIFY_PARAM_inherit(ctx->param, param);
2296 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2301 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2303 X509_VERIFY_PARAM_free(ctx->param);
2307 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, struct dane_st *dane)
2312 static unsigned char *dane_i2d(
2315 unsigned int *i2dlen)
2317 unsigned char *buf = NULL;
2321 * Extract ASN.1 DER form of certificate or public key.
2324 case DANETLS_SELECTOR_CERT:
2325 len = i2d_X509(cert, &buf);
2327 case DANETLS_SELECTOR_SPKI:
2328 len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2331 X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2335 if (len < 0 || buf == NULL) {
2336 X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2340 *i2dlen = (unsigned int)len;
2344 #define DANETLS_NONE 256 /* impossible uint8_t */
2346 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2348 struct dane_st *dane = (struct dane_st *)ctx->dane;
2349 unsigned usage = DANETLS_NONE;
2350 unsigned selector = DANETLS_NONE;
2351 unsigned ordinal = DANETLS_NONE;
2352 unsigned mtype = DANETLS_NONE;
2353 unsigned char *i2dbuf = NULL;
2354 unsigned int i2dlen = 0;
2355 unsigned char mdbuf[EVP_MAX_MD_SIZE];
2356 unsigned char *cmpbuf = NULL;
2357 unsigned int cmplen = 0;
2361 danetls_record *t = NULL;
2364 mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2367 * The trust store is not applicable with DANE-TA(2)
2369 if (depth >= ctx->num_untrusted)
2370 mask &= DANETLS_PKIX_MASK;
2373 * If we've previously matched a PKIX-?? record, no need to test any
2374 * furher PKIX-?? records, it remains to just build the PKIX chain.
2375 * Had the match been a DANE-?? record, we'd be done already.
2377 if (dane->mdpth >= 0)
2378 mask &= ~DANETLS_PKIX_MASK;
2381 * https://tools.ietf.org/html/rfc7671#section-5.1
2382 * https://tools.ietf.org/html/rfc7671#section-5.2
2383 * https://tools.ietf.org/html/rfc7671#section-5.3
2384 * https://tools.ietf.org/html/rfc7671#section-5.4
2386 * We handle DANE-EE(3) records first as they require no chain building
2387 * and no expiration or hostname checks. We also process digests with
2388 * higher ordinals first and ignore lower priorities except Full(0) which
2389 * is always processed (last). If none match, we then process PKIX-EE(1).
2391 * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2392 * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2393 * priorities. See twin comment in ssl/ssl_lib.c.
2395 * We expect that most TLSA RRsets will have just a single usage, so we
2396 * don't go out of our way to cache multiple selector-specific i2d buffers
2397 * across usages, but if the selector happens to remain the same as switch
2398 * usages, that's OK. Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2399 * records would result in us generating each of the certificate and public
2400 * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2401 * or multiple "3 0 1" records.
2403 * As soon as we find a match at any given depth, we stop, because either
2404 * we've matched a DANE-?? record and the peer is authenticated, or, after
2405 * exhausing all DANE-?? records, we've matched a PKIX-?? record, which is
2406 * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2408 recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2409 for (i = 0; matched == 0 && i < recnum; ++i) {
2410 t = sk_danetls_record_value(dane->trecs, i);
2411 if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2413 if (t->usage != usage) {
2416 /* Reset digest agility for each usage/selector pair */
2417 mtype = DANETLS_NONE;
2418 ordinal = dane->dctx->mdord[t->mtype];
2420 if (t->selector != selector) {
2421 selector = t->selector;
2423 /* Update per-selector state */
2424 OPENSSL_free(i2dbuf);
2425 i2dbuf = dane_i2d(cert, selector, &i2dlen);
2429 /* Reset digest agility for each usage/selector pair */
2430 mtype = DANETLS_NONE;
2431 ordinal = dane->dctx->mdord[t->mtype];
2432 } else if (t->mtype != DANETLS_MATCHING_FULL) {
2436 * <https://tools.ietf.org/html/rfc7671#section-9>
2438 * For a fixed selector, after processing all records with the
2439 * highest mtype ordinal, ignore all mtypes with lower ordinals
2440 * other than "Full".
2442 if (dane->dctx->mdord[t->mtype] < ordinal)
2447 * Each time we hit a (new selector or) mtype, re-compute the relevant
2448 * digest, more complex caching is not worth the code space.
2450 if (t->mtype != mtype) {
2451 const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2457 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2465 * Squirrel away the certificate and depth if we have a match. Any
2466 * DANE match is dispositive, but with PKIX we still need to build a
2469 if (cmplen == t->dlen &&
2470 memcmp(cmpbuf, t->data, cmplen) == 0) {
2471 if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2473 if (matched || dane->mdpth < 0) {
2474 dane->mdpth = depth;
2476 OPENSSL_free(dane->mcert);
2484 /* Clear the one-element DER cache */
2485 OPENSSL_free(i2dbuf);
2489 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2491 struct dane_st *dane = (struct dane_st *)ctx->dane;
2495 if (!DANETLS_HAS_TA(dane) || depth == 0)
2496 return X509_TRUST_UNTRUSTED;
2499 * Record any DANE trust anchor matches, for the first depth to test, if
2500 * there's one at that depth. (This'll be false for length 1 chains looking
2501 * for an exact match for the leaf certificate).
2503 cert = sk_X509_value(ctx->chain, depth);
2504 if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2505 return X509_TRUST_REJECTED;
2507 ctx->num_untrusted = depth - 1;
2508 return X509_TRUST_TRUSTED;
2511 return X509_TRUST_UNTRUSTED;
2514 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2516 struct dane_st *dane = (struct dane_st *)ctx->dane;
2518 int num = ctx->num_untrusted;
2519 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2520 int recnum = sk_danetls_record_num(dane->trecs);
2523 for (i = 0; i < recnum; ++i) {
2524 t = sk_danetls_record_value(dane->trecs, i);
2525 if (t->usage != DANETLS_USAGE_DANE_TA ||
2526 t->selector != DANETLS_SELECTOR_SPKI ||
2527 t->mtype != DANETLS_MATCHING_FULL ||
2528 X509_verify(cert, t->spki) <= 0)
2531 /* Clear PKIX-?? matches that failed to panned out to a full chain */
2532 X509_free(dane->mcert);
2535 /* Record match via a bare TA public key */
2536 ctx->bare_ta_signed = 1;
2537 dane->mdpth = num - 1;
2540 /* Prune any excess chain certificates */
2541 num = sk_X509_num(ctx->chain);
2542 for (; num > ctx->num_untrusted; --num)
2543 X509_free(sk_X509_pop(ctx->chain));
2545 return X509_TRUST_TRUSTED;
2548 return X509_TRUST_UNTRUSTED;
2551 static void dane_reset(struct dane_st *dane)
2554 * Reset state to verify another chain, or clear after failure.
2556 X509_free(dane->mcert);
2563 static int dane_verify(X509_STORE_CTX *ctx)
2565 X509 *cert = ctx->cert;
2566 int (*cb)(int xok, X509_STORE_CTX *xctx) = ctx->verify_cb;
2567 struct dane_st *dane = (struct dane_st *)ctx->dane;
2573 matched = dane_match(ctx, ctx->cert, 0);
2574 done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2577 X509_get_pubkey_parameters(NULL, ctx->chain);
2580 ctx->error_depth = 0;
2581 ctx->current_cert = cert;
2586 ctx->error_depth = 0;
2587 ctx->current_cert = cert;
2588 ctx->error = X509_V_ERR_OUT_OF_MEM;
2593 /* Fail early, TA-based success is not possible */
2594 ctx->current_cert = cert;
2595 ctx->error_depth = 0;
2596 ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2601 * Chain verification for usages 0/1/2. TLSA record matching of depth > 0
2602 * certificates happens in-line with building the rest of the chain.
2604 return verify_chain(ctx);
2607 static int build_chain(X509_STORE_CTX *ctx)
2609 struct dane_st *dane = (struct dane_st *)ctx->dane;
2610 int (*cb) (int, X509_STORE_CTX *) = ctx->verify_cb;
2611 int num = sk_X509_num(ctx->chain);
2612 X509 *cert = sk_X509_value(ctx->chain, num - 1);
2613 int ss = cert_self_signed(cert);
2614 STACK_OF(X509) *sktmp = NULL;
2615 unsigned int search;
2616 int may_trusted = 0;
2617 int may_alternate = 0;
2618 int trust = X509_TRUST_UNTRUSTED;
2619 int alt_untrusted = 0;
2624 /* Our chain starts with a single untrusted element. */
2625 OPENSSL_assert(num == 1 && ctx->num_untrusted == num);
2627 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
2628 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
2629 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
2631 * Set up search policy, untrusted if possible, trusted-first if enabled.
2632 * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2633 * trust_store, otherwise we might look there first. If not trusted-first,
2634 * and alternate chains are not disabled, try building an alternate chain
2635 * if no luck with untrusted first.
2637 search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2638 if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2639 if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2640 search |= S_DOTRUSTED;
2641 else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2647 * Shallow-copy the stack of untrusted certificates (with TLS, this is
2648 * typically the content of the peer's certificate message) so can make
2649 * multiple passes over it, while free to remove elements as we go.
2651 if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
2652 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2656 /* Include any untrusted full certificates from DNS */
2657 if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
2658 for (i = 0; i < sk_X509_num(dane->certs); ++i) {
2659 if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
2660 sk_X509_free(sktmp);
2661 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2668 * Still absurdly large, but arithmetically safe, a lower hard upper bound
2669 * might be reasonable.
2671 if (ctx->param->depth > INT_MAX/2)
2672 ctx->param->depth = INT_MAX/2;
2675 * Try to Extend the chain until we reach an ultimately trusted issuer.
2676 * Build chains up to one longer the limit, later fail if we hit the limit,
2677 * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
2679 depth = ctx->param->depth + 1;
2681 while (search != 0) {
2686 * Look in the trust store if enabled for first lookup, or we've run
2687 * out of untrusted issuers and search here is not disabled. When
2688 * we exceed the depth limit, we simulate absence of a match.
2690 if ((search & S_DOTRUSTED) != 0) {
2691 STACK_OF(X509) *hide = ctx->chain;
2693 i = num = sk_X509_num(ctx->chain);
2694 if ((search & S_DOALTERNATE) != 0) {
2696 * As high up the chain as we can, look for an alternative
2697 * trusted issuer of an untrusted certificate that currently
2698 * has an untrusted issuer. We use the alt_untrusted variable
2699 * to track how far up the chain we find the first match. It
2700 * is only if and when we find a match, that we prune the chain
2701 * and reset ctx->num_untrusted to the reduced count of
2702 * untrusted certificates. While we're searching for such a
2703 * match (which may never be found), it is neither safe nor
2704 * wise to preemptively modify either the chain or
2705 * ctx->num_untrusted.
2707 * Note, like ctx->num_untrusted, alt_untrusted is a count of
2708 * untrusted certificates, not a "depth".
2712 x = sk_X509_value(ctx->chain, i-1);
2714 /* Suppress duplicate suppression */
2716 ok = (depth < num) ? 0 : ctx->get_issuer(&xtmp, ctx, x);
2720 trust = X509_TRUST_REJECTED;
2727 * Alternative trusted issuer for a mid-chain untrusted cert?
2728 * Pop the untrusted cert's successors and retry. We might now
2729 * be able to complete a valid chain via the trust store. Note
2730 * that despite the current trust-store match we might still
2731 * fail complete the chain to a suitable trust-anchor, in which
2732 * case we may prune some more untrusted certificates and try
2733 * again. Thus the S_DOALTERNATE bit may yet be turned on
2734 * again with an even shorter untrusted chain!
2736 * If in the process we threw away our matching PKIX-TA trust
2737 * anchor, reset DANE trust. We might find a suitable trusted
2738 * certificate among the ones from the trust store.
2740 if ((search & S_DOALTERNATE) != 0) {
2741 OPENSSL_assert(num > i && i > 0 && ss == 0);
2742 search &= ~S_DOALTERNATE;
2743 for (; num > i; --num)
2744 X509_free(sk_X509_pop(ctx->chain));
2745 ctx->num_untrusted = num;
2747 if (DANETLS_ENABLED(dane) &&
2748 dane->mdpth >= ctx->num_untrusted) {
2750 X509_free(dane->mcert);
2753 if (DANETLS_ENABLED(dane) &&
2754 dane->pdpth >= ctx->num_untrusted)
2759 * Self-signed untrusted certificates get replaced by their
2760 * trusted matching issuer. Otherwise, grow the chain.
2763 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2765 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2766 trust = X509_TRUST_REJECTED;
2770 ss = cert_self_signed(x);
2771 } else if (num == ctx->num_untrusted) {
2773 * We have a self-signed certificate that has the same
2774 * subject name (and perhaps keyid and/or serial number) as
2775 * a trust-anchor. We must have an exact match to avoid
2776 * possible impersonation via key substitution etc.
2778 if (X509_cmp(x, xtmp) != 0) {
2779 /* Self-signed untrusted mimic. */
2784 ctx->num_untrusted = --num;
2785 (void) sk_X509_set(ctx->chain, num, x = xtmp);
2790 * We've added a new trusted certificate to the chain, recheck
2791 * trust. If not done, and not self-signed look deeper.
2792 * Whether or not we're doing "trusted first", we no longer
2793 * look for untrusted certificates from the peer's chain.
2795 * At this point ctx->num_trusted and num must reflect the
2796 * correct number of untrusted certificates, since the DANE
2797 * logic in check_trust() depends on distinguishing CAs from
2798 * "the wire" from CAs from the trust store. In particular, the
2799 * certificate at depth "num" should be the new trusted
2800 * certificate with ctx->num_untrusted <= num.
2803 OPENSSL_assert(ctx->num_untrusted <= num);
2804 search &= ~S_DOUNTRUSTED;
2805 switch (trust = check_trust(ctx, num)) {
2806 case X509_TRUST_TRUSTED:
2807 case X509_TRUST_REJECTED:
2817 * No dispositive decision, and either self-signed or no match, if
2818 * we were doing untrusted-first, and alt-chains are not disabled,
2819 * do that, by repeatedly losing one untrusted element at a time,
2820 * and trying to extend the shorted chain.
2822 if ((search & S_DOUNTRUSTED) == 0) {
2823 /* Continue search for a trusted issuer of a shorter chain? */
2824 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
2826 /* Still no luck and no fallbacks left? */
2827 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
2828 ctx->num_untrusted < 2)
2830 /* Search for a trusted issuer of a shorter chain */
2831 search |= S_DOALTERNATE;
2832 alt_untrusted = ctx->num_untrusted - 1;
2838 * Extend chain with peer-provided certificates
2840 if ((search & S_DOUNTRUSTED) != 0) {
2841 num = sk_X509_num(ctx->chain);
2842 OPENSSL_assert(num == ctx->num_untrusted);
2843 x = sk_X509_value(ctx->chain, num-1);
2844 xtmp = (depth < num) ? NULL : find_issuer(ctx, sktmp, x);
2847 * Once we run out of untrusted issuers, we stop looking for more
2848 * and start looking only in the trust store if enabled.
2851 search &= ~S_DOUNTRUSTED;
2853 search |= S_DOTRUSTED;
2857 if (!sk_X509_push(ctx->chain, x = xtmp)) {
2858 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
2859 trust = X509_TRUST_REJECTED;
2864 ++ctx->num_untrusted;
2865 ss = cert_self_signed(xtmp);
2868 * Not strictly necessary, but saves cycles looking at the same
2869 * certificates over and over.
2871 (void) sk_X509_delete_ptr(sktmp, x);
2874 * Check for DANE-TA trust of the topmost untrusted certificate.
2876 switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
2877 case X509_TRUST_TRUSTED:
2878 case X509_TRUST_REJECTED:
2884 sk_X509_free(sktmp);
2887 * Last chance to make a trusted chain, either bare DANE-TA public-key
2888 * signers, or else direct leaf PKIX trust.
2890 if (sk_X509_num(ctx->chain) <= depth) {
2891 if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
2892 trust = check_dane_pkeys(ctx);
2893 if (trust == X509_TRUST_UNTRUSTED &&
2894 sk_X509_num(ctx->chain) == ctx->num_untrusted)
2895 trust = check_trust(ctx, 1);
2899 case X509_TRUST_TRUSTED:
2901 case X509_TRUST_REJECTED:
2903 case X509_TRUST_UNTRUSTED:
2905 num = sk_X509_num(ctx->chain);
2906 ctx->current_cert = sk_X509_value(ctx->chain, num - 1);
2907 ctx->error_depth = num-1;
2909 ctx->error = X509_V_ERR_CERT_CHAIN_TOO_LONG;
2910 else if (DANETLS_ENABLED(dane) &&
2911 (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
2912 ctx->error = X509_V_ERR_CERT_UNTRUSTED;
2913 else if (ss && sk_X509_num(ctx->chain) == 1)
2914 ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
2916 ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2917 else if (ctx->num_untrusted == num)
2918 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
2920 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
2921 if (DANETLS_ENABLED(dane))