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