]> CyberLeo.Net >> Repos - FreeBSD/releng/9.3.git/blob - crypto/openssl/crypto/x509/x509_vfy.c
Fix multiple OpenSSL vulnerabilities.
[FreeBSD/releng/9.3.git] / crypto / openssl / crypto / x509 / x509_vfy.c
1 /* crypto/x509/x509_vfy.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include <time.h>
61 #include <errno.h>
62
63 #include "cryptlib.h"
64 #include <openssl/crypto.h>
65 #include <openssl/lhash.h>
66 #include <openssl/buffer.h>
67 #include <openssl/evp.h>
68 #include <openssl/asn1.h>
69 #include <openssl/x509.h>
70 #include <openssl/x509v3.h>
71 #include <openssl/objects.h>
72
73 static int null_callback(int ok, X509_STORE_CTX *e);
74 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
75 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
76 static int check_chain_extensions(X509_STORE_CTX *ctx);
77 static int check_trust(X509_STORE_CTX *ctx);
78 static int check_revocation(X509_STORE_CTX *ctx);
79 static int check_cert(X509_STORE_CTX *ctx);
80 static int check_policy(X509_STORE_CTX *ctx);
81 static int internal_verify(X509_STORE_CTX *ctx);
82 const char X509_version[] = "X.509" OPENSSL_VERSION_PTEXT;
83
84 static int null_callback(int ok, X509_STORE_CTX *e)
85 {
86     return ok;
87 }
88
89 #if 0
90 static int x509_subject_cmp(X509 **a, X509 **b)
91 {
92     return X509_subject_name_cmp(*a, *b);
93 }
94 #endif
95
96 int X509_verify_cert(X509_STORE_CTX *ctx)
97 {
98     X509 *x, *xtmp, *chain_ss = NULL;
99     int bad_chain = 0;
100     X509_VERIFY_PARAM *param = ctx->param;
101     int depth, i, ok = 0;
102     int num;
103     int (*cb) (int xok, X509_STORE_CTX *xctx);
104     STACK_OF(X509) *sktmp = NULL;
105     if (ctx->cert == NULL) {
106         X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
107         return -1;
108     }
109
110     cb = ctx->verify_cb;
111
112     /*
113      * first we make sure the chain we are going to build is present and that
114      * the first entry is in place
115      */
116     if (ctx->chain == NULL) {
117         if (((ctx->chain = sk_X509_new_null()) == NULL) ||
118             (!sk_X509_push(ctx->chain, ctx->cert))) {
119             X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
120             goto end;
121         }
122         CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
123         ctx->last_untrusted = 1;
124     }
125
126     /* We use a temporary STACK so we can chop and hack at it */
127     if (ctx->untrusted != NULL
128         && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
129         X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
130         goto end;
131     }
132
133     num = sk_X509_num(ctx->chain);
134     x = sk_X509_value(ctx->chain, num - 1);
135     depth = param->depth;
136
137     for (;;) {
138         /* If we have enough, we break */
139         if (depth < num)
140             break;              /* FIXME: If this happens, we should take
141                                  * note of it and, if appropriate, use the
142                                  * X509_V_ERR_CERT_CHAIN_TOO_LONG error code
143                                  * later. */
144
145         /* If we are self signed, we break */
146         if (ctx->check_issued(ctx, x, x))
147             break;
148
149         /* If we were passed a cert chain, use it first */
150         if (ctx->untrusted != NULL) {
151             xtmp = find_issuer(ctx, sktmp, x);
152             if (xtmp != NULL) {
153                 if (!sk_X509_push(ctx->chain, xtmp)) {
154                     X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
155                     goto end;
156                 }
157                 CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
158                 (void)sk_X509_delete_ptr(sktmp, xtmp);
159                 ctx->last_untrusted++;
160                 x = xtmp;
161                 num++;
162                 /*
163                  * reparse the full chain for the next one
164                  */
165                 continue;
166             }
167         }
168         break;
169     }
170
171     /*
172      * at this point, chain should contain a list of untrusted certificates.
173      * We now need to add at least one trusted one, if possible, otherwise we
174      * complain.
175      */
176
177     /*
178      * Examine last certificate in chain and see if it is self signed.
179      */
180
181     i = sk_X509_num(ctx->chain);
182     x = sk_X509_value(ctx->chain, i - 1);
183     if (ctx->check_issued(ctx, x, x)) {
184         /* we have a self signed certificate */
185         if (sk_X509_num(ctx->chain) == 1) {
186             /*
187              * We have a single self signed certificate: see if we can find
188              * it in the store. We must have an exact match to avoid possible
189              * impersonation.
190              */
191             ok = ctx->get_issuer(&xtmp, ctx, x);
192             if ((ok <= 0) || X509_cmp(x, xtmp)) {
193                 ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
194                 ctx->current_cert = x;
195                 ctx->error_depth = i - 1;
196                 if (ok == 1)
197                     X509_free(xtmp);
198                 bad_chain = 1;
199                 ok = cb(0, ctx);
200                 if (!ok)
201                     goto end;
202             } else {
203                 /*
204                  * We have a match: replace certificate with store version so
205                  * we get any trust settings.
206                  */
207                 X509_free(x);
208                 x = xtmp;
209                 (void)sk_X509_set(ctx->chain, i - 1, x);
210                 ctx->last_untrusted = 0;
211             }
212         } else {
213             /*
214              * extract and save self signed certificate for later use
215              */
216             chain_ss = sk_X509_pop(ctx->chain);
217             ctx->last_untrusted--;
218             num--;
219             x = sk_X509_value(ctx->chain, num - 1);
220         }
221     }
222
223     /* We now lookup certs from the certificate store */
224     for (;;) {
225         /* If we have enough, we break */
226         if (depth < num)
227             break;
228
229         /* If we are self signed, we break */
230         if (ctx->check_issued(ctx, x, x))
231             break;
232
233         ok = ctx->get_issuer(&xtmp, ctx, x);
234
235         if (ok < 0)
236             return ok;
237         if (ok == 0)
238             break;
239
240         x = xtmp;
241         if (!sk_X509_push(ctx->chain, x)) {
242             X509_free(xtmp);
243             X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
244             return 0;
245         }
246         num++;
247     }
248
249     /* we now have our chain, lets check it... */
250
251     /* Is last certificate looked up self signed? */
252     if (!ctx->check_issued(ctx, x, x)) {
253         if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
254             if (ctx->last_untrusted >= num)
255                 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
256             else
257                 ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
258             ctx->current_cert = x;
259         } else {
260
261             sk_X509_push(ctx->chain, chain_ss);
262             num++;
263             ctx->last_untrusted = num;
264             ctx->current_cert = chain_ss;
265             ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
266             chain_ss = NULL;
267         }
268
269         ctx->error_depth = num - 1;
270         bad_chain = 1;
271         ok = cb(0, ctx);
272         if (!ok)
273             goto end;
274     }
275
276     /* We have the chain complete: now we need to check its purpose */
277     ok = check_chain_extensions(ctx);
278
279     if (!ok)
280         goto end;
281
282     /* The chain extensions are OK: check trust */
283
284     if (param->trust > 0)
285         ok = check_trust(ctx);
286
287     if (!ok)
288         goto end;
289
290     /* We may as well copy down any DSA parameters that are required */
291     X509_get_pubkey_parameters(NULL, ctx->chain);
292
293     /*
294      * Check revocation status: we do this after copying parameters because
295      * they may be needed for CRL signature verification.
296      */
297
298     ok = ctx->check_revocation(ctx);
299     if (!ok)
300         goto end;
301
302     /* At this point, we have a chain and need to verify it */
303     if (ctx->verify != NULL)
304         ok = ctx->verify(ctx);
305     else
306         ok = internal_verify(ctx);
307     if (!ok)
308         goto end;
309
310 #ifndef OPENSSL_NO_RFC3779
311     /* RFC 3779 path validation, now that CRL check has been done */
312     ok = v3_asid_validate_path(ctx);
313     if (!ok)
314         goto end;
315     ok = v3_addr_validate_path(ctx);
316     if (!ok)
317         goto end;
318 #endif
319
320     /* If we get this far evaluate policies */
321     if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
322         ok = ctx->check_policy(ctx);
323     if (!ok)
324         goto end;
325     if (0) {
326  end:
327         X509_get_pubkey_parameters(NULL, ctx->chain);
328     }
329     if (sktmp != NULL)
330         sk_X509_free(sktmp);
331     if (chain_ss != NULL)
332         X509_free(chain_ss);
333     return ok;
334 }
335
336 /*
337  * Given a STACK_OF(X509) find the issuer of cert (if any)
338  */
339
340 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
341 {
342     int i;
343     X509 *issuer;
344     for (i = 0; i < sk_X509_num(sk); i++) {
345         issuer = sk_X509_value(sk, i);
346         if (ctx->check_issued(ctx, x, issuer))
347             return issuer;
348     }
349     return NULL;
350 }
351
352 /* Given a possible certificate and issuer check them */
353
354 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
355 {
356     int ret;
357     ret = X509_check_issued(issuer, x);
358     if (ret == X509_V_OK)
359         return 1;
360     /* If we haven't asked for issuer errors don't set ctx */
361     if (!(ctx->param->flags & X509_V_FLAG_CB_ISSUER_CHECK))
362         return 0;
363
364     ctx->error = ret;
365     ctx->current_cert = x;
366     ctx->current_issuer = issuer;
367     return ctx->verify_cb(0, ctx);
368     return 0;
369 }
370
371 /* Alternative lookup method: look from a STACK stored in other_ctx */
372
373 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
374 {
375     *issuer = find_issuer(ctx, ctx->other_ctx, x);
376     if (*issuer) {
377         CRYPTO_add(&(*issuer)->references, 1, CRYPTO_LOCK_X509);
378         return 1;
379     } else
380         return 0;
381 }
382
383 /*
384  * Check a certificate chains extensions for consistency with the supplied
385  * purpose
386  */
387
388 static int check_chain_extensions(X509_STORE_CTX *ctx)
389 {
390 #ifdef OPENSSL_NO_CHAIN_VERIFY
391     return 1;
392 #else
393     int i, ok = 0, must_be_ca, plen = 0;
394     X509 *x;
395     int (*cb) (int xok, X509_STORE_CTX *xctx);
396     int proxy_path_length = 0;
397     int allow_proxy_certs =
398         ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
399     cb = ctx->verify_cb;
400
401     /*-
402      *  must_be_ca can have 1 of 3 values:
403      * -1: we accept both CA and non-CA certificates, to allow direct
404      *     use of self-signed certificates (which are marked as CA).
405      * 0:  we only accept non-CA certificates.  This is currently not
406      *     used, but the possibility is present for future extensions.
407      * 1:  we only accept CA certificates.  This is currently used for
408      *     all certificates in the chain except the leaf certificate.
409      */
410     must_be_ca = -1;
411
412     /*
413      * A hack to keep people who don't want to modify their software happy
414      */
415     if (getenv("OPENSSL_ALLOW_PROXY_CERTS"))
416         allow_proxy_certs = 1;
417
418     /* Check all untrusted certificates */
419     for (i = 0; i < ctx->last_untrusted; i++) {
420         int ret;
421         x = sk_X509_value(ctx->chain, i);
422         if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
423             && (x->ex_flags & EXFLAG_CRITICAL)) {
424             ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
425             ctx->error_depth = i;
426             ctx->current_cert = x;
427             ok = cb(0, ctx);
428             if (!ok)
429                 goto end;
430         }
431         if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
432             ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
433             ctx->error_depth = i;
434             ctx->current_cert = x;
435             ok = cb(0, ctx);
436             if (!ok)
437                 goto end;
438         }
439         ret = X509_check_ca(x);
440         switch (must_be_ca) {
441         case -1:
442             if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
443                 && (ret != 1) && (ret != 0)) {
444                 ret = 0;
445                 ctx->error = X509_V_ERR_INVALID_CA;
446             } else
447                 ret = 1;
448             break;
449         case 0:
450             if (ret != 0) {
451                 ret = 0;
452                 ctx->error = X509_V_ERR_INVALID_NON_CA;
453             } else
454                 ret = 1;
455             break;
456         default:
457             if ((ret == 0)
458                 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
459                     && (ret != 1))) {
460                 ret = 0;
461                 ctx->error = X509_V_ERR_INVALID_CA;
462             } else
463                 ret = 1;
464             break;
465         }
466         if (ret == 0) {
467             ctx->error_depth = i;
468             ctx->current_cert = x;
469             ok = cb(0, ctx);
470             if (!ok)
471                 goto end;
472         }
473         if (ctx->param->purpose > 0) {
474             ret = X509_check_purpose(x, ctx->param->purpose, must_be_ca > 0);
475             if ((ret == 0)
476                 || ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
477                     && (ret != 1))) {
478                 ctx->error = X509_V_ERR_INVALID_PURPOSE;
479                 ctx->error_depth = i;
480                 ctx->current_cert = x;
481                 ok = cb(0, ctx);
482                 if (!ok)
483                     goto end;
484             }
485         }
486         /* Check pathlen if not self issued */
487         if ((i > 1) && !(x->ex_flags & EXFLAG_SI)
488             && (x->ex_pathlen != -1)
489             && (plen > (x->ex_pathlen + proxy_path_length + 1))) {
490             ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED;
491             ctx->error_depth = i;
492             ctx->current_cert = x;
493             ok = cb(0, ctx);
494             if (!ok)
495                 goto end;
496         }
497         /* Increment path length if not self issued */
498         if (!(x->ex_flags & EXFLAG_SI))
499             plen++;
500         /*
501          * If this certificate is a proxy certificate, the next certificate
502          * must be another proxy certificate or a EE certificate.  If not,
503          * the next certificate must be a CA certificate.
504          */
505         if (x->ex_flags & EXFLAG_PROXY) {
506             if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) {
507                 ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
508                 ctx->error_depth = i;
509                 ctx->current_cert = x;
510                 ok = cb(0, ctx);
511                 if (!ok)
512                     goto end;
513             }
514             proxy_path_length++;
515             must_be_ca = 0;
516         } else
517             must_be_ca = 1;
518     }
519     ok = 1;
520  end:
521     return ok;
522 #endif
523 }
524
525 static int check_trust(X509_STORE_CTX *ctx)
526 {
527 #ifdef OPENSSL_NO_CHAIN_VERIFY
528     return 1;
529 #else
530     int i, ok;
531     X509 *x;
532     int (*cb) (int xok, X509_STORE_CTX *xctx);
533     cb = ctx->verify_cb;
534 /* For now just check the last certificate in the chain */
535     i = sk_X509_num(ctx->chain) - 1;
536     x = sk_X509_value(ctx->chain, i);
537     ok = X509_check_trust(x, ctx->param->trust, 0);
538     if (ok == X509_TRUST_TRUSTED)
539         return 1;
540     ctx->error_depth = i;
541     ctx->current_cert = x;
542     if (ok == X509_TRUST_REJECTED)
543         ctx->error = X509_V_ERR_CERT_REJECTED;
544     else
545         ctx->error = X509_V_ERR_CERT_UNTRUSTED;
546     ok = cb(0, ctx);
547     return ok;
548 #endif
549 }
550
551 static int check_revocation(X509_STORE_CTX *ctx)
552 {
553     int i, last, ok;
554     if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
555         return 1;
556     if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
557         last = sk_X509_num(ctx->chain) - 1;
558     else
559         last = 0;
560     for (i = 0; i <= last; i++) {
561         ctx->error_depth = i;
562         ok = check_cert(ctx);
563         if (!ok)
564             return ok;
565     }
566     return 1;
567 }
568
569 static int check_cert(X509_STORE_CTX *ctx)
570 {
571     X509_CRL *crl = NULL;
572     X509 *x;
573     int ok, cnum;
574     cnum = ctx->error_depth;
575     x = sk_X509_value(ctx->chain, cnum);
576     ctx->current_cert = x;
577     /* Try to retrieve relevant CRL */
578     ok = ctx->get_crl(ctx, &crl, x);
579     /*
580      * If error looking up CRL, nothing we can do except notify callback
581      */
582     if (!ok) {
583         ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL;
584         ok = ctx->verify_cb(0, ctx);
585         goto err;
586     }
587     ctx->current_crl = crl;
588     ok = ctx->check_crl(ctx, crl);
589     if (!ok)
590         goto err;
591     ok = ctx->cert_crl(ctx, crl, x);
592  err:
593     ctx->current_crl = NULL;
594     X509_CRL_free(crl);
595     return ok;
596
597 }
598
599 /* Check CRL times against values in X509_STORE_CTX */
600
601 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
602 {
603     time_t *ptime;
604     int i;
605     ctx->current_crl = crl;
606     if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
607         ptime = &ctx->param->check_time;
608     else
609         ptime = NULL;
610
611     i = X509_cmp_time(X509_CRL_get_lastUpdate(crl), ptime);
612     if (i == 0) {
613         ctx->error = X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
614         if (!notify || !ctx->verify_cb(0, ctx))
615             return 0;
616     }
617
618     if (i > 0) {
619         ctx->error = X509_V_ERR_CRL_NOT_YET_VALID;
620         if (!notify || !ctx->verify_cb(0, ctx))
621             return 0;
622     }
623
624     if (X509_CRL_get_nextUpdate(crl)) {
625         i = X509_cmp_time(X509_CRL_get_nextUpdate(crl), ptime);
626
627         if (i == 0) {
628             ctx->error = X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
629             if (!notify || !ctx->verify_cb(0, ctx))
630                 return 0;
631         }
632
633         if (i < 0) {
634             ctx->error = X509_V_ERR_CRL_HAS_EXPIRED;
635             if (!notify || !ctx->verify_cb(0, ctx))
636                 return 0;
637         }
638     }
639
640     ctx->current_crl = NULL;
641
642     return 1;
643 }
644
645 /*
646  * Lookup CRLs from the supplied list. Look for matching isser name and
647  * validity. If we can't find a valid CRL return the last one with matching
648  * name. This gives more meaningful error codes. Otherwise we'd get a CRL not
649  * found error if a CRL existed with matching name but was invalid.
650  */
651
652 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl,
653                       X509_NAME *nm, STACK_OF(X509_CRL) *crls)
654 {
655     int i;
656     X509_CRL *crl, *best_crl = NULL;
657     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
658         crl = sk_X509_CRL_value(crls, i);
659         if (X509_NAME_cmp(nm, X509_CRL_get_issuer(crl)))
660             continue;
661         if (check_crl_time(ctx, crl, 0)) {
662             *pcrl = crl;
663             CRYPTO_add(&crl->references, 1, CRYPTO_LOCK_X509);
664             return 1;
665         }
666         best_crl = crl;
667     }
668     if (best_crl) {
669         *pcrl = best_crl;
670         CRYPTO_add(&best_crl->references, 1, CRYPTO_LOCK_X509);
671     }
672
673     return 0;
674 }
675
676 /*
677  * Retrieve CRL corresponding to certificate: currently just a subject
678  * lookup: maybe use AKID later...
679  */
680 static int get_crl(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509 *x)
681 {
682     int ok;
683     X509_CRL *crl = NULL;
684     X509_OBJECT xobj;
685     X509_NAME *nm;
686     nm = X509_get_issuer_name(x);
687     ok = get_crl_sk(ctx, &crl, nm, ctx->crls);
688     if (ok) {
689         *pcrl = crl;
690         return 1;
691     }
692
693     ok = X509_STORE_get_by_subject(ctx, X509_LU_CRL, nm, &xobj);
694
695     if (!ok) {
696         /* If we got a near match from get_crl_sk use that */
697         if (crl) {
698             *pcrl = crl;
699             return 1;
700         }
701         return 0;
702     }
703
704     *pcrl = xobj.data.crl;
705     if (crl)
706         X509_CRL_free(crl);
707     return 1;
708 }
709
710 /* Check CRL validity */
711 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
712 {
713     X509 *issuer = NULL;
714     EVP_PKEY *ikey = NULL;
715     int ok = 0, chnum, cnum;
716     cnum = ctx->error_depth;
717     chnum = sk_X509_num(ctx->chain) - 1;
718     /*
719      * Find CRL issuer: if not last certificate then issuer is next
720      * certificate in chain.
721      */
722     if (cnum < chnum)
723         issuer = sk_X509_value(ctx->chain, cnum + 1);
724     else {
725         issuer = sk_X509_value(ctx->chain, chnum);
726         /* If not self signed, can't check signature */
727         if (!ctx->check_issued(ctx, issuer, issuer)) {
728             ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
729             ok = ctx->verify_cb(0, ctx);
730             if (!ok)
731                 goto err;
732         }
733     }
734
735     if (issuer) {
736         /* Check for cRLSign bit if keyUsage present */
737         if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
738             !(issuer->ex_kusage & KU_CRL_SIGN)) {
739             ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
740             ok = ctx->verify_cb(0, ctx);
741             if (!ok)
742                 goto err;
743         }
744
745         /* Attempt to get issuer certificate public key */
746         ikey = X509_get_pubkey(issuer);
747
748         if (!ikey) {
749             ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
750             ok = ctx->verify_cb(0, ctx);
751             if (!ok)
752                 goto err;
753         } else {
754             /* Verify CRL signature */
755             if (X509_CRL_verify(crl, ikey) <= 0) {
756                 ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE;
757                 ok = ctx->verify_cb(0, ctx);
758                 if (!ok)
759                     goto err;
760             }
761         }
762     }
763
764     ok = check_crl_time(ctx, crl, 1);
765     if (!ok)
766         goto err;
767
768     ok = 1;
769
770  err:
771     EVP_PKEY_free(ikey);
772     return ok;
773 }
774
775 /* Check certificate against CRL */
776 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
777 {
778     int idx, ok;
779     X509_REVOKED rtmp;
780     STACK_OF(X509_EXTENSION) *exts;
781     X509_EXTENSION *ext;
782     /* Look for serial number of certificate in CRL */
783     rtmp.serialNumber = X509_get_serialNumber(x);
784     /*
785      * Sort revoked into serial number order if not already sorted. Do this
786      * under a lock to avoid race condition.
787      */
788     if (!sk_X509_REVOKED_is_sorted(crl->crl->revoked)) {
789         CRYPTO_w_lock(CRYPTO_LOCK_X509_CRL);
790         sk_X509_REVOKED_sort(crl->crl->revoked);
791         CRYPTO_w_unlock(CRYPTO_LOCK_X509_CRL);
792     }
793     idx = sk_X509_REVOKED_find(crl->crl->revoked, &rtmp);
794     /*
795      * If found assume revoked: want something cleverer than this to handle
796      * entry extensions in V2 CRLs.
797      */
798     if (idx >= 0) {
799         ctx->error = X509_V_ERR_CERT_REVOKED;
800         ok = ctx->verify_cb(0, ctx);
801         if (!ok)
802             return 0;
803     }
804
805     if (ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
806         return 1;
807
808     /*
809      * See if we have any critical CRL extensions: since we currently don't
810      * handle any CRL extensions the CRL must be rejected. This code
811      * accesses the X509_CRL structure directly: applications shouldn't do
812      * this.
813      */
814
815     exts = crl->crl->extensions;
816
817     for (idx = 0; idx < sk_X509_EXTENSION_num(exts); idx++) {
818         ext = sk_X509_EXTENSION_value(exts, idx);
819         if (ext->critical > 0) {
820             ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
821             ok = ctx->verify_cb(0, ctx);
822             if (!ok)
823                 return 0;
824             break;
825         }
826     }
827     return 1;
828 }
829
830 static int check_policy(X509_STORE_CTX *ctx)
831 {
832     int ret;
833     ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
834                             ctx->param->policies, ctx->param->flags);
835     if (ret == 0) {
836         X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
837         return 0;
838     }
839     /* Invalid or inconsistent extensions */
840     if (ret == -1) {
841         /*
842          * Locate certificates with bad extensions and notify callback.
843          */
844         X509 *x;
845         int i;
846         for (i = 1; i < sk_X509_num(ctx->chain); i++) {
847             x = sk_X509_value(ctx->chain, i);
848             if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
849                 continue;
850             ctx->current_cert = x;
851             ctx->error = X509_V_ERR_INVALID_POLICY_EXTENSION;
852             ret = ctx->verify_cb(0, ctx);
853         }
854         return 1;
855     }
856     if (ret == -2) {
857         ctx->current_cert = NULL;
858         ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
859         return ctx->verify_cb(0, ctx);
860     }
861
862     if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
863         ctx->current_cert = NULL;
864         ctx->error = X509_V_OK;
865         if (!ctx->verify_cb(2, ctx))
866             return 0;
867     }
868
869     return 1;
870 }
871
872 static int check_cert_time(X509_STORE_CTX *ctx, X509 *x)
873 {
874     time_t *ptime;
875     int i;
876
877     if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
878         ptime = &ctx->param->check_time;
879     else
880         ptime = NULL;
881
882     i = X509_cmp_time(X509_get_notBefore(x), ptime);
883     if (i == 0) {
884         ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
885         ctx->current_cert = x;
886         if (!ctx->verify_cb(0, ctx))
887             return 0;
888     }
889
890     if (i > 0) {
891         ctx->error = X509_V_ERR_CERT_NOT_YET_VALID;
892         ctx->current_cert = x;
893         if (!ctx->verify_cb(0, ctx))
894             return 0;
895     }
896
897     i = X509_cmp_time(X509_get_notAfter(x), ptime);
898     if (i == 0) {
899         ctx->error = X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
900         ctx->current_cert = x;
901         if (!ctx->verify_cb(0, ctx))
902             return 0;
903     }
904
905     if (i < 0) {
906         ctx->error = X509_V_ERR_CERT_HAS_EXPIRED;
907         ctx->current_cert = x;
908         if (!ctx->verify_cb(0, ctx))
909             return 0;
910     }
911
912     return 1;
913 }
914
915 static int internal_verify(X509_STORE_CTX *ctx)
916 {
917     int ok = 0, n;
918     X509 *xs, *xi;
919     EVP_PKEY *pkey = NULL;
920     int (*cb) (int xok, X509_STORE_CTX *xctx);
921
922     cb = ctx->verify_cb;
923
924     n = sk_X509_num(ctx->chain);
925     ctx->error_depth = n - 1;
926     n--;
927     xi = sk_X509_value(ctx->chain, n);
928
929     if (ctx->check_issued(ctx, xi, xi))
930         xs = xi;
931     else {
932         if (n <= 0) {
933             ctx->error = X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
934             ctx->current_cert = xi;
935             ok = cb(0, ctx);
936             goto end;
937         } else {
938             n--;
939             ctx->error_depth = n;
940             xs = sk_X509_value(ctx->chain, n);
941         }
942     }
943
944 /*      ctx->error=0;  not needed */
945     while (n >= 0) {
946         ctx->error_depth = n;
947
948         /*
949          * Skip signature check for self signed certificates unless
950          * explicitly asked for. It doesn't add any security and just wastes
951          * time.
952          */
953         if (!xs->valid
954             && (xs != xi
955                 || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE))) {
956             if ((pkey = X509_get_pubkey(xi)) == NULL) {
957                 ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
958                 ctx->current_cert = xi;
959                 ok = (*cb) (0, ctx);
960                 if (!ok)
961                     goto end;
962             } else if (X509_verify(xs, pkey) <= 0) {
963                 ctx->error = X509_V_ERR_CERT_SIGNATURE_FAILURE;
964                 ctx->current_cert = xs;
965                 ok = (*cb) (0, ctx);
966                 if (!ok) {
967                     EVP_PKEY_free(pkey);
968                     goto end;
969                 }
970             }
971             EVP_PKEY_free(pkey);
972             pkey = NULL;
973         }
974
975         xs->valid = 1;
976
977         ok = check_cert_time(ctx, xs);
978         if (!ok)
979             goto end;
980
981         /* The last error (if any) is still in the error value */
982         ctx->current_issuer = xi;
983         ctx->current_cert = xs;
984         ok = (*cb) (1, ctx);
985         if (!ok)
986             goto end;
987
988         n--;
989         if (n >= 0) {
990             xi = xs;
991             xs = sk_X509_value(ctx->chain, n);
992         }
993     }
994     ok = 1;
995  end:
996     return ok;
997 }
998
999 int X509_cmp_current_time(ASN1_TIME *ctm)
1000 {
1001     return X509_cmp_time(ctm, NULL);
1002 }
1003
1004 int X509_cmp_time(ASN1_TIME *ctm, time_t *cmp_time)
1005 {
1006     char *str;
1007     ASN1_TIME atm;
1008     long offset;
1009     char buff1[24], buff2[24], *p;
1010     int i, j, remaining;
1011
1012     p = buff1;
1013     remaining = ctm->length;
1014     str = (char *)ctm->data;
1015     /*
1016      * Note that the following (historical) code allows much more slack in the
1017      * time format than RFC5280. In RFC5280, the representation is fixed:
1018      * UTCTime: YYMMDDHHMMSSZ
1019      * GeneralizedTime: YYYYMMDDHHMMSSZ
1020      */
1021     if (ctm->type == V_ASN1_UTCTIME) {
1022         /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
1023         int min_length = sizeof("YYMMDDHHMMZ") - 1;
1024         int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
1025         if (remaining < min_length || remaining > max_length)
1026             return 0;
1027         memcpy(p, str, 10);
1028         p += 10;
1029         str += 10;
1030         remaining -= 10;
1031     } else {
1032         /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
1033         int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
1034         int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
1035         if (remaining < min_length || remaining > max_length)
1036             return 0;
1037         memcpy(p, str, 12);
1038         p += 12;
1039         str += 12;
1040         remaining -= 12;
1041     }
1042
1043     if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
1044         *(p++) = '0';
1045         *(p++) = '0';
1046     } else {
1047         /* SS (seconds) */
1048         if (remaining < 2)
1049             return 0;
1050         *(p++) = *(str++);
1051         *(p++) = *(str++);
1052         remaining -= 2;
1053         /*
1054          * Skip any (up to three) fractional seconds...
1055          * TODO(emilia): in RFC5280, fractional seconds are forbidden.
1056          * Can we just kill them altogether?
1057          */
1058         if (remaining && *str == '.') {
1059             str++;
1060             remaining--;
1061             for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
1062                 if (*str < '0' || *str > '9')
1063                     break;
1064             }
1065         }
1066
1067     }
1068     *(p++) = 'Z';
1069     *(p++) = '\0';
1070
1071     /* We now need either a terminating 'Z' or an offset. */
1072     if (!remaining)
1073         return 0;
1074     if (*str == 'Z') {
1075         if (remaining != 1)
1076             return 0;
1077         offset = 0;
1078     } else {
1079         /* (+-)HHMM */
1080         if ((*str != '+') && (*str != '-'))
1081             return 0;
1082         /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
1083         if (remaining != 5)
1084             return 0;
1085         if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
1086             str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
1087             return 0;
1088         offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
1089         offset += (str[3] - '0') * 10 + (str[4] - '0');
1090         if (*str == '-')
1091             offset = -offset;
1092     }
1093     atm.type = ctm->type;
1094     atm.length = sizeof(buff2);
1095     atm.data = (unsigned char *)buff2;
1096
1097     if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
1098         return 0;
1099
1100     if (ctm->type == V_ASN1_UTCTIME) {
1101         i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
1102         if (i < 50)
1103             i += 100;           /* cf. RFC 2459 */
1104         j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
1105         if (j < 50)
1106             j += 100;
1107
1108         if (i < j)
1109             return -1;
1110         if (i > j)
1111             return 1;
1112     }
1113     i = strcmp(buff1, buff2);
1114     if (i == 0)                 /* wait a second then return younger :-) */
1115         return -1;
1116     else
1117         return i;
1118 }
1119
1120 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1121 {
1122     return X509_time_adj(s, adj, NULL);
1123 }
1124
1125 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *in_tm)
1126 {
1127     time_t t;
1128     int type = -1;
1129
1130     if (in_tm)
1131         t = *in_tm;
1132     else
1133         time(&t);
1134
1135     t += adj;
1136     if (s)
1137         type = s->type;
1138     if (type == V_ASN1_UTCTIME)
1139         return ASN1_UTCTIME_set(s, t);
1140     if (type == V_ASN1_GENERALIZEDTIME)
1141         return ASN1_GENERALIZEDTIME_set(s, t);
1142     return ASN1_TIME_set(s, t);
1143 }
1144
1145 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1146 {
1147     EVP_PKEY *ktmp = NULL, *ktmp2;
1148     int i, j;
1149
1150     if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1151         return 1;
1152
1153     for (i = 0; i < sk_X509_num(chain); i++) {
1154         ktmp = X509_get_pubkey(sk_X509_value(chain, i));
1155         if (ktmp == NULL) {
1156             X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1157                     X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1158             return 0;
1159         }
1160         if (!EVP_PKEY_missing_parameters(ktmp))
1161             break;
1162         else {
1163             EVP_PKEY_free(ktmp);
1164             ktmp = NULL;
1165         }
1166     }
1167     if (ktmp == NULL) {
1168         X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1169                 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1170         return 0;
1171     }
1172
1173     /* first, populate the other certs */
1174     for (j = i - 1; j >= 0; j--) {
1175         ktmp2 = X509_get_pubkey(sk_X509_value(chain, j));
1176         EVP_PKEY_copy_parameters(ktmp2, ktmp);
1177         EVP_PKEY_free(ktmp2);
1178     }
1179
1180     if (pkey != NULL)
1181         EVP_PKEY_copy_parameters(pkey, ktmp);
1182     EVP_PKEY_free(ktmp);
1183     return 1;
1184 }
1185
1186 int X509_STORE_CTX_get_ex_new_index(long argl, void *argp,
1187                                     CRYPTO_EX_new *new_func,
1188                                     CRYPTO_EX_dup *dup_func,
1189                                     CRYPTO_EX_free *free_func)
1190 {
1191     /*
1192      * This function is (usually) called only once, by
1193      * SSL_get_ex_data_X509_STORE_CTX_idx (ssl/ssl_cert.c).
1194      */
1195     return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, argl, argp,
1196                                    new_func, dup_func, free_func);
1197 }
1198
1199 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
1200 {
1201     return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
1202 }
1203
1204 void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx, int idx)
1205 {
1206     return CRYPTO_get_ex_data(&ctx->ex_data, idx);
1207 }
1208
1209 int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx)
1210 {
1211     return ctx->error;
1212 }
1213
1214 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
1215 {
1216     ctx->error = err;
1217 }
1218
1219 int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx)
1220 {
1221     return ctx->error_depth;
1222 }
1223
1224 X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx)
1225 {
1226     return ctx->current_cert;
1227 }
1228
1229 STACK_OF(X509) *X509_STORE_CTX_get_chain(X509_STORE_CTX *ctx)
1230 {
1231     return ctx->chain;
1232 }
1233
1234 STACK_OF(X509) *X509_STORE_CTX_get1_chain(X509_STORE_CTX *ctx)
1235 {
1236     int i;
1237     X509 *x;
1238     STACK_OF(X509) *chain;
1239     if (!ctx->chain || !(chain = sk_X509_dup(ctx->chain)))
1240         return NULL;
1241     for (i = 0; i < sk_X509_num(chain); i++) {
1242         x = sk_X509_value(chain, i);
1243         CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1244     }
1245     return chain;
1246 }
1247
1248 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
1249 {
1250     ctx->cert = x;
1251 }
1252
1253 void X509_STORE_CTX_set_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
1254 {
1255     ctx->untrusted = sk;
1256 }
1257
1258 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
1259 {
1260     ctx->crls = sk;
1261 }
1262
1263 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
1264 {
1265     return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
1266 }
1267
1268 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
1269 {
1270     return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
1271 }
1272
1273 /*
1274  * This function is used to set the X509_STORE_CTX purpose and trust values.
1275  * This is intended to be used when another structure has its own trust and
1276  * purpose values which (if set) will be inherited by the ctx. If they aren't
1277  * set then we will usually have a default purpose in mind which should then
1278  * be used to set the trust value. An example of this is SSL use: an SSL
1279  * structure will have its own purpose and trust settings which the
1280  * application can set: if they aren't set then we use the default of SSL
1281  * client/server.
1282  */
1283
1284 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
1285                                    int purpose, int trust)
1286 {
1287     int idx;
1288     /* If purpose not set use default */
1289     if (!purpose)
1290         purpose = def_purpose;
1291     /* If we have a purpose then check it is valid */
1292     if (purpose) {
1293         X509_PURPOSE *ptmp;
1294         idx = X509_PURPOSE_get_by_id(purpose);
1295         if (idx == -1) {
1296             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1297                     X509_R_UNKNOWN_PURPOSE_ID);
1298             return 0;
1299         }
1300         ptmp = X509_PURPOSE_get0(idx);
1301         if (ptmp->trust == X509_TRUST_DEFAULT) {
1302             idx = X509_PURPOSE_get_by_id(def_purpose);
1303             if (idx == -1) {
1304                 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1305                         X509_R_UNKNOWN_PURPOSE_ID);
1306                 return 0;
1307             }
1308             ptmp = X509_PURPOSE_get0(idx);
1309         }
1310         /* If trust not set then get from purpose default */
1311         if (!trust)
1312             trust = ptmp->trust;
1313     }
1314     if (trust) {
1315         idx = X509_TRUST_get_by_id(trust);
1316         if (idx == -1) {
1317             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
1318                     X509_R_UNKNOWN_TRUST_ID);
1319             return 0;
1320         }
1321     }
1322
1323     if (purpose && !ctx->param->purpose)
1324         ctx->param->purpose = purpose;
1325     if (trust && !ctx->param->trust)
1326         ctx->param->trust = trust;
1327     return 1;
1328 }
1329
1330 X509_STORE_CTX *X509_STORE_CTX_new(void)
1331 {
1332     X509_STORE_CTX *ctx;
1333     ctx = (X509_STORE_CTX *)OPENSSL_malloc(sizeof(X509_STORE_CTX));
1334     if (!ctx) {
1335         X509err(X509_F_X509_STORE_CTX_NEW, ERR_R_MALLOC_FAILURE);
1336         return NULL;
1337     }
1338     memset(ctx, 0, sizeof(X509_STORE_CTX));
1339     return ctx;
1340 }
1341
1342 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
1343 {
1344     if (!ctx)
1345         return;
1346     X509_STORE_CTX_cleanup(ctx);
1347     OPENSSL_free(ctx);
1348 }
1349
1350 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
1351                         STACK_OF(X509) *chain)
1352 {
1353     int ret = 1;
1354     ctx->ctx = store;
1355     ctx->current_method = 0;
1356     ctx->cert = x509;
1357     ctx->untrusted = chain;
1358     ctx->crls = NULL;
1359     ctx->last_untrusted = 0;
1360     ctx->other_ctx = NULL;
1361     ctx->valid = 0;
1362     ctx->chain = NULL;
1363     ctx->error = 0;
1364     ctx->explicit_policy = 0;
1365     ctx->error_depth = 0;
1366     ctx->current_cert = NULL;
1367     ctx->current_issuer = NULL;
1368     ctx->tree = NULL;
1369
1370     ctx->param = X509_VERIFY_PARAM_new();
1371
1372     if (!ctx->param) {
1373         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
1374         return 0;
1375     }
1376
1377     /*
1378      * Inherit callbacks and flags from X509_STORE if not set use defaults.
1379      */
1380
1381     if (store)
1382         ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
1383     else
1384         ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
1385
1386     if (store) {
1387         ctx->verify_cb = store->verify_cb;
1388         ctx->cleanup = store->cleanup;
1389     } else
1390         ctx->cleanup = 0;
1391
1392     if (ret)
1393         ret = X509_VERIFY_PARAM_inherit(ctx->param,
1394                                         X509_VERIFY_PARAM_lookup("default"));
1395
1396     if (ret == 0) {
1397         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
1398         return 0;
1399     }
1400
1401     if (store && store->check_issued)
1402         ctx->check_issued = store->check_issued;
1403     else
1404         ctx->check_issued = check_issued;
1405
1406     if (store && store->get_issuer)
1407         ctx->get_issuer = store->get_issuer;
1408     else
1409         ctx->get_issuer = X509_STORE_CTX_get1_issuer;
1410
1411     if (store && store->verify_cb)
1412         ctx->verify_cb = store->verify_cb;
1413     else
1414         ctx->verify_cb = null_callback;
1415
1416     if (store && store->verify)
1417         ctx->verify = store->verify;
1418     else
1419         ctx->verify = internal_verify;
1420
1421     if (store && store->check_revocation)
1422         ctx->check_revocation = store->check_revocation;
1423     else
1424         ctx->check_revocation = check_revocation;
1425
1426     if (store && store->get_crl)
1427         ctx->get_crl = store->get_crl;
1428     else
1429         ctx->get_crl = get_crl;
1430
1431     if (store && store->check_crl)
1432         ctx->check_crl = store->check_crl;
1433     else
1434         ctx->check_crl = check_crl;
1435
1436     if (store && store->cert_crl)
1437         ctx->cert_crl = store->cert_crl;
1438     else
1439         ctx->cert_crl = cert_crl;
1440
1441     ctx->check_policy = check_policy;
1442
1443     /*
1444      * This memset() can't make any sense anyway, so it's removed. As
1445      * X509_STORE_CTX_cleanup does a proper "free" on the ex_data, we put a
1446      * corresponding "new" here and remove this bogus initialisation.
1447      */
1448     /* memset(&(ctx->ex_data),0,sizeof(CRYPTO_EX_DATA)); */
1449     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
1450                             &(ctx->ex_data))) {
1451         OPENSSL_free(ctx);
1452         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
1453         return 0;
1454     }
1455     return 1;
1456 }
1457
1458 /*
1459  * Set alternative lookup method: just a STACK of trusted certificates. This
1460  * avoids X509_STORE nastiness where it isn't needed.
1461  */
1462
1463 void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
1464 {
1465     ctx->other_ctx = sk;
1466     ctx->get_issuer = get_issuer_sk;
1467 }
1468
1469 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
1470 {
1471     if (ctx->cleanup)
1472         ctx->cleanup(ctx);
1473     if (ctx->param != NULL) {
1474         X509_VERIFY_PARAM_free(ctx->param);
1475         ctx->param = NULL;
1476     }
1477     if (ctx->tree != NULL) {
1478         X509_policy_tree_free(ctx->tree);
1479         ctx->tree = NULL;
1480     }
1481     if (ctx->chain != NULL) {
1482         sk_X509_pop_free(ctx->chain, X509_free);
1483         ctx->chain = NULL;
1484     }
1485     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
1486     memset(&ctx->ex_data, 0, sizeof(CRYPTO_EX_DATA));
1487 }
1488
1489 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
1490 {
1491     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
1492 }
1493
1494 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
1495 {
1496     X509_VERIFY_PARAM_set_flags(ctx->param, flags);
1497 }
1498
1499 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
1500                              time_t t)
1501 {
1502     X509_VERIFY_PARAM_set_time(ctx->param, t);
1503 }
1504
1505 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
1506                                   int (*verify_cb) (int, X509_STORE_CTX *))
1507 {
1508     ctx->verify_cb = verify_cb;
1509 }
1510
1511 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(X509_STORE_CTX *ctx)
1512 {
1513     return ctx->tree;
1514 }
1515
1516 int X509_STORE_CTX_get_explicit_policy(X509_STORE_CTX *ctx)
1517 {
1518     return ctx->explicit_policy;
1519 }
1520
1521 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
1522 {
1523     const X509_VERIFY_PARAM *param;
1524     param = X509_VERIFY_PARAM_lookup(name);
1525     if (!param)
1526         return 0;
1527     return X509_VERIFY_PARAM_inherit(ctx->param, param);
1528 }
1529
1530 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *ctx)
1531 {
1532     return ctx->param;
1533 }
1534
1535 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
1536 {
1537     if (ctx->param)
1538         X509_VERIFY_PARAM_free(ctx->param);
1539     ctx->param = param;
1540 }
1541
1542 IMPLEMENT_STACK_OF(X509)
1543
1544 IMPLEMENT_ASN1_SET_OF(X509)
1545
1546 IMPLEMENT_STACK_OF(X509_NAME)
1547
1548 IMPLEMENT_STACK_OF(X509_ATTRIBUTE)
1549
1550 IMPLEMENT_ASN1_SET_OF(X509_ATTRIBUTE)