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