x509_vfy.c revision 296341
1/* crypto/x509/x509_vfy.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
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.
8 *
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).
15 *
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.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
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)"
40 *
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
51 * SUCH DAMAGE.
52 *
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.]
57 */
58
59#include <stdio.h>
60#include <time.h>
61#include <errno.h>
62
63#include "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
73/* CRL score values */
74
75/* No unhandled critical extensions */
76
77#define CRL_SCORE_NOCRITICAL    0x100
78
79/* certificate is within CRL scope */
80
81#define CRL_SCORE_SCOPE         0x080
82
83/* CRL times valid */
84
85#define CRL_SCORE_TIME          0x040
86
87/* Issuer name matches certificate */
88
89#define CRL_SCORE_ISSUER_NAME   0x020
90
91/* If this score or above CRL is probably valid */
92
93#define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
94
95/* CRL issuer is certificate issuer */
96
97#define CRL_SCORE_ISSUER_CERT   0x018
98
99/* CRL issuer is on certificate path */
100
101#define CRL_SCORE_SAME_PATH     0x008
102
103/* CRL issuer matches CRL AKID */
104
105#define CRL_SCORE_AKID          0x004
106
107/* Have a delta CRL with valid times */
108
109#define CRL_SCORE_TIME_DELTA    0x002
110
111static int null_callback(int ok, X509_STORE_CTX *e);
112static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
113static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
114static int check_chain_extensions(X509_STORE_CTX *ctx);
115static int check_name_constraints(X509_STORE_CTX *ctx);
116static int check_trust(X509_STORE_CTX *ctx);
117static int check_revocation(X509_STORE_CTX *ctx);
118static int check_cert(X509_STORE_CTX *ctx);
119static int check_policy(X509_STORE_CTX *ctx);
120
121static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
122                         unsigned int *preasons, X509_CRL *crl, X509 *x);
123static int get_crl_delta(X509_STORE_CTX *ctx,
124                         X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
125static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
126                         int *pcrl_score, X509_CRL *base,
127                         STACK_OF(X509_CRL) *crls);
128static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
129                           int *pcrl_score);
130static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
131                           unsigned int *preasons);
132static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
133static int check_crl_chain(X509_STORE_CTX *ctx,
134                           STACK_OF(X509) *cert_path,
135                           STACK_OF(X509) *crl_path);
136
137static int internal_verify(X509_STORE_CTX *ctx);
138const char X509_version[] = "X.509" OPENSSL_VERSION_PTEXT;
139
140static int null_callback(int ok, X509_STORE_CTX *e)
141{
142    return ok;
143}
144
145#if 0
146static int x509_subject_cmp(X509 **a, X509 **b)
147{
148    return X509_subject_name_cmp(*a, *b);
149}
150#endif
151
152int X509_verify_cert(X509_STORE_CTX *ctx)
153{
154    X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
155    int bad_chain = 0;
156    X509_VERIFY_PARAM *param = ctx->param;
157    int depth, i, ok = 0;
158    int num, j, retry;
159    int (*cb) (int xok, X509_STORE_CTX *xctx);
160    STACK_OF(X509) *sktmp = NULL;
161    if (ctx->cert == NULL) {
162        X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
163        return -1;
164    }
165    if (ctx->chain != NULL) {
166        /*
167         * This X509_STORE_CTX has already been used to verify a cert. We
168         * cannot do another one.
169         */
170        X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
171        return -1;
172    }
173
174    cb = ctx->verify_cb;
175
176    /*
177     * first we make sure the chain we are going to build is present and that
178     * the first entry is in place
179     */
180    if (((ctx->chain = sk_X509_new_null()) == NULL) ||
181        (!sk_X509_push(ctx->chain, ctx->cert))) {
182        X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
183        goto end;
184    }
185    CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
186    ctx->last_untrusted = 1;
187
188    /* We use a temporary STACK so we can chop and hack at it */
189    if (ctx->untrusted != NULL
190        && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
191        X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
192        goto end;
193    }
194
195    num = sk_X509_num(ctx->chain);
196    x = sk_X509_value(ctx->chain, num - 1);
197    depth = param->depth;
198
199    for (;;) {
200        /* If we have enough, we break */
201        if (depth < num)
202            break;              /* FIXME: If this happens, we should take
203                                 * note of it and, if appropriate, use the
204                                 * X509_V_ERR_CERT_CHAIN_TOO_LONG error code
205                                 * later. */
206
207        /* If we are self signed, we break */
208        if (ctx->check_issued(ctx, x, x))
209            break;
210
211        /* If we were passed a cert chain, use it first */
212        if (ctx->untrusted != NULL) {
213            xtmp = find_issuer(ctx, sktmp, x);
214            if (xtmp != NULL) {
215                if (!sk_X509_push(ctx->chain, xtmp)) {
216                    X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
217                    goto end;
218                }
219                CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
220                (void)sk_X509_delete_ptr(sktmp, xtmp);
221                ctx->last_untrusted++;
222                x = xtmp;
223                num++;
224                /*
225                 * reparse the full chain for the next one
226                 */
227                continue;
228            }
229        }
230        break;
231    }
232
233    /* Remember how many untrusted certs we have */
234    j = num;
235    /*
236     * at this point, chain should contain a list of untrusted certificates.
237     * We now need to add at least one trusted one, if possible, otherwise we
238     * complain.
239     */
240
241    do {
242        /*
243         * Examine last certificate in chain and see if it is self signed.
244         */
245        i = sk_X509_num(ctx->chain);
246        x = sk_X509_value(ctx->chain, i - 1);
247        if (ctx->check_issued(ctx, x, x)) {
248            /* we have a self signed certificate */
249            if (sk_X509_num(ctx->chain) == 1) {
250                /*
251                 * We have a single self signed certificate: see if we can
252                 * find it in the store. We must have an exact match to avoid
253                 * possible impersonation.
254                 */
255                ok = ctx->get_issuer(&xtmp, ctx, x);
256                if ((ok <= 0) || X509_cmp(x, xtmp)) {
257                    ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
258                    ctx->current_cert = x;
259                    ctx->error_depth = i - 1;
260                    if (ok == 1)
261                        X509_free(xtmp);
262                    bad_chain = 1;
263                    ok = cb(0, ctx);
264                    if (!ok)
265                        goto end;
266                } else {
267                    /*
268                     * We have a match: replace certificate with store
269                     * version so we get any trust settings.
270                     */
271                    X509_free(x);
272                    x = xtmp;
273                    (void)sk_X509_set(ctx->chain, i - 1, x);
274                    ctx->last_untrusted = 0;
275                }
276            } else {
277                /*
278                 * extract and save self signed certificate for later use
279                 */
280                chain_ss = sk_X509_pop(ctx->chain);
281                ctx->last_untrusted--;
282                num--;
283                j--;
284                x = sk_X509_value(ctx->chain, num - 1);
285            }
286        }
287        /* We now lookup certs from the certificate store */
288        for (;;) {
289            /* If we have enough, we break */
290            if (depth < num)
291                break;
292            /* If we are self signed, we break */
293            if (ctx->check_issued(ctx, x, x))
294                break;
295            ok = ctx->get_issuer(&xtmp, ctx, x);
296            if (ok < 0)
297                return ok;
298            if (ok == 0)
299                break;
300            x = xtmp;
301            if (!sk_X509_push(ctx->chain, x)) {
302                X509_free(xtmp);
303                X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
304                return 0;
305            }
306            num++;
307        }
308
309        /*
310         * If we haven't got a least one certificate from our store then check
311         * if there is an alternative chain that could be used.  We only do this
312         * if the user hasn't switched off alternate chain checking
313         */
314        retry = 0;
315        if (num == ctx->last_untrusted &&
316            !(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
317            while (j-- > 1) {
318                xtmp2 = sk_X509_value(ctx->chain, j - 1);
319                ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
320                if (ok < 0)
321                    goto end;
322                /* Check if we found an alternate chain */
323                if (ok > 0) {
324                    /*
325                     * Free up the found cert we'll add it again later
326                     */
327                    X509_free(xtmp);
328
329                    /*
330                     * Dump all the certs above this point - we've found an
331                     * alternate chain
332                     */
333                    while (num > j) {
334                        xtmp = sk_X509_pop(ctx->chain);
335                        X509_free(xtmp);
336                        num--;
337                    }
338                    ctx->last_untrusted = sk_X509_num(ctx->chain);
339                    retry = 1;
340                    break;
341                }
342            }
343        }
344    } while (retry);
345
346    /* Is last certificate looked up self signed? */
347    if (!ctx->check_issued(ctx, x, x)) {
348        if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
349            if (ctx->last_untrusted >= num)
350                ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
351            else
352                ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
353            ctx->current_cert = x;
354        } else {
355
356            sk_X509_push(ctx->chain, chain_ss);
357            num++;
358            ctx->last_untrusted = num;
359            ctx->current_cert = chain_ss;
360            ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
361            chain_ss = NULL;
362        }
363
364        ctx->error_depth = num - 1;
365        bad_chain = 1;
366        ok = cb(0, ctx);
367        if (!ok)
368            goto end;
369    }
370
371    /* We have the chain complete: now we need to check its purpose */
372    ok = check_chain_extensions(ctx);
373
374    if (!ok)
375        goto end;
376
377    /* Check name constraints */
378
379    ok = check_name_constraints(ctx);
380
381    if (!ok)
382        goto end;
383
384    /* The chain extensions are OK: check trust */
385
386    if (param->trust > 0)
387        ok = check_trust(ctx);
388
389    if (!ok)
390        goto end;
391
392    /* We may as well copy down any DSA parameters that are required */
393    X509_get_pubkey_parameters(NULL, ctx->chain);
394
395    /*
396     * Check revocation status: we do this after copying parameters because
397     * they may be needed for CRL signature verification.
398     */
399
400    ok = ctx->check_revocation(ctx);
401    if (!ok)
402        goto end;
403
404    /* At this point, we have a chain and need to verify it */
405    if (ctx->verify != NULL)
406        ok = ctx->verify(ctx);
407    else
408        ok = internal_verify(ctx);
409    if (!ok)
410        goto end;
411
412#ifndef OPENSSL_NO_RFC3779
413    /* RFC 3779 path validation, now that CRL check has been done */
414    ok = v3_asid_validate_path(ctx);
415    if (!ok)
416        goto end;
417    ok = v3_addr_validate_path(ctx);
418    if (!ok)
419        goto end;
420#endif
421
422    /* If we get this far evaluate policies */
423    if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
424        ok = ctx->check_policy(ctx);
425    if (!ok)
426        goto end;
427    if (0) {
428 end:
429        X509_get_pubkey_parameters(NULL, ctx->chain);
430    }
431    if (sktmp != NULL)
432        sk_X509_free(sktmp);
433    if (chain_ss != NULL)
434        X509_free(chain_ss);
435    return ok;
436}
437
438/*
439 * Given a STACK_OF(X509) find the issuer of cert (if any)
440 */
441
442static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
443{
444    int i;
445    X509 *issuer;
446    for (i = 0; i < sk_X509_num(sk); i++) {
447        issuer = sk_X509_value(sk, i);
448        if (ctx->check_issued(ctx, x, issuer))
449            return issuer;
450    }
451    return NULL;
452}
453
454/* Given a possible certificate and issuer check them */
455
456static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
457{
458    int ret;
459    ret = X509_check_issued(issuer, x);
460    if (ret == X509_V_OK)
461        return 1;
462    /* If we haven't asked for issuer errors don't set ctx */
463    if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
464        return 0;
465
466    ctx->error = ret;
467    ctx->current_cert = x;
468    ctx->current_issuer = issuer;
469    return ctx->verify_cb(0, ctx);
470    return 0;
471}
472
473/* Alternative lookup method: look from a STACK stored in other_ctx */
474
475static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
476{
477    *issuer = find_issuer(ctx, ctx->other_ctx, x);
478    if (*issuer) {
479        CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
480        return 1;
481    } else
482        return 0;
483}
484
485/*
486 * Check a certificate chains extensions for consistency with the supplied
487 * purpose
488 */
489
490static int check_chain_extensions(X509_STORE_CTX *ctx)
491{
492#ifdef OPENSSL_NO_CHAIN_VERIFY
493    return 1;
494#else
495    int i, ok = 0, must_be_ca, plen = 0;
496    X509 *x;
497    int (*cb) (int xok, X509_STORE_CTX *xctx);
498    int proxy_path_length = 0;
499    int purpose;
500    int allow_proxy_certs;
501    cb = ctx->verify_cb;
502
503    /*-
504     *  must_be_ca can have 1 of 3 values:
505     * -1: we accept both CA and non-CA certificates, to allow direct
506     *     use of self-signed certificates (which are marked as CA).
507     * 0:  we only accept non-CA certificates.  This is currently not
508     *     used, but the possibility is present for future extensions.
509     * 1:  we only accept CA certificates.  This is currently used for
510     *     all certificates in the chain except the leaf certificate.
511     */
512    must_be_ca = -1;
513
514    /* CRL path validation */
515    if (ctx->parent) {
516        allow_proxy_certs = 0;
517        purpose = X509_PURPOSE_CRL_SIGN;
518    } else {
519        allow_proxy_certs =
520            ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
521        /*
522         * A hack to keep people who don't want to modify their software
523         * happy
524         */
525        if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
526            allow_proxy_certs = 1;
527        purpose = ctx->param->purpose;
528    }
529
530    /* Check all untrusted certificates */
531    for (i = 0; i < ctx->last_untrusted; i++) {
532        int ret;
533        x = sk_X509_value(ctx->chain, i);
534        if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
535            && (x->ex_flags & EXFLAG_CRITICAL)) {
536            ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
537            ctx->error_depth = i;
538            ctx->current_cert = x;
539            ok = cb(0, ctx);
540            if (!ok)
541                goto end;
542        }
543        if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
544            ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
545            ctx->error_depth = i;
546            ctx->current_cert = x;
547            ok = cb(0, ctx);
548            if (!ok)
549                goto end;
550        }
551        ret = X509_check_ca(x);
552        switch (must_be_ca) {
553        case -1:
554            if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
555                && (ret != 1) && (ret != 0)) {
556                ret = 0;
557                ctx->error = X509_V_ERR_INVALID_CA;
558            } else
559                ret = 1;
560            break;
561        case 0:
562            if (ret != 0) {
563                ret = 0;
564                ctx->error = X509_V_ERR_INVALID_NON_CA;
565            } else
566                ret = 1;
567            break;
568        default:
569            if ((ret == 0)
570                || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
571                    && (ret != 1))) {
572                ret = 0;
573                ctx->error = X509_V_ERR_INVALID_CA;
574            } else
575                ret = 1;
576            break;
577        }
578        if (ret == 0) {
579            ctx->error_depth = i;
580            ctx->current_cert = x;
581            ok = cb(0, ctx);
582            if (!ok)
583                goto end;
584        }
585        if (ctx->param->purpose > 0) {
586            ret = X509_check_purpose(x, purpose, must_be_ca > 0);
587            if ((ret == 0)
588                || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
589                    && (ret != 1))) {
590                ctx->error = X509_V_ERR_INVALID_PURPOSE;
591                ctx->error_depth = i;
592                ctx->current_cert = x;
593                ok = cb(0, ctx);
594                if (!ok)
595                    goto end;
596            }
597        }
598        /* Check pathlen if not self issued */
599        if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
600            && (x->ex_pathlen != -1)
601            && (plen > (x->ex_pathlen + proxy_path_length + 1))) {
602            ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
603            ctx->error_depth = i;
604            ctx->current_cert = x;
605            ok = cb(0, ctx);
606            if (!ok)
607                goto end;
608        }
609        /* Increment path length if not self issued */
610        if (!(x->ex_flags & EXFLAG_SI))
611            plen++;
612        /*
613         * If this certificate is a proxy certificate, the next certificate
614         * must be another proxy certificate or a EE certificate.  If not,
615         * the next certificate must be a CA certificate.
616         */
617        if (x->ex_flags & EXFLAG_PROXY) {
618            if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
619                ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
620                ctx->error_depth = i;
621                ctx->current_cert = x;
622                ok = cb(0, ctx);
623                if (!ok)
624                    goto end;
625            }
626            proxy_path_length++;
627            must_be_ca = 0;
628        } else
629            must_be_ca = 1;
630    }
631    ok = 1;
632 end:
633    return ok;
634#endif
635}
636
637static int check_name_constraints(X509_STORE_CTX *ctx)
638{
639    X509 *x;
640    int i, j, rv;
641    /* Check name constraints for all certificates */
642    for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
643        x = sk_X509_value(ctx->chain, i);
644        /* Ignore self issued certs unless last in chain */
645        if (i && (x->ex_flags & EXFLAG_SI))
646            continue;
647        /*
648         * Check against constraints for all certificates higher in chain
649         * including trust anchor. Trust anchor not strictly speaking needed
650         * but if it includes constraints it is to be assumed it expects them
651         * to be obeyed.
652         */
653        for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
654            NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
655            if (nc) {
656                rv = NAME_CONSTRAINTS_check(x, nc);
657                if (rv != X509_V_OK) {
658                    ctx->error = rv;
659                    ctx->error_depth = i;
660                    ctx->current_cert = x;
661                    if (!ctx->verify_cb(0, ctx))
662                        return 0;
663                }
664            }
665        }
666    }
667    return 1;
668}
669
670static int check_trust(X509_STORE_CTX *ctx)
671{
672#ifdef OPENSSL_NO_CHAIN_VERIFY
673    return 1;
674#else
675    int i, ok;
676    X509 *x;
677    int (*cb) (int xok, X509_STORE_CTX *xctx);
678    cb = ctx->verify_cb;
679/* For now just check the last certificate in the chain */
680    i = sk_X509_num(ctx->chain) - 1;
681    x = sk_X509_value(ctx->chain, i);
682    ok = X509_check_trust(x, ctx->param->trust, 0);
683    if (ok == X509_TRUST_TRUSTED)
684        return 1;
685    ctx->error_depth = i;
686    ctx->current_cert = x;
687    if (ok == X509_TRUST_REJECTED)
688        ctx->error = X509_V_ERR_CERT_REJECTED;
689    else
690        ctx->error = X509_V_ERR_CERT_UNTRUSTED;
691    ok = cb(0, ctx);
692    return ok;
693#endif
694}
695
696static int check_revocation(X509_STORE_CTX *ctx)
697{
698    int i, last, ok;
699    if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
700        return 1;
701    if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
702        last = sk_X509_num(ctx->chain) - 1;
703    else {
704        /* If checking CRL paths this isn't the EE certificate */
705        if (ctx->parent)
706            return 1;
707        last = 0;
708    }
709    for (i = 0; i <= last; i++) {
710        ctx->error_depth = i;
711        ok = check_cert(ctx);
712        if (!ok)
713            return ok;
714    }
715    return 1;
716}
717
718static int check_cert(X509_STORE_CTX *ctx)
719{
720    X509_CRL *crl = NULL, *dcrl = NULL;
721    X509 *x;
722    int ok, cnum;
723    unsigned int last_reasons;
724    cnum = ctx->error_depth;
725    x = sk_X509_value(ctx->chain, cnum);
726    ctx->current_cert = x;
727    ctx->current_issuer = NULL;
728    ctx->current_crl_score = 0;
729    ctx->current_reasons = 0;
730    while (ctx->current_reasons != CRLDP_ALL_REASONS) {
731        last_reasons = ctx->current_reasons;
732        /* Try to retrieve relevant CRL */
733        if (ctx->get_crl)
734            ok = ctx->get_crl(ctx, &crl, x);
735        else
736            ok = get_crl_delta(ctx, &crl, &dcrl, x);
737        /*
738         * If error looking up CRL, nothing we can do except notify callback
739         */
740        if (!ok) {
741            ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
742            ok = ctx->verify_cb(0, ctx);
743            goto err;
744        }
745        ctx->current_crl = crl;
746        ok = ctx->check_crl(ctx, crl);
747        if (!ok)
748            goto err;
749
750        if (dcrl) {
751            ok = ctx->check_crl(ctx, dcrl);
752            if (!ok)
753                goto err;
754            ok = ctx->cert_crl(ctx, dcrl, x);
755            if (!ok)
756                goto err;
757        } else
758            ok = 1;
759
760        /* Don't look in full CRL if delta reason is removefromCRL */
761        if (ok != 2) {
762            ok = ctx->cert_crl(ctx, crl, x);
763            if (!ok)
764                goto err;
765        }
766
767        X509_CRL_free(crl);
768        X509_CRL_free(dcrl);
769        crl = NULL;
770        dcrl = NULL;
771        /*
772         * If reasons not updated we wont get anywhere by another iteration,
773         * so exit loop.
774         */
775        if (last_reasons == ctx->current_reasons) {
776            ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
777            ok = ctx->verify_cb(0, ctx);
778            goto err;
779        }
780    }
781 err:
782    X509_CRL_free(crl);
783    X509_CRL_free(dcrl);
784
785    ctx->current_crl = NULL;
786    return ok;
787
788}
789
790/* Check CRL times against values in X509_STORE_CTX */
791
792static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
793{
794    time_t *ptime;
795    int i;
796    if (notify)
797        ctx->current_crl = crl;
798    if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
799        ptime = &ctx->param->check_time;
800    else
801        ptime = NULL;
802
803    i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
804    if (i == 0) {
805        if (!notify)
806            return 0;
807        ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
808        if (!ctx->verify_cb(0, ctx))
809            return 0;
810    }
811
812    if (i > 0) {
813        if (!notify)
814            return 0;
815        ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
816        if (!ctx->verify_cb(0, ctx))
817            return 0;
818    }
819
820    if (X509_CRL_get_nextUpdate(crl)) {
821        i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
822
823        if (i == 0) {
824            if (!notify)
825                return 0;
826            ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
827            if (!ctx->verify_cb(0, ctx))
828                return 0;
829        }
830        /* Ignore expiry of base CRL is delta is valid */
831        if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
832            if (!notify)
833                return 0;
834            ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
835            if (!ctx->verify_cb(0, ctx))
836                return 0;
837        }
838    }
839
840    if (notify)
841        ctx->current_crl = NULL;
842
843    return 1;
844}
845
846static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
847                      X509 **pissuer, int *pscore, unsigned int *preasons,
848                      STACK_OF(X509_CRL) *crls)
849{
850    int i, crl_score, best_score = *pscore;
851    unsigned int reasons, best_reasons = 0;
852    X509 *x = ctx->current_cert;
853    X509_CRL *crl, *best_crl = NULL;
854    X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
855
856    for (i = 0; i < sk_X509_CRL_num(crls); i++) {
857        crl = sk_X509_CRL_value(crls, i);
858        reasons = *preasons;
859        crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
860
861        if (crl_score > best_score) {
862            best_crl = crl;
863            best_crl_issuer = crl_issuer;
864            best_score = crl_score;
865            best_reasons = reasons;
866        }
867    }
868
869    if (best_crl) {
870        if (*pcrl)
871            X509_CRL_free(*pcrl);
872        *pcrl = best_crl;
873        *pissuer = best_crl_issuer;
874        *pscore = best_score;
875        *preasons = best_reasons;
876        CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509_CRL);
877        if (*pdcrl) {
878            X509_CRL_free(*pdcrl);
879            *pdcrl = NULL;
880        }
881        get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
882    }
883
884    if (best_score >= CRL_SCORE_VALID)
885        return 1;
886
887    return 0;
888}
889
890/*
891 * Compare two CRL extensions for delta checking purposes. They should be
892 * both present or both absent. If both present all fields must be identical.
893 */
894
895static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
896{
897    ASN1_OCTET_STRING *exta, *extb;
898    int i;
899    i = X509_CRL_get_ext_by_NID(a, nid, -1);
900    if (i >= 0) {
901        /* Can't have multiple occurrences */
902        if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
903            return 0;
904        exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
905    } else
906        exta = NULL;
907
908    i = X509_CRL_get_ext_by_NID(b, nid, -1);
909
910    if (i >= 0) {
911
912        if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
913            return 0;
914        extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
915    } else
916        extb = NULL;
917
918    if (!exta && !extb)
919        return 1;
920
921    if (!exta || !extb)
922        return 0;
923
924    if (ASN1_OCTET_STRING_cmp(exta, extb))
925        return 0;
926
927    return 1;
928}
929
930/* See if a base and delta are compatible */
931
932static int check_delta_base(X509_CRL *delta, X509_CRL *base)
933{
934    /* Delta CRL must be a delta */
935    if (!delta->base_crl_number)
936        return 0;
937    /* Base must have a CRL number */
938    if (!base->crl_number)
939        return 0;
940    /* Issuer names must match */
941    if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
942        return 0;
943    /* AKID and IDP must match */
944    if (!crl_extension_match(delta, base, NID_authority_key_identifier))
945        return 0;
946    if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
947        return 0;
948    /* Delta CRL base number must not exceed Full CRL number. */
949    if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
950        return 0;
951    /* Delta CRL number must exceed full CRL number */
952    if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
953        return 1;
954    return 0;
955}
956
957/*
958 * For a given base CRL find a delta... maybe extend to delta scoring or
959 * retrieve a chain of deltas...
960 */
961
962static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
963                         X509_CRL *base, STACK_OF(X509_CRL) *crls)
964{
965    X509_CRL *delta;
966    int i;
967    if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
968        return;
969    if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
970        return;
971    for (i = 0; i < sk_X509_CRL_num(crls); i++) {
972        delta = sk_X509_CRL_value(crls, i);
973        if (check_delta_base(delta, base)) {
974            if (check_crl_time(ctx, delta, 0))
975                *pscore |= CRL_SCORE_TIME_DELTA;
976            CRYPTO_add(&delta->references, 1, CRYPTO_LOCK_X509_CRL);
977            *dcrl = delta;
978            return;
979        }
980    }
981    *dcrl = NULL;
982}
983
984/*
985 * For a given CRL return how suitable it is for the supplied certificate
986 * 'x'. The return value is a mask of several criteria. If the issuer is not
987 * the certificate issuer this is returned in *pissuer. The reasons mask is
988 * also used to determine if the CRL is suitable: if no new reasons the CRL
989 * is rejected, otherwise reasons is updated.
990 */
991
992static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
993                         unsigned int *preasons, X509_CRL *crl, X509 *x)
994{
995
996    int crl_score = 0;
997    unsigned int tmp_reasons = *preasons, crl_reasons;
998
999    /* First see if we can reject CRL straight away */
1000
1001    /* Invalid IDP cannot be processed */
1002    if (crl->idp_flags & IDP_INVALID)
1003        return 0;
1004    /* Reason codes or indirect CRLs need extended CRL support */
1005    if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1006        if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1007            return 0;
1008    } else if (crl->idp_flags & IDP_REASONS) {
1009        /* If no new reasons reject */
1010        if (!(crl->idp_reasons & ~tmp_reasons))
1011            return 0;
1012    }
1013    /* Don't process deltas at this stage */
1014    else if (crl->base_crl_number)
1015        return 0;
1016    /* If issuer name doesn't match certificate need indirect CRL */
1017    if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1018        if (!(crl->idp_flags & IDP_INDIRECT))
1019            return 0;
1020    } else
1021        crl_score |= CRL_SCORE_ISSUER_NAME;
1022
1023    if (!(crl->flags & EXFLAG_CRITICAL))
1024        crl_score |= CRL_SCORE_NOCRITICAL;
1025
1026    /* Check expiry */
1027    if (check_crl_time(ctx, crl, 0))
1028        crl_score |= CRL_SCORE_TIME;
1029
1030    /* Check authority key ID and locate certificate issuer */
1031    crl_akid_check(ctx, crl, pissuer, &crl_score);
1032
1033    /* If we can't locate certificate issuer at this point forget it */
1034
1035    if (!(crl_score & CRL_SCORE_AKID))
1036        return 0;
1037
1038    /* Check cert for matching CRL distribution points */
1039
1040    if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1041        /* If no new reasons reject */
1042        if (!(crl_reasons & ~tmp_reasons))
1043            return 0;
1044        tmp_reasons |= crl_reasons;
1045        crl_score |= CRL_SCORE_SCOPE;
1046    }
1047
1048    *preasons = tmp_reasons;
1049
1050    return crl_score;
1051
1052}
1053
1054static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1055                           X509 **pissuer, int *pcrl_score)
1056{
1057    X509 *crl_issuer = NULL;
1058    X509_NAME *cnm = X509_CRL_get_issuer(crl);
1059    int cidx = ctx->error_depth;
1060    int i;
1061
1062    if (cidx != sk_X509_num(ctx->chain) - 1)
1063        cidx++;
1064
1065    crl_issuer = sk_X509_value(ctx->chain, cidx);
1066
1067    if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1068        if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1069            *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1070            *pissuer = crl_issuer;
1071            return;
1072        }
1073    }
1074
1075    for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1076        crl_issuer = sk_X509_value(ctx->chain, cidx);
1077        if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1078            continue;
1079        if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1080            *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1081            *pissuer = crl_issuer;
1082            return;
1083        }
1084    }
1085
1086    /* Anything else needs extended CRL support */
1087
1088    if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1089        return;
1090
1091    /*
1092     * Otherwise the CRL issuer is not on the path. Look for it in the set of
1093     * untrusted certificates.
1094     */
1095    for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1096        crl_issuer = sk_X509_value(ctx->untrusted, i);
1097        if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1098            continue;
1099        if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1100            *pissuer = crl_issuer;
1101            *pcrl_score |= CRL_SCORE_AKID;
1102            return;
1103        }
1104    }
1105}
1106
1107/*
1108 * Check the path of a CRL issuer certificate. This creates a new
1109 * X509_STORE_CTX and populates it with most of the parameters from the
1110 * parent. This could be optimised somewhat since a lot of path checking will
1111 * be duplicated by the parent, but this will rarely be used in practice.
1112 */
1113
1114static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1115{
1116    X509_STORE_CTX crl_ctx;
1117    int ret;
1118    /* Don't allow recursive CRL path validation */
1119    if (ctx->parent)
1120        return 0;
1121    if (!X509_STORE_CTX_init(&crl_ctx, ctx->ctx, x, ctx->untrusted))
1122        return -1;
1123
1124    crl_ctx.crls = ctx->crls;
1125    /* Copy verify params across */
1126    X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1127
1128    crl_ctx.parent = ctx;
1129    crl_ctx.verify_cb = ctx->verify_cb;
1130
1131    /* Verify CRL issuer */
1132    ret = X509_verify_cert(&crl_ctx);
1133
1134    if (ret <= 0)
1135        goto err;
1136
1137    /* Check chain is acceptable */
1138
1139    ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1140 err:
1141    X509_STORE_CTX_cleanup(&crl_ctx);
1142    return ret;
1143}
1144
1145/*
1146 * RFC3280 says nothing about the relationship between CRL path and
1147 * certificate path, which could lead to situations where a certificate could
1148 * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1149 * strict and states that the two paths must end in the same trust anchor,
1150 * though some discussions remain... until this is resolved we use the
1151 * RFC5280 version
1152 */
1153
1154static int check_crl_chain(X509_STORE_CTX *ctx,
1155                           STACK_OF(X509) *cert_path,
1156                           STACK_OF(X509) *crl_path)
1157{
1158    X509 *cert_ta, *crl_ta;
1159    cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1160    crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1161    if (!X509_cmp(cert_ta, crl_ta))
1162        return 1;
1163    return 0;
1164}
1165
1166/*-
1167 * Check for match between two dist point names: three separate cases.
1168 * 1. Both are relative names and compare X509_NAME types.
1169 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1170 * 3. Both are full names and compare two GENERAL_NAMES.
1171 * 4. One is NULL: automatic match.
1172 */
1173
1174static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1175{
1176    X509_NAME *nm = NULL;
1177    GENERAL_NAMES *gens = NULL;
1178    GENERAL_NAME *gena, *genb;
1179    int i, j;
1180    if (!a || !b)
1181        return 1;
1182    if (a->type == 1) {
1183        if (!a->dpname)
1184            return 0;
1185        /* Case 1: two X509_NAME */
1186        if (b->type == 1) {
1187            if (!b->dpname)
1188                return 0;
1189            if (!X509_NAME_cmp(a->dpname, b->dpname))
1190                return 1;
1191            else
1192                return 0;
1193        }
1194        /* Case 2: set name and GENERAL_NAMES appropriately */
1195        nm = a->dpname;
1196        gens = b->name.fullname;
1197    } else if (b->type == 1) {
1198        if (!b->dpname)
1199            return 0;
1200        /* Case 2: set name and GENERAL_NAMES appropriately */
1201        gens = a->name.fullname;
1202        nm = b->dpname;
1203    }
1204
1205    /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1206    if (nm) {
1207        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1208            gena = sk_GENERAL_NAME_value(gens, i);
1209            if (gena->type != GEN_DIRNAME)
1210                continue;
1211            if (!X509_NAME_cmp(nm, gena->d.directoryName))
1212                return 1;
1213        }
1214        return 0;
1215    }
1216
1217    /* Else case 3: two GENERAL_NAMES */
1218
1219    for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1220        gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1221        for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1222            genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1223            if (!GENERAL_NAME_cmp(gena, genb))
1224                return 1;
1225        }
1226    }
1227
1228    return 0;
1229
1230}
1231
1232static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1233{
1234    int i;
1235    X509_NAME *nm = X509_CRL_get_issuer(crl);
1236    /* If no CRLissuer return is successful iff don't need a match */
1237    if (!dp->CRLissuer)
1238        return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1239    for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1240        GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1241        if (gen->type != GEN_DIRNAME)
1242            continue;
1243        if (!X509_NAME_cmp(gen->d.directoryName, nm))
1244            return 1;
1245    }
1246    return 0;
1247}
1248
1249/* Check CRLDP and IDP */
1250
1251static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1252                           unsigned int *preasons)
1253{
1254    int i;
1255    if (crl->idp_flags & IDP_ONLYATTR)
1256        return 0;
1257    if (x->ex_flags & EXFLAG_CA) {
1258        if (crl->idp_flags & IDP_ONLYUSER)
1259            return 0;
1260    } else {
1261        if (crl->idp_flags & IDP_ONLYCA)
1262            return 0;
1263    }
1264    *preasons = crl->idp_reasons;
1265    for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1266        DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1267        if (crldp_check_crlissuer(dp, crl, crl_score)) {
1268            if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1269                *preasons &= dp->dp_reasons;
1270                return 1;
1271            }
1272        }
1273    }
1274    if ((!crl->idp || !crl->idp->distpoint)
1275        && (crl_score & CRL_SCORE_ISSUER_NAME))
1276        return 1;
1277    return 0;
1278}
1279
1280/*
1281 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1282 * to find a delta CRL too
1283 */
1284
1285static int get_crl_delta(X509_STORE_CTX *ctx,
1286                         X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1287{
1288    int ok;
1289    X509 *issuer = NULL;
1290    int crl_score = 0;
1291    unsigned int reasons;
1292    X509_CRL *crl = NULL, *dcrl = NULL;
1293    STACK_OF(X509_CRL) *skcrl;
1294    X509_NAME *nm = X509_get_issuer_name(x);
1295    reasons = ctx->current_reasons;
1296    ok = get_crl_sk(ctx, &crl, &dcrl,
1297                    &issuer, &crl_score, &reasons, ctx->crls);
1298
1299    if (ok)
1300        goto done;
1301
1302    /* Lookup CRLs from store */
1303
1304    skcrl = ctx->lookup_crls(ctx, nm);
1305
1306    /* If no CRLs found and a near match from get_crl_sk use that */
1307    if (!skcrl && crl)
1308        goto done;
1309
1310    get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1311
1312    sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1313
1314 done:
1315
1316    /* If we got any kind of CRL use it and return success */
1317    if (crl) {
1318        ctx->current_issuer = issuer;
1319        ctx->current_crl_score = crl_score;
1320        ctx->current_reasons = reasons;
1321        *pcrl = crl;
1322        *pdcrl = dcrl;
1323        return 1;
1324    }
1325
1326    return 0;
1327}
1328
1329/* Check CRL validity */
1330static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1331{
1332    X509 *issuer = NULL;
1333    EVP_PKEY *ikey = NULL;
1334    int ok = 0, chnum, cnum;
1335    cnum = ctx->error_depth;
1336    chnum = sk_X509_num(ctx->chain) - 1;
1337    /* if we have an alternative CRL issuer cert use that */
1338    if (ctx->current_issuer)
1339        issuer = ctx->current_issuer;
1340
1341    /*
1342     * Else find CRL issuer: if not last certificate then issuer is next
1343     * certificate in chain.
1344     */
1345    else if (cnum < chnum)
1346        issuer = sk_X509_value(ctx->chain, cnum + 1);
1347    else {
1348        issuer = sk_X509_value(ctx->chain, chnum);
1349        /* If not self signed, can't check signature */
1350        if (!ctx->check_issued(ctx, issuer, issuer)) {
1351            ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
1352            ok = ctx->verify_cb(0, ctx);
1353            if (!ok)
1354                goto err;
1355        }
1356    }
1357
1358    if (issuer) {
1359        /*
1360         * Skip most tests for deltas because they have already been done
1361         */
1362        if (!crl->base_crl_number) {
1363            /* Check for cRLSign bit if keyUsage present */
1364            if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1365                !(issuer->ex_kusage & KU_CRL_SIGN)) {
1366                ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
1367                ok = ctx->verify_cb(0, ctx);
1368                if (!ok)
1369                    goto err;
1370            }
1371
1372            if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) {
1373                ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE;
1374                ok = ctx->verify_cb(0, ctx);
1375                if (!ok)
1376                    goto err;
1377            }
1378
1379            if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) {
1380                if (check_crl_path(ctx, ctx->current_issuer) <= 0) {
1381                    ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
1382                    ok = ctx->verify_cb(0, ctx);
1383                    if (!ok)
1384                        goto err;
1385                }
1386            }
1387
1388            if (crl->idp_flags & IDP_INVALID) {
1389                ctx->error = X509_V_ERR_INVALID_EXTENSION;
1390                ok = ctx->verify_cb(0, ctx);
1391                if (!ok)
1392                    goto err;
1393            }
1394
1395        }
1396
1397        if (!(ctx->current_crl_score & CRL_SCORE_TIME)) {
1398            ok = check_crl_time(ctx, crl, 1);
1399            if (!ok)
1400                goto err;
1401        }
1402
1403        /* Attempt to get issuer certificate public key */
1404        ikey = X509_get_pubkey(issuer);
1405
1406        if (!ikey) {
1407            ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1408            ok = ctx->verify_cb(0, ctx);
1409            if (!ok)
1410                goto err;
1411        } else {
1412            /* Verify CRL signature */
1413            if (X509_CRL_verify(crl, ikey) <= 0) {
1414                ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
1415                ok = ctx->verify_cb(0, ctx);
1416                if (!ok)
1417                    goto err;
1418            }
1419        }
1420    }
1421
1422    ok = 1;
1423
1424 err:
1425    EVP_PKEY_free(ikey);
1426    return ok;
1427}
1428
1429/* Check certificate against CRL */
1430static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1431{
1432    int ok;
1433    X509_REVOKED *rev;
1434    /*
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.
1439     */
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);
1444        if (!ok)
1445            return 0;
1446    }
1447    /*
1448     * Look for serial number of certificate in CRL If found make sure reason
1449     * is not removeFromCRL.
1450     */
1451    if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1452        if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1453            return 2;
1454        ctx->error = X509_V_ERR_CERT_REVOKED;
1455        ok = ctx->verify_cb(0, ctx);
1456        if (!ok)
1457            return 0;
1458    }
1459
1460    return 1;
1461}
1462
1463static int check_policy(X509_STORE_CTX *ctx)
1464{
1465    int ret;
1466    if (ctx->parent)
1467        return 1;
1468    ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1469                            ctx->param->policies, ctx->param->flags);
1470    if (ret == 0) {
1471        X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1472        return 0;
1473    }
1474    /* Invalid or inconsistent extensions */
1475    if (ret == -1) {
1476        /*
1477         * Locate certificates with bad extensions and notify callback.
1478         */
1479        X509 *x;
1480        int i;
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))
1484                continue;
1485            ctx->current_cert = x;
1486            ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
1487            if (!ctx->verify_cb(0, ctx))
1488                return 0;
1489        }
1490        return 1;
1491    }
1492    if (ret == -2) {
1493        ctx->current_cert = NULL;
1494        ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1495        return ctx->verify_cb(0, ctx);
1496    }
1497
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))
1502            return 0;
1503    }
1504
1505    return 1;
1506}
1507
1508static int check_cert_time(X509_STORE_CTX *ctx, X509 *x)
1509{
1510    time_t *ptime;
1511    int i;
1512
1513    if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1514        ptime = &ctx->param->check_time;
1515    else
1516        ptime = NULL;
1517
1518    i = X509_cmp_time(X509_get_notBefore(x), ptime);
1519    if (i == 0) {
1520        ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
1521        ctx->current_cert = x;
1522        if (!ctx->verify_cb(0, ctx))
1523            return 0;
1524    }
1525
1526    if (i > 0) {
1527        ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
1528        ctx->current_cert = x;
1529        if (!ctx->verify_cb(0, ctx))
1530            return 0;
1531    }
1532
1533    i = X509_cmp_time(X509_get_notAfter(x), ptime);
1534    if (i == 0) {
1535        ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
1536        ctx->current_cert = x;
1537        if (!ctx->verify_cb(0, ctx))
1538            return 0;
1539    }
1540
1541    if (i < 0) {
1542        ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
1543        ctx->current_cert = x;
1544        if (!ctx->verify_cb(0, ctx))
1545            return 0;
1546    }
1547
1548    return 1;
1549}
1550
1551static int internal_verify(X509_STORE_CTX *ctx)
1552{
1553    int ok = 0, n;
1554    X509 *xs, *xi;
1555    EVP_PKEY *pkey = NULL;
1556    int (*cb) (int xok, X509_STORE_CTX *xctx);
1557
1558    cb = ctx->verify_cb;
1559
1560    n = sk_X509_num(ctx->chain);
1561    ctx->error_depth = n - 1;
1562    n--;
1563    xi = sk_X509_value(ctx->chain, n);
1564
1565    if (ctx->check_issued(ctx, xi, xi))
1566        xs = xi;
1567    else {
1568        if (n <= 0) {
1569            ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
1570            ctx->current_cert = xi;
1571            ok = cb(0, ctx);
1572            goto end;
1573        } else {
1574            n--;
1575            ctx->error_depth = n;
1576            xs = sk_X509_value(ctx->chain, n);
1577        }
1578    }
1579
1580/*      ctx->error=0;  not needed */
1581    while (n >= 0) {
1582        ctx->error_depth = n;
1583
1584        /*
1585         * Skip signature check for self signed certificates unless
1586         * explicitly asked for. It doesn't add any security and just wastes
1587         * time.
1588         */
1589        if (!xs->valid
1590            && (xs != xi
1591                || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
1592            if ((pkey = X509_get_pubkey(xi)) == NULL) {
1593                ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
1594                ctx->current_cert = xi;
1595                ok = (*cb) (0, ctx);
1596                if (!ok)
1597                    goto end;
1598            } else if (X509_verify(xs, pkey) <= 0) {
1599                ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
1600                ctx->current_cert = xs;
1601                ok = (*cb) (0, ctx);
1602                if (!ok) {
1603                    EVP_PKEY_free(pkey);
1604                    goto end;
1605                }
1606            }
1607            EVP_PKEY_free(pkey);
1608            pkey = NULL;
1609        }
1610
1611        xs->valid = 1;
1612
1613        ok = check_cert_time(ctx, xs);
1614        if (!ok)
1615            goto end;
1616
1617        /* The last error (if any) is still in the error value */
1618        ctx->current_issuer = xi;
1619        ctx->current_cert = xs;
1620        ok = (*cb) (1, ctx);
1621        if (!ok)
1622            goto end;
1623
1624        n--;
1625        if (n >= 0) {
1626            xi = xs;
1627            xs = sk_X509_value(ctx->chain, n);
1628        }
1629    }
1630    ok = 1;
1631 end:
1632    return ok;
1633}
1634
1635int X509_cmp_current_time(const ASN1_TIME *ctm)
1636{
1637    return X509_cmp_time(ctm, NULL);
1638}
1639
1640int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1641{
1642    char *str;
1643    ASN1_TIME atm;
1644    long offset;
1645    char buff1[24], buff2[24], *p;
1646    int i, j, remaining;
1647
1648    p = buff1;
1649    remaining = ctm->length;
1650    str = (char *)ctm->data;
1651    /*
1652     * Note that the following (historical) code allows much more slack in the
1653     * time format than RFC5280. In RFC5280, the representation is fixed:
1654     * UTCTime: YYMMDDHHMMSSZ
1655     * GeneralizedTime: YYYYMMDDHHMMSSZ
1656     */
1657    if (ctm->type == V_ASN1_UTCTIME) {
1658        /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1659        int min_length = sizeof("YYMMDDHHMMZ") - 1;
1660        int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1661        if (remaining < min_length || remaining > max_length)
1662            return 0;
1663        memcpy(p, str, 10);
1664        p += 10;
1665        str += 10;
1666        remaining -= 10;
1667    } else {
1668        /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1669        int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1670        int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1671        if (remaining < min_length || remaining > max_length)
1672            return 0;
1673        memcpy(p, str, 12);
1674        p += 12;
1675        str += 12;
1676        remaining -= 12;
1677    }
1678
1679    if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1680        *(p++) = '0';
1681        *(p++) = '0';
1682    } else {
1683        /* SS (seconds) */
1684        if (remaining < 2)
1685            return 0;
1686        *(p++) = *(str++);
1687        *(p++) = *(str++);
1688        remaining -= 2;
1689        /*
1690         * Skip any (up to three) fractional seconds...
1691         * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1692         * Can we just kill them altogether?
1693         */
1694        if (remaining && *str == '.') {
1695            str++;
1696            remaining--;
1697            for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1698                if (*str < '0' || *str > '9')
1699                    break;
1700            }
1701        }
1702
1703    }
1704    *(p++) = 'Z';
1705    *(p++) = '\0';
1706
1707    /* We now need either a terminating 'Z' or an offset. */
1708    if (!remaining)
1709        return 0;
1710    if (*str == 'Z') {
1711        if (remaining != 1)
1712            return 0;
1713        offset = 0;
1714    } else {
1715        /* (+-)HHMM */
1716        if ((*str != '+') && (*str != '-'))
1717            return 0;
1718        /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1719        if (remaining != 5)
1720            return 0;
1721        if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1722            str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1723            return 0;
1724        offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1725        offset += (str[3] - '0') * 10 + (str[4] - '0');
1726        if (*str == '-')
1727            offset = -offset;
1728    }
1729    atm.type = ctm->type;
1730    atm.flags = 0;
1731    atm.length = sizeof(buff2);
1732    atm.data = (unsigned char *)buff2;
1733
1734    if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1735        return 0;
1736
1737    if (ctm->type == V_ASN1_UTCTIME) {
1738        i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1739        if (i < 50)
1740            i += 100;           /* cf. RFC 2459 */
1741        j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1742        if (j < 50)
1743            j += 100;
1744
1745        if (i < j)
1746            return -1;
1747        if (i > j)
1748            return 1;
1749    }
1750    i = strcmp(buff1, buff2);
1751    if (i == 0)                 /* wait a second then return younger :-) */
1752        return -1;
1753    else
1754        return i;
1755}
1756
1757ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1758{
1759    return X509_time_adj(s, adj, NULL);
1760}
1761
1762ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1763{
1764    return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1765}
1766
1767ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1768                            int offset_day, long offset_sec, time_t *in_tm)
1769{
1770    time_t t;
1771
1772    if (in_tm)
1773        t = *in_tm;
1774    else
1775        time(&t);
1776
1777    if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1778        if (s->type == V_ASN1_UTCTIME)
1779            return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1780        if (s->type == V_ASN1_GENERALIZEDTIME)
1781            return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1782    }
1783    return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1784}
1785
1786int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1787{
1788    EVP_PKEY *ktmp = NULL, *ktmp2;
1789    int i, j;
1790
1791    if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1792        return 1;
1793
1794    for (i = 0; i < sk_X509_num(chain); i++) {
1795        ktmp = X509_get_pubkey(sk_X509_value(chain, i));
1796        if (ktmp == NULL) {
1797            X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1798                    X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1799            return 0;
1800        }
1801        if (!EVP_PKEY_missing_parameters(ktmp))
1802            break;
1803        else {
1804            EVP_PKEY_free(ktmp);
1805            ktmp = NULL;
1806        }
1807    }
1808    if (ktmp == NULL) {
1809        X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1810                X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1811        return 0;
1812    }
1813
1814    /* first, populate the other certs */
1815    for (j = i - 1; j >= 0; j--) {
1816        ktmp2 = X509_get_pubkey(sk_X509_value(chain, j));
1817        EVP_PKEY_copy_parameters(ktmp2, ktmp);
1818        EVP_PKEY_free(ktmp2);
1819    }
1820
1821    if (pkey != NULL)
1822        EVP_PKEY_copy_parameters(pkey, ktmp);
1823    EVP_PKEY_free(ktmp);
1824    return 1;
1825}
1826
1827int X509_STORE_CTX_get_ex_new_index(long argl, void *argp,
1828                                    CRYPTO_EX_new *new_func,
1829                                    CRYPTO_EX_dup *dup_func,
1830                                    CRYPTO_EX_free *free_func)
1831{
1832    /*
1833     * This function is (usually) called only once, by
1834     * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c).
1835     */
1836    return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, argl, argp,
1837                                   new_func, dup_func, free_func);
1838}
1839
1840int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1841{
1842    return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1843}
1844
1845void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1846{
1847    return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1848}
1849
1850int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1851{
1852    return ctx->error;
1853}
1854
1855void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1856{
1857    ctx->error = err;
1858}
1859
1860int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1861{
1862    return ctx->error_depth;
1863}
1864
1865X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1866{
1867    return ctx->current_cert;
1868}
1869
1870STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1871{
1872    return ctx->chain;
1873}
1874
1875STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1876{
1877    int i;
1878    X509 *x;
1879    STACK_OF(X509) *chain;
1880    if (!ctx->chain || !(chain = sk_X509_dup(ctx->chain)))
1881        return NULL;
1882    for (i = 0; i < sk_X509_num(chain); i++) {
1883        x = sk_X509_value(chain, i);
1884        CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1885    }
1886    return chain;
1887}
1888
1889X509 *X509_STORE_CTX_get0_current_issuer(X509_STORE_CTX *ctx)
1890{
1891    return ctx->current_issuer;
1892}
1893
1894X509_CRL *X509_STORE_CTX_get0_current_crl(X509_STORE_CTX *ctx)
1895{
1896    return ctx->current_crl;
1897}
1898
1899X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(X509_STORE_CTX *ctx)
1900{
1901    return ctx->parent;
1902}
1903
1904void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
1905{
1906    ctx->cert = x;
1907}
1908
1909void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
1910{
1911    ctx->untrusted = sk;
1912}
1913
1914void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
1915{
1916    ctx->crls = sk;
1917}
1918
1919int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
1920{
1921    return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
1922}
1923
1924int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
1925{
1926    return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
1927}
1928
1929/*
1930 * This function is used to set the X509_STORE_CTX purpose and trust values.
1931 * This is intended to be used when another structure has its own trust and
1932 * purpose values which (if set) will be inherited by the ctx. If they aren't
1933 * set then we will usually have a default purpose in mind which should then
1934 * be used to set the trust value. An example of this is SSL use: an SSL
1935 * structure will have its own purpose and trust settings which the
1936 * application can set: if they aren't set then we use the default of SSL
1937 * client/server.
1938 */
1939
1940int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
1941                                   int purpose, int trust)
1942{
1943    int idx;
1944    /* If purpose not set use default */
1945    if (!purpose)
1946        purpose = def_purpose;
1947    /* If we have a purpose then check it is valid */
1948    if (purpose) {
1949        X509_PURPOSE *ptmp;
1950        idx = X509_PURPOSE_get_by_id(purpose);
1951        if (idx == -1) {
1952            X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1953                    X509_R_UNKNOWN_PURPOSE_ID);
1954            return 0;
1955        }
1956        ptmp = X509_PURPOSE_get0(idx);
1957        if (ptmp->trust == X509_TRUST_DEFAULT) {
1958            idx = X509_PURPOSE_get_by_id(def_purpose);
1959            if (idx == -1) {
1960                X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1961                        X509_R_UNKNOWN_PURPOSE_ID);
1962                return 0;
1963            }
1964            ptmp = X509_PURPOSE_get0(idx);
1965        }
1966        /* If trust not set then get from purpose default */
1967        if (!trust)
1968            trust = ptmp->trust;
1969    }
1970    if (trust) {
1971        idx = X509_TRUST_get_by_id(trust);
1972        if (idx == -1) {
1973            X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1974                    X509_R_UNKNOWN_TRUST_ID);
1975            return 0;
1976        }
1977    }
1978
1979    if (purpose && !ctx->param->purpose)
1980        ctx->param->purpose = purpose;
1981    if (trust && !ctx->param->trust)
1982        ctx->param->trust = trust;
1983    return 1;
1984}
1985
1986X509_STORE_CTX *X509_STORE_CTX_new(void)
1987{
1988    X509_STORE_CTX *ctx;
1989    ctx = (X509_STORE_CTX *)OPENSSL_malloc(sizeof(X509_STORE_CTX));
1990    if (!ctx) {
1991        X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
1992        return NULL;
1993    }
1994    memset(ctx, 0, sizeof(X509_STORE_CTX));
1995    return ctx;
1996}
1997
1998void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
1999{
2000    if (!ctx)
2001        return;
2002    X509_STORE_CTX_cleanup(ctx);
2003    OPENSSL_free(ctx);
2004}
2005
2006int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2007                        STACK_OF(X509) *chain)
2008{
2009    int ret = 1;
2010    ctx->ctx = store;
2011    ctx->current_method = 0;
2012    ctx->cert = x509;
2013    ctx->untrusted = chain;
2014    ctx->crls = NULL;
2015    ctx->last_untrusted = 0;
2016    ctx->other_ctx = NULL;
2017    ctx->valid = 0;
2018    ctx->chain = NULL;
2019    ctx->error = 0;
2020    ctx->explicit_policy = 0;
2021    ctx->error_depth = 0;
2022    ctx->current_cert = NULL;
2023    ctx->current_issuer = NULL;
2024    ctx->current_crl = NULL;
2025    ctx->current_crl_score = 0;
2026    ctx->current_reasons = 0;
2027    ctx->tree = NULL;
2028    ctx->parent = NULL;
2029
2030    ctx->param = X509_VERIFY_PARAM_new();
2031
2032    if (!ctx->param) {
2033        X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2034        return 0;
2035    }
2036
2037    /*
2038     * Inherit callbacks and flags from X509_STORE if not set use defaults.
2039     */
2040
2041    if (store)
2042        ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2043    else
2044        ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2045
2046    if (store) {
2047        ctx->verify_cb = store->verify_cb;
2048        ctx->cleanup = store->cleanup;
2049    } else
2050        ctx->cleanup = 0;
2051
2052    if (ret)
2053        ret = X509_VERIFY_PARAM_inherit(ctx->param,
2054                                        X509_VERIFY_PARAM_lookup("default"));
2055
2056    if (ret == 0) {
2057        X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2058        return 0;
2059    }
2060
2061    if (store && store->check_issued)
2062        ctx->check_issued = store->check_issued;
2063    else
2064        ctx->check_issued = check_issued;
2065
2066    if (store && store->get_issuer)
2067        ctx->get_issuer = store->get_issuer;
2068    else
2069        ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2070
2071    if (store && store->verify_cb)
2072        ctx->verify_cb = store->verify_cb;
2073    else
2074        ctx->verify_cb = null_callback;
2075
2076    if (store && store->verify)
2077        ctx->verify = store->verify;
2078    else
2079        ctx->verify = internal_verify;
2080
2081    if (store && store->check_revocation)
2082        ctx->check_revocation = store->check_revocation;
2083    else
2084        ctx->check_revocation = check_revocation;
2085
2086    if (store && store->get_crl)
2087        ctx->get_crl = store->get_crl;
2088    else
2089        ctx->get_crl = NULL;
2090
2091    if (store && store->check_crl)
2092        ctx->check_crl = store->check_crl;
2093    else
2094        ctx->check_crl = check_crl;
2095
2096    if (store && store->cert_crl)
2097        ctx->cert_crl = store->cert_crl;
2098    else
2099        ctx->cert_crl = cert_crl;
2100
2101    if (store && store->lookup_certs)
2102        ctx->lookup_certs = store->lookup_certs;
2103    else
2104        ctx->lookup_certs = X509_STORE_get1_certs;
2105
2106    if (store && store->lookup_crls)
2107        ctx->lookup_crls = store->lookup_crls;
2108    else
2109        ctx->lookup_crls = X509_STORE_get1_crls;
2110
2111    ctx->check_policy = check_policy;
2112
2113    /*
2114     * This memset() can't make any sense anyway, so it's removed. As
2115     * X509_STORE_CTX_cleanup does a proper "free" on the ex_data, we put a
2116     * corresponding "new" here and remove this bogus initialisation.
2117     */
2118    /* memset(&(ctx->ex_data),0,sizeof(CRYPTO_EX_DATA)); */
2119    if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2120                            &(ctx->ex_data))) {
2121        OPENSSL_free(ctx);
2122        X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2123        return 0;
2124    }
2125    return 1;
2126}
2127
2128/*
2129 * Set alternative lookup method: just a STACK of trusted certificates. This
2130 * avoids X509_STORE nastiness where it isn't needed.
2131 */
2132
2133void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2134{
2135    ctx->other_ctx = sk;
2136    ctx->get_issuer = get_issuer_sk;
2137}
2138
2139void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2140{
2141    if (ctx->cleanup)
2142        ctx->cleanup(ctx);
2143    if (ctx->param != NULL) {
2144        if (ctx->parent == NULL)
2145            X509_VERIFY_PARAM_free(ctx->param);
2146        ctx->param = NULL;
2147    }
2148    if (ctx->tree != NULL) {
2149        X509_policy_tree_free(ctx->tree);
2150        ctx->tree = NULL;
2151    }
2152    if (ctx->chain != NULL) {
2153        sk_X509_pop_free(ctx->chain, X509_free);
2154        ctx->chain = NULL;
2155    }
2156    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2157    memset(&ctx->ex_data, 0, sizeof(CRYPTO_EX_DATA));
2158}
2159
2160void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2161{
2162    X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2163}
2164
2165void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2166{
2167    X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2168}
2169
2170void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2171                             time_t t)
2172{
2173    X509_VERIFY_PARAM_set_time(ctx->param, t);
2174}
2175
2176void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2177                                  int (*verify_cb) (int, X509_STORE_CTX *))
2178{
2179    ctx->verify_cb = verify_cb;
2180}
2181
2182X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
2183{
2184    return ctx->tree;
2185}
2186
2187int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
2188{
2189    return ctx->explicit_policy;
2190}
2191
2192int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2193{
2194    const X509_VERIFY_PARAM *param;
2195    param = X509_VERIFY_PARAM_lookup(name);
2196    if (!param)
2197        return 0;
2198    return X509_VERIFY_PARAM_inherit(ctx->param, param);
2199}
2200
2201X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
2202{
2203    return ctx->param;
2204}
2205
2206void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2207{
2208    if (ctx->param)
2209        X509_VERIFY_PARAM_free(ctx->param);
2210    ctx->param = param;
2211}
2212
2213IMPLEMENT_STACK_OF(X509)
2214
2215IMPLEMENT_ASN1_SET_OF(X509)
2216
2217IMPLEMENT_STACK_OF(X509_NAME)
2218
2219IMPLEMENT_STACK_OF(X509_ATTRIBUTE)
2220
2221IMPLEMENT_ASN1_SET_OF(X509_ATTRIBUTE)
2222