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