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