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