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