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