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