CTR, HASH and HMAC DRBGs in provider
[openssl.git] / crypto / x509 / x509_vfy.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <time.h>
12 #include <errno.h>
13 #include <limits.h>
14
15 #include "crypto/ctype.h"
16 #include "internal/cryptlib.h"
17 #include <openssl/crypto.h>
18 #include <openssl/buffer.h>
19 #include <openssl/evp.h>
20 #include <openssl/asn1.h>
21 #include <openssl/x509.h>
22 #include <openssl/x509v3.h>
23 #include <openssl/objects.h>
24 #include "internal/dane.h"
25 #include "crypto/x509.h"
26 #include "x509_local.h"
27
28 DEFINE_STACK_OF(X509)
29 DEFINE_STACK_OF(X509_REVOKED)
30 DEFINE_STACK_OF(GENERAL_NAME)
31 DEFINE_STACK_OF(X509_CRL)
32 DEFINE_STACK_OF(DIST_POINT)
33 DEFINE_STACK_OF_STRING()
34
35 /* CRL score values */
36
37 /* No unhandled critical extensions */
38
39 #define CRL_SCORE_NOCRITICAL    0x100
40
41 /* certificate is within CRL scope */
42
43 #define CRL_SCORE_SCOPE         0x080
44
45 /* CRL times valid */
46
47 #define CRL_SCORE_TIME          0x040
48
49 /* Issuer name matches certificate */
50
51 #define CRL_SCORE_ISSUER_NAME   0x020
52
53 /* If this score or above CRL is probably valid */
54
55 #define CRL_SCORE_VALID (CRL_SCORE_NOCRITICAL|CRL_SCORE_TIME|CRL_SCORE_SCOPE)
56
57 /* CRL issuer is certificate issuer */
58
59 #define CRL_SCORE_ISSUER_CERT   0x018
60
61 /* CRL issuer is on certificate path */
62
63 #define CRL_SCORE_SAME_PATH     0x008
64
65 /* CRL issuer matches CRL AKID */
66
67 #define CRL_SCORE_AKID          0x004
68
69 /* Have a delta CRL with valid times */
70
71 #define CRL_SCORE_TIME_DELTA    0x002
72
73 static int build_chain(X509_STORE_CTX *ctx);
74 static int verify_chain(X509_STORE_CTX *ctx);
75 static int dane_verify(X509_STORE_CTX *ctx);
76 static int null_callback(int ok, X509_STORE_CTX *e);
77 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
78 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x);
79 static int check_chain_extensions(X509_STORE_CTX *ctx);
80 static int check_name_constraints(X509_STORE_CTX *ctx);
81 static int check_id(X509_STORE_CTX *ctx);
82 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted);
83 static int check_revocation(X509_STORE_CTX *ctx);
84 static int check_cert(X509_STORE_CTX *ctx);
85 static int check_policy(X509_STORE_CTX *ctx);
86 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
87 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth);
88 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert);
89 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert);
90
91 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
92                          unsigned int *preasons, X509_CRL *crl, X509 *x);
93 static int get_crl_delta(X509_STORE_CTX *ctx,
94                          X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x);
95 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl,
96                          int *pcrl_score, X509_CRL *base,
97                          STACK_OF(X509_CRL) *crls);
98 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl, X509 **pissuer,
99                            int *pcrl_score);
100 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
101                            unsigned int *preasons);
102 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x);
103 static int check_crl_chain(X509_STORE_CTX *ctx,
104                            STACK_OF(X509) *cert_path,
105                            STACK_OF(X509) *crl_path);
106
107 static int internal_verify(X509_STORE_CTX *ctx);
108
109 static int null_callback(int ok, X509_STORE_CTX *e)
110 {
111     return ok;
112 }
113
114 /* Return 1 is a certificate is self signed, 0 if not, or -1 on error */
115 static int cert_self_signed(X509_STORE_CTX *ctx, X509 *x)
116 {
117     if (!X509v3_cache_extensions(x, ctx->libctx, ctx->propq))
118         return -1;
119
120     if (x->ex_flags & EXFLAG_SS)
121         return 1;
122     else
123         return 0;
124 }
125
126 /* Given a certificate try and find an exact match in the store */
127
128 static X509 *lookup_cert_match(X509_STORE_CTX *ctx, X509 *x)
129 {
130     STACK_OF(X509) *certs;
131     X509 *xtmp = NULL;
132     int i;
133     /* Lookup all certs with matching subject name */
134     certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
135     if (certs == NULL)
136         return NULL;
137     /* Look for exact match */
138     for (i = 0; i < sk_X509_num(certs); i++) {
139         xtmp = sk_X509_value(certs, i);
140         if (!X509_cmp(xtmp, x))
141             break;
142         xtmp = NULL;
143     }
144     if (xtmp != NULL && !X509_up_ref(xtmp))
145         xtmp = NULL;
146     sk_X509_pop_free(certs, X509_free);
147     return xtmp;
148 }
149
150 /*-
151  * Inform the verify callback of an error.
152  * If B<x> is not NULL it is the error cert, otherwise use the chain cert at
153  * B<depth>.
154  * If B<err> is not X509_V_OK, that's the error value, otherwise leave
155  * unchanged (presumably set by the caller).
156  *
157  * Returns 0 to abort verification with an error, non-zero to continue.
158  */
159 static int verify_cb_cert(X509_STORE_CTX *ctx, X509 *x, int depth, int err)
160 {
161     ctx->error_depth = depth;
162     ctx->current_cert = (x != NULL) ? x : sk_X509_value(ctx->chain, depth);
163     if (err != X509_V_OK)
164         ctx->error = err;
165     return ctx->verify_cb(0, ctx);
166 }
167
168 /*-
169  * Inform the verify callback of an error, CRL-specific variant.  Here, the
170  * error depth and certificate are already set, we just specify the error
171  * number.
172  *
173  * Returns 0 to abort verification with an error, non-zero to continue.
174  */
175 static int verify_cb_crl(X509_STORE_CTX *ctx, int err)
176 {
177     ctx->error = err;
178     return ctx->verify_cb(0, ctx);
179 }
180
181 static int check_auth_level(X509_STORE_CTX *ctx)
182 {
183     int i;
184     int num = sk_X509_num(ctx->chain);
185
186     if (ctx->param->auth_level <= 0)
187         return 1;
188
189     for (i = 0; i < num; ++i) {
190         X509 *cert = sk_X509_value(ctx->chain, i);
191
192         /*
193          * We've already checked the security of the leaf key, so here we only
194          * check the security of issuer keys.
195          */
196         if (i > 0 && !check_key_level(ctx, cert) &&
197             verify_cb_cert(ctx, cert, i, X509_V_ERR_CA_KEY_TOO_SMALL) == 0)
198             return 0;
199         /*
200          * We also check the signature algorithm security of all certificates
201          * except those of the trust anchor at index num-1.
202          */
203         if (i < num - 1 && !check_sig_level(ctx, cert) &&
204             verify_cb_cert(ctx, cert, i, X509_V_ERR_CA_MD_TOO_WEAK) == 0)
205             return 0;
206     }
207     return 1;
208 }
209
210 static int verify_chain(X509_STORE_CTX *ctx)
211 {
212     int err;
213     int ok;
214
215     /*
216      * Before either returning with an error, or continuing with CRL checks,
217      * instantiate chain public key parameters.
218      */
219     if ((ok = build_chain(ctx)) == 0 ||
220         (ok = check_chain_extensions(ctx)) == 0 ||
221         (ok = check_auth_level(ctx)) == 0 ||
222         (ok = check_id(ctx)) == 0 || 1)
223         X509_get_pubkey_parameters(NULL, ctx->chain);
224     if (ok == 0 || (ok = ctx->check_revocation(ctx)) == 0)
225         return ok;
226
227     err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
228                                   ctx->param->flags);
229     if (err != X509_V_OK) {
230         if ((ok = verify_cb_cert(ctx, NULL, ctx->error_depth, err)) == 0)
231             return ok;
232     }
233
234     /* Verify chain signatures and expiration times */
235     ok = (ctx->verify != NULL) ? ctx->verify(ctx) : internal_verify(ctx);
236     if (!ok)
237         return ok;
238
239     if ((ok = check_name_constraints(ctx)) == 0)
240         return ok;
241
242 #ifndef OPENSSL_NO_RFC3779
243     /* RFC 3779 path validation, now that CRL check has been done */
244     if ((ok = X509v3_asid_validate_path(ctx)) == 0)
245         return ok;
246     if ((ok = X509v3_addr_validate_path(ctx)) == 0)
247         return ok;
248 #endif
249
250     /* If we get this far evaluate policies */
251     if (ctx->param->flags & X509_V_FLAG_POLICY_CHECK)
252         ok = ctx->check_policy(ctx);
253     return ok;
254 }
255
256 int X509_verify_cert(X509_STORE_CTX *ctx)
257 {
258     SSL_DANE *dane = ctx->dane;
259     int ret;
260
261     if (ctx->cert == NULL) {
262         X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
263         ctx->error = X509_V_ERR_INVALID_CALL;
264         return -1;
265     }
266
267     if (ctx->chain != NULL) {
268         /*
269          * This X509_STORE_CTX has already been used to verify a cert. We
270          * cannot do another one.
271          */
272         X509err(X509_F_X509_VERIFY_CERT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
273         ctx->error = X509_V_ERR_INVALID_CALL;
274         return -1;
275     }
276
277     if (!X509_up_ref(ctx->cert)) {
278         X509err(X509_F_X509_VERIFY_CERT, ERR_R_INTERNAL_ERROR);
279         ctx->error = X509_V_ERR_UNSPECIFIED;
280         return -1;
281     }
282
283     /*
284      * first we make sure the chain we are going to build is present and that
285      * the first entry is in place
286      */
287     if ((ctx->chain = sk_X509_new_null()) == NULL
288             || !sk_X509_push(ctx->chain, ctx->cert)) {
289         X509_free(ctx->cert);
290         X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
291         ctx->error = X509_V_ERR_OUT_OF_MEM;
292         return -1;
293     }
294
295     ctx->num_untrusted = 1;
296
297     /* If the peer's public key is too weak, we can stop early. */
298     if (!check_key_level(ctx, ctx->cert) &&
299         !verify_cb_cert(ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL))
300         return 0;
301
302     if (DANETLS_ENABLED(dane))
303         ret = dane_verify(ctx);
304     else
305         ret = verify_chain(ctx);
306
307     /*
308      * Safety-net.  If we are returning an error, we must also set ctx->error,
309      * so that the chain is not considered verified should the error be ignored
310      * (e.g. TLS with SSL_VERIFY_NONE).
311      */
312     if (ret <= 0 && ctx->error == X509_V_OK)
313         ctx->error = X509_V_ERR_UNSPECIFIED;
314     return ret;
315 }
316
317 /*
318  * Given a STACK_OF(X509) find the issuer of cert (if any)
319  */
320 static X509 *find_issuer(X509_STORE_CTX *ctx, STACK_OF(X509) *sk, X509 *x)
321 {
322     int i;
323     X509 *issuer, *rv = NULL;
324
325     for (i = 0; i < sk_X509_num(sk); i++) {
326         issuer = sk_X509_value(sk, i);
327         if (ctx->check_issued(ctx, x, issuer)) {
328             rv = issuer;
329             if (x509_check_cert_time(ctx, rv, -1))
330                 break;
331         }
332     }
333     return rv;
334 }
335
336 /* Given a possible certificate and issuer check them */
337
338 static int check_issued(X509_STORE_CTX *ctx, X509 *x, X509 *issuer)
339 {
340     int ret;
341     int ss;
342
343     if (x == issuer) {
344         ss = cert_self_signed(ctx, x);
345         if (ss < 0)
346             return 0;
347         return ss;
348     }
349
350     ret = x509_check_issued_int(issuer, x, ctx->libctx, ctx->propq);
351     if (ret == X509_V_OK) {
352         int i;
353         X509 *ch;
354
355         ss = cert_self_signed(ctx, x);
356         if (ss < 0)
357             return 0;
358
359         /* Special case: single self signed certificate */
360         if (ss > 0 && sk_X509_num(ctx->chain) == 1)
361             return 1;
362         for (i = 0; i < sk_X509_num(ctx->chain); i++) {
363             ch = sk_X509_value(ctx->chain, i);
364             if (ch == issuer || !X509_cmp(ch, issuer)) {
365                 ret = X509_V_ERR_PATH_LOOP;
366                 break;
367             }
368         }
369     }
370
371     return (ret == X509_V_OK);
372 }
373
374 /* Alternative lookup method: look from a STACK stored in other_ctx */
375
376 static int get_issuer_sk(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
377 {
378     *issuer = find_issuer(ctx, ctx->other_ctx, x);
379
380     if (*issuer == NULL || !X509_up_ref(*issuer))
381         goto err;
382
383     return 1;
384
385  err:
386     *issuer = NULL;
387     return 0;
388 }
389
390 static STACK_OF(X509) *lookup_certs_sk(X509_STORE_CTX *ctx,
391                                        const X509_NAME *nm)
392 {
393     STACK_OF(X509) *sk = NULL;
394     X509 *x;
395     int i;
396
397     for (i = 0; i < sk_X509_num(ctx->other_ctx); i++) {
398         x = sk_X509_value(ctx->other_ctx, i);
399         if (X509_NAME_cmp(nm, X509_get_subject_name(x)) == 0) {
400             if (!X509_up_ref(x)) {
401                 sk_X509_pop_free(sk, X509_free);
402                 X509err(X509_F_LOOKUP_CERTS_SK, ERR_R_INTERNAL_ERROR);
403                 ctx->error = X509_V_ERR_UNSPECIFIED;
404                 return NULL;
405             }
406             if (sk == NULL)
407                 sk = sk_X509_new_null();
408             if (sk == NULL || !sk_X509_push(sk, x)) {
409                 X509_free(x);
410                 sk_X509_pop_free(sk, X509_free);
411                 X509err(X509_F_LOOKUP_CERTS_SK, ERR_R_MALLOC_FAILURE);
412                 ctx->error = X509_V_ERR_OUT_OF_MEM;
413                 return NULL;
414             }
415         }
416     }
417     return sk;
418 }
419
420 /*
421  * Check EE or CA certificate purpose.  For trusted certificates explicit local
422  * auxiliary trust can be used to override EKU-restrictions.
423  */
424 static int check_purpose(X509_STORE_CTX *ctx, X509 *x, int purpose, int depth,
425                          int must_be_ca)
426 {
427     int tr_ok = X509_TRUST_UNTRUSTED;
428
429     /*
430      * For trusted certificates we want to see whether any auxiliary trust
431      * settings trump the purpose constraints.
432      *
433      * This is complicated by the fact that the trust ordinals in
434      * ctx->param->trust are entirely independent of the purpose ordinals in
435      * ctx->param->purpose!
436      *
437      * What connects them is their mutual initialization via calls from
438      * X509_STORE_CTX_set_default() into X509_VERIFY_PARAM_lookup() which sets
439      * related values of both param->trust and param->purpose.  It is however
440      * typically possible to infer associated trust values from a purpose value
441      * via the X509_PURPOSE API.
442      *
443      * Therefore, we can only check for trust overrides when the purpose we're
444      * checking is the same as ctx->param->purpose and ctx->param->trust is
445      * also set.
446      */
447     if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
448         tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
449
450     switch (tr_ok) {
451     case X509_TRUST_TRUSTED:
452         return 1;
453     case X509_TRUST_REJECTED:
454         break;
455     default:
456         switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
457         case 1:
458             return 1;
459         case 0:
460             break;
461         default:
462             if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
463                 return 1;
464         }
465         break;
466     }
467
468     return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE);
469 }
470
471 /*
472  * Check a certificate chains extensions for consistency with the supplied
473  * purpose
474  */
475
476 static int check_chain_extensions(X509_STORE_CTX *ctx)
477 {
478     int i, must_be_ca, plen = 0;
479     X509 *x;
480     int proxy_path_length = 0;
481     int purpose;
482     int allow_proxy_certs;
483     int num = sk_X509_num(ctx->chain);
484
485     /*-
486      *  must_be_ca can have 1 of 3 values:
487      * -1: we accept both CA and non-CA certificates, to allow direct
488      *     use of self-signed certificates (which are marked as CA).
489      * 0:  we only accept non-CA certificates.  This is currently not
490      *     used, but the possibility is present for future extensions.
491      * 1:  we only accept CA certificates.  This is currently used for
492      *     all certificates in the chain except the leaf certificate.
493      */
494     must_be_ca = -1;
495
496     /* CRL path validation */
497     if (ctx->parent) {
498         allow_proxy_certs = 0;
499         purpose = X509_PURPOSE_CRL_SIGN;
500     } else {
501         allow_proxy_certs =
502             ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS);
503         purpose = ctx->param->purpose;
504     }
505
506     for (i = 0; i < num; i++) {
507         int ret;
508         x = sk_X509_value(ctx->chain, i);
509         if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
510             && (x->ex_flags & EXFLAG_CRITICAL)) {
511             if (!verify_cb_cert(ctx, x, i,
512                                 X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION))
513                 return 0;
514         }
515         if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) {
516             if (!verify_cb_cert(ctx, x, i,
517                                 X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED))
518                 return 0;
519         }
520         ret = X509_check_ca(x);
521         switch (must_be_ca) {
522         case -1:
523             if ((ctx->param->flags & X509_V_FLAG_X509_STRICT)
524                 && (ret != 1) && (ret != 0)) {
525                 ret = 0;
526                 ctx->error = X509_V_ERR_INVALID_CA;
527             } else
528                 ret = 1;
529             break;
530         case 0:
531             if (ret != 0) {
532                 ret = 0;
533                 ctx->error = X509_V_ERR_INVALID_NON_CA;
534             } else
535                 ret = 1;
536             break;
537         default:
538             /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */
539             if ((ret == 0)
540                 || ((i + 1 < num || ctx->param->flags & X509_V_FLAG_X509_STRICT)
541                     && (ret != 1))) {
542                 ret = 0;
543                 ctx->error = X509_V_ERR_INVALID_CA;
544             } else
545                 ret = 1;
546             break;
547         }
548         if ((x->ex_flags & EXFLAG_CA) == 0
549             && x->ex_pathlen != -1
550             && (ctx->param->flags & X509_V_FLAG_X509_STRICT)) {
551             ctx->error = X509_V_ERR_INVALID_EXTENSION;
552             ret = 0;
553         }
554         if (ret == 0 && !verify_cb_cert(ctx, x, i, X509_V_OK))
555             return 0;
556         /* check_purpose() makes the callback as needed */
557         if (purpose > 0 && !check_purpose(ctx, x, purpose, i, must_be_ca))
558             return 0;
559         /* Check pathlen */
560         if ((i > 1) && (x->ex_pathlen != -1)
561             && (plen > (x->ex_pathlen + proxy_path_length))) {
562             if (!verify_cb_cert(ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED))
563                 return 0;
564         }
565         /* Increment path length if not a self issued intermediate CA */
566         if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0)
567             plen++;
568         /*
569          * If this certificate is a proxy certificate, the next certificate
570          * must be another proxy certificate or a EE certificate.  If not,
571          * the next certificate must be a CA certificate.
572          */
573         if (x->ex_flags & EXFLAG_PROXY) {
574             /*
575              * RFC3820, 4.1.3 (b)(1) stipulates that if pCPathLengthConstraint
576              * is less than max_path_length, the former should be copied to
577              * the latter, and 4.1.4 (a) stipulates that max_path_length
578              * should be verified to be larger than zero and decrement it.
579              *
580              * Because we're checking the certs in the reverse order, we start
581              * with verifying that proxy_path_length isn't larger than pcPLC,
582              * and copy the latter to the former if it is, and finally,
583              * increment proxy_path_length.
584              */
585             if (x->ex_pcpathlen != -1) {
586                 if (proxy_path_length > x->ex_pcpathlen) {
587                     if (!verify_cb_cert(ctx, x, i,
588                                         X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED))
589                         return 0;
590                 }
591                 proxy_path_length = x->ex_pcpathlen;
592             }
593             proxy_path_length++;
594             must_be_ca = 0;
595         } else
596             must_be_ca = 1;
597     }
598     return 1;
599 }
600
601 static int has_san_id(X509 *x, int gtype)
602 {
603     int i;
604     int ret = 0;
605     GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
606
607     if (gs == NULL)
608         return 0;
609
610     for (i = 0; i < sk_GENERAL_NAME_num(gs); i++) {
611         GENERAL_NAME *g = sk_GENERAL_NAME_value(gs, i);
612
613         if (g->type == gtype) {
614             ret = 1;
615             break;
616         }
617     }
618     GENERAL_NAMES_free(gs);
619     return ret;
620 }
621
622 static int check_name_constraints(X509_STORE_CTX *ctx)
623 {
624     int i;
625
626     /* Check name constraints for all certificates */
627     for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
628         X509 *x = sk_X509_value(ctx->chain, i);
629         int j;
630
631         /* Ignore self issued certs unless last in chain */
632         if (i && (x->ex_flags & EXFLAG_SI))
633             continue;
634
635         /*
636          * Proxy certificates policy has an extra constraint, where the
637          * certificate subject MUST be the issuer with a single CN entry
638          * added.
639          * (RFC 3820: 3.4, 4.1.3 (a)(4))
640          */
641         if (x->ex_flags & EXFLAG_PROXY) {
642             X509_NAME *tmpsubject = X509_get_subject_name(x);
643             X509_NAME *tmpissuer = X509_get_issuer_name(x);
644             X509_NAME_ENTRY *tmpentry = NULL;
645             int last_object_nid = 0;
646             int err = X509_V_OK;
647             int last_object_loc = X509_NAME_entry_count(tmpsubject) - 1;
648
649             /* Check that there are at least two RDNs */
650             if (last_object_loc < 1) {
651                 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
652                 goto proxy_name_done;
653             }
654
655             /*
656              * Check that there is exactly one more RDN in subject as
657              * there is in issuer.
658              */
659             if (X509_NAME_entry_count(tmpsubject)
660                 != X509_NAME_entry_count(tmpissuer) + 1) {
661                 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
662                 goto proxy_name_done;
663             }
664
665             /*
666              * Check that the last subject component isn't part of a
667              * multivalued RDN
668              */
669             if (X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
670                                                         last_object_loc))
671                 == X509_NAME_ENTRY_set(X509_NAME_get_entry(tmpsubject,
672                                                            last_object_loc - 1))) {
673                 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
674                 goto proxy_name_done;
675             }
676
677             /*
678              * Check that the last subject RDN is a commonName, and that
679              * all the previous RDNs match the issuer exactly
680              */
681             tmpsubject = X509_NAME_dup(tmpsubject);
682             if (tmpsubject == NULL) {
683                 X509err(X509_F_CHECK_NAME_CONSTRAINTS, ERR_R_MALLOC_FAILURE);
684                 ctx->error = X509_V_ERR_OUT_OF_MEM;
685                 return 0;
686             }
687
688             tmpentry =
689                 X509_NAME_delete_entry(tmpsubject, last_object_loc);
690             last_object_nid =
691                 OBJ_obj2nid(X509_NAME_ENTRY_get_object(tmpentry));
692
693             if (last_object_nid != NID_commonName
694                 || X509_NAME_cmp(tmpsubject, tmpissuer) != 0) {
695                 err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
696             }
697
698             X509_NAME_ENTRY_free(tmpentry);
699             X509_NAME_free(tmpsubject);
700
701          proxy_name_done:
702             if (err != X509_V_OK
703                 && !verify_cb_cert(ctx, x, i, err))
704                 return 0;
705         }
706
707         /*
708          * Check against constraints for all certificates higher in chain
709          * including trust anchor. Trust anchor not strictly speaking needed
710          * but if it includes constraints it is to be assumed it expects them
711          * to be obeyed.
712          */
713         for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
714             NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
715
716             if (nc) {
717                 int rv = NAME_CONSTRAINTS_check(x, nc);
718
719                 /* If EE certificate check commonName too */
720                 if (rv == X509_V_OK && i == 0
721                     && (ctx->param->hostflags
722                         & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT) == 0
723                     && ((ctx->param->hostflags
724                          & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT) != 0
725                         || !has_san_id(x, GEN_DNS)))
726                     rv = NAME_CONSTRAINTS_check_CN(x, nc);
727
728                 switch (rv) {
729                 case X509_V_OK:
730                     break;
731                 case X509_V_ERR_OUT_OF_MEM:
732                     return 0;
733                 default:
734                     if (!verify_cb_cert(ctx, x, i, rv))
735                         return 0;
736                     break;
737                 }
738             }
739         }
740     }
741     return 1;
742 }
743
744 static int check_id_error(X509_STORE_CTX *ctx, int errcode)
745 {
746     return verify_cb_cert(ctx, ctx->cert, 0, errcode);
747 }
748
749 static int check_hosts(X509 *x, X509_VERIFY_PARAM *vpm)
750 {
751     int i;
752     int n = sk_OPENSSL_STRING_num(vpm->hosts);
753     char *name;
754
755     if (vpm->peername != NULL) {
756         OPENSSL_free(vpm->peername);
757         vpm->peername = NULL;
758     }
759     for (i = 0; i < n; ++i) {
760         name = sk_OPENSSL_STRING_value(vpm->hosts, i);
761         if (X509_check_host(x, name, 0, vpm->hostflags, &vpm->peername) > 0)
762             return 1;
763     }
764     return n == 0;
765 }
766
767 static int check_id(X509_STORE_CTX *ctx)
768 {
769     X509_VERIFY_PARAM *vpm = ctx->param;
770     X509 *x = ctx->cert;
771     if (vpm->hosts && check_hosts(x, vpm) <= 0) {
772         if (!check_id_error(ctx, X509_V_ERR_HOSTNAME_MISMATCH))
773             return 0;
774     }
775     if (vpm->email && X509_check_email(x, vpm->email, vpm->emaillen, 0) <= 0) {
776         if (!check_id_error(ctx, X509_V_ERR_EMAIL_MISMATCH))
777             return 0;
778     }
779     if (vpm->ip && X509_check_ip(x, vpm->ip, vpm->iplen, 0) <= 0) {
780         if (!check_id_error(ctx, X509_V_ERR_IP_ADDRESS_MISMATCH))
781             return 0;
782     }
783     return 1;
784 }
785
786 static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
787 {
788     int i;
789     X509 *x = NULL;
790     X509 *mx;
791     SSL_DANE *dane = ctx->dane;
792     int num = sk_X509_num(ctx->chain);
793     int trust;
794
795     /*
796      * Check for a DANE issuer at depth 1 or greater, if it is a DANE-TA(2)
797      * match, we're done, otherwise we'll merely record the match depth.
798      */
799     if (DANETLS_HAS_TA(dane) && num_untrusted > 0 && num_untrusted < num) {
800         switch (trust = check_dane_issuer(ctx, num_untrusted)) {
801         case X509_TRUST_TRUSTED:
802         case X509_TRUST_REJECTED:
803             return trust;
804         }
805     }
806
807     /*
808      * Check trusted certificates in chain at depth num_untrusted and up.
809      * Note, that depths 0..num_untrusted-1 may also contain trusted
810      * certificates, but the caller is expected to have already checked those,
811      * and wants to incrementally check just any added since.
812      */
813     for (i = num_untrusted; i < num; i++) {
814         x = sk_X509_value(ctx->chain, i);
815         trust = X509_check_trust(x, ctx->param->trust, 0);
816         /* If explicitly trusted return trusted */
817         if (trust == X509_TRUST_TRUSTED)
818             goto trusted;
819         if (trust == X509_TRUST_REJECTED)
820             goto rejected;
821     }
822
823     /*
824      * If we are looking at a trusted certificate, and accept partial chains,
825      * the chain is PKIX trusted.
826      */
827     if (num_untrusted < num) {
828         if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN)
829             goto trusted;
830         return X509_TRUST_UNTRUSTED;
831     }
832
833     if (num_untrusted == num && ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
834         /*
835          * Last-resort call with no new trusted certificates, check the leaf
836          * for a direct trust store match.
837          */
838         i = 0;
839         x = sk_X509_value(ctx->chain, i);
840         mx = lookup_cert_match(ctx, x);
841         if (!mx)
842             return X509_TRUST_UNTRUSTED;
843
844         /*
845          * Check explicit auxiliary trust/reject settings.  If none are set,
846          * we'll accept X509_TRUST_UNTRUSTED when not self-signed.
847          */
848         trust = X509_check_trust(mx, ctx->param->trust, 0);
849         if (trust == X509_TRUST_REJECTED) {
850             X509_free(mx);
851             goto rejected;
852         }
853
854         /* Replace leaf with trusted match */
855         (void) sk_X509_set(ctx->chain, 0, mx);
856         X509_free(x);
857         ctx->num_untrusted = 0;
858         goto trusted;
859     }
860
861     /*
862      * If no trusted certs in chain at all return untrusted and allow
863      * standard (no issuer cert) etc errors to be indicated.
864      */
865     return X509_TRUST_UNTRUSTED;
866
867  rejected:
868     if (!verify_cb_cert(ctx, x, i, X509_V_ERR_CERT_REJECTED))
869         return X509_TRUST_REJECTED;
870     return X509_TRUST_UNTRUSTED;
871
872  trusted:
873     if (!DANETLS_ENABLED(dane))
874         return X509_TRUST_TRUSTED;
875     if (dane->pdpth < 0)
876         dane->pdpth = num_untrusted;
877     /* With DANE, PKIX alone is not trusted until we have both */
878     if (dane->mdpth >= 0)
879         return X509_TRUST_TRUSTED;
880     return X509_TRUST_UNTRUSTED;
881 }
882
883 static int check_revocation(X509_STORE_CTX *ctx)
884 {
885     int i = 0, last = 0, ok = 0;
886     if (!(ctx->param->flags & X509_V_FLAG_CRL_CHECK))
887         return 1;
888     if (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL)
889         last = sk_X509_num(ctx->chain) - 1;
890     else {
891         /* If checking CRL paths this isn't the EE certificate */
892         if (ctx->parent)
893             return 1;
894         last = 0;
895     }
896     for (i = 0; i <= last; i++) {
897         ctx->error_depth = i;
898         ok = check_cert(ctx);
899         if (!ok)
900             return ok;
901     }
902     return 1;
903 }
904
905 static int check_cert(X509_STORE_CTX *ctx)
906 {
907     X509_CRL *crl = NULL, *dcrl = NULL;
908     int ok = 0;
909     int cnum = ctx->error_depth;
910     X509 *x = sk_X509_value(ctx->chain, cnum);
911
912     ctx->current_cert = x;
913     ctx->current_issuer = NULL;
914     ctx->current_crl_score = 0;
915     ctx->current_reasons = 0;
916
917     if (x->ex_flags & EXFLAG_PROXY)
918         return 1;
919
920     while (ctx->current_reasons != CRLDP_ALL_REASONS) {
921         unsigned int last_reasons = ctx->current_reasons;
922
923         /* Try to retrieve relevant CRL */
924         if (ctx->get_crl)
925             ok = ctx->get_crl(ctx, &crl, x);
926         else
927             ok = get_crl_delta(ctx, &crl, &dcrl, x);
928         /*
929          * If error looking up CRL, nothing we can do except notify callback
930          */
931         if (!ok) {
932             ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
933             goto done;
934         }
935         ctx->current_crl = crl;
936         ok = ctx->check_crl(ctx, crl);
937         if (!ok)
938             goto done;
939
940         if (dcrl) {
941             ok = ctx->check_crl(ctx, dcrl);
942             if (!ok)
943                 goto done;
944             ok = ctx->cert_crl(ctx, dcrl, x);
945             if (!ok)
946                 goto done;
947         } else
948             ok = 1;
949
950         /* Don't look in full CRL if delta reason is removefromCRL */
951         if (ok != 2) {
952             ok = ctx->cert_crl(ctx, crl, x);
953             if (!ok)
954                 goto done;
955         }
956
957         X509_CRL_free(crl);
958         X509_CRL_free(dcrl);
959         crl = NULL;
960         dcrl = NULL;
961         /*
962          * If reasons not updated we won't get anywhere by another iteration,
963          * so exit loop.
964          */
965         if (last_reasons == ctx->current_reasons) {
966             ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
967             goto done;
968         }
969     }
970  done:
971     X509_CRL_free(crl);
972     X509_CRL_free(dcrl);
973
974     ctx->current_crl = NULL;
975     return ok;
976 }
977
978 /* Check CRL times against values in X509_STORE_CTX */
979
980 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
981 {
982     time_t *ptime;
983     int i;
984
985     if (notify)
986         ctx->current_crl = crl;
987     if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
988         ptime = &ctx->param->check_time;
989     else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
990         return 1;
991     else
992         ptime = NULL;
993
994     i = X509_cmp_time(X509_CRL_get0_lastUpdate(crl), ptime);
995     if (i == 0) {
996         if (!notify)
997             return 0;
998         if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD))
999             return 0;
1000     }
1001
1002     if (i > 0) {
1003         if (!notify)
1004             return 0;
1005         if (!verify_cb_crl(ctx, X509_V_ERR_CRL_NOT_YET_VALID))
1006             return 0;
1007     }
1008
1009     if (X509_CRL_get0_nextUpdate(crl)) {
1010         i = X509_cmp_time(X509_CRL_get0_nextUpdate(crl), ptime);
1011
1012         if (i == 0) {
1013             if (!notify)
1014                 return 0;
1015             if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD))
1016                 return 0;
1017         }
1018         /* Ignore expiry of base CRL is delta is valid */
1019         if ((i < 0) && !(ctx->current_crl_score & CRL_SCORE_TIME_DELTA)) {
1020             if (!notify)
1021                 return 0;
1022             if (!verify_cb_crl(ctx, X509_V_ERR_CRL_HAS_EXPIRED))
1023                 return 0;
1024         }
1025     }
1026
1027     if (notify)
1028         ctx->current_crl = NULL;
1029
1030     return 1;
1031 }
1032
1033 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1034                       X509 **pissuer, int *pscore, unsigned int *preasons,
1035                       STACK_OF(X509_CRL) *crls)
1036 {
1037     int i, crl_score, best_score = *pscore;
1038     unsigned int reasons, best_reasons = 0;
1039     X509 *x = ctx->current_cert;
1040     X509_CRL *crl, *best_crl = NULL;
1041     X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1042
1043     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1044         crl = sk_X509_CRL_value(crls, i);
1045         reasons = *preasons;
1046         crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1047         if (crl_score < best_score || crl_score == 0)
1048             continue;
1049         /* If current CRL is equivalent use it if it is newer */
1050         if (crl_score == best_score && best_crl != NULL) {
1051             int day, sec;
1052             if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl),
1053                                X509_CRL_get0_lastUpdate(crl)) == 0)
1054                 continue;
1055             /*
1056              * ASN1_TIME_diff never returns inconsistent signs for |day|
1057              * and |sec|.
1058              */
1059             if (day <= 0 && sec <= 0)
1060                 continue;
1061         }
1062         best_crl = crl;
1063         best_crl_issuer = crl_issuer;
1064         best_score = crl_score;
1065         best_reasons = reasons;
1066     }
1067
1068     if (best_crl) {
1069         X509_CRL_free(*pcrl);
1070         *pcrl = best_crl;
1071         *pissuer = best_crl_issuer;
1072         *pscore = best_score;
1073         *preasons = best_reasons;
1074         X509_CRL_up_ref(best_crl);
1075         X509_CRL_free(*pdcrl);
1076         *pdcrl = NULL;
1077         get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1078     }
1079
1080     if (best_score >= CRL_SCORE_VALID)
1081         return 1;
1082
1083     return 0;
1084 }
1085
1086 /*
1087  * Compare two CRL extensions for delta checking purposes. They should be
1088  * both present or both absent. If both present all fields must be identical.
1089  */
1090
1091 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1092 {
1093     ASN1_OCTET_STRING *exta, *extb;
1094     int i;
1095     i = X509_CRL_get_ext_by_NID(a, nid, -1);
1096     if (i >= 0) {
1097         /* Can't have multiple occurrences */
1098         if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1099             return 0;
1100         exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1101     } else
1102         exta = NULL;
1103
1104     i = X509_CRL_get_ext_by_NID(b, nid, -1);
1105
1106     if (i >= 0) {
1107
1108         if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1109             return 0;
1110         extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1111     } else
1112         extb = NULL;
1113
1114     if (!exta && !extb)
1115         return 1;
1116
1117     if (!exta || !extb)
1118         return 0;
1119
1120     if (ASN1_OCTET_STRING_cmp(exta, extb))
1121         return 0;
1122
1123     return 1;
1124 }
1125
1126 /* See if a base and delta are compatible */
1127
1128 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
1129 {
1130     /* Delta CRL must be a delta */
1131     if (!delta->base_crl_number)
1132         return 0;
1133     /* Base must have a CRL number */
1134     if (!base->crl_number)
1135         return 0;
1136     /* Issuer names must match */
1137     if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(delta)))
1138         return 0;
1139     /* AKID and IDP must match */
1140     if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1141         return 0;
1142     if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1143         return 0;
1144     /* Delta CRL base number must not exceed Full CRL number. */
1145     if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1146         return 0;
1147     /* Delta CRL number must exceed full CRL number */
1148     if (ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0)
1149         return 1;
1150     return 0;
1151 }
1152
1153 /*
1154  * For a given base CRL find a delta... maybe extend to delta scoring or
1155  * retrieve a chain of deltas...
1156  */
1157
1158 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
1159                          X509_CRL *base, STACK_OF(X509_CRL) *crls)
1160 {
1161     X509_CRL *delta;
1162     int i;
1163     if (!(ctx->param->flags & X509_V_FLAG_USE_DELTAS))
1164         return;
1165     if (!((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST))
1166         return;
1167     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1168         delta = sk_X509_CRL_value(crls, i);
1169         if (check_delta_base(delta, base)) {
1170             if (check_crl_time(ctx, delta, 0))
1171                 *pscore |= CRL_SCORE_TIME_DELTA;
1172             X509_CRL_up_ref(delta);
1173             *dcrl = delta;
1174             return;
1175         }
1176     }
1177     *dcrl = NULL;
1178 }
1179
1180 /*
1181  * For a given CRL return how suitable it is for the supplied certificate
1182  * 'x'. The return value is a mask of several criteria. If the issuer is not
1183  * the certificate issuer this is returned in *pissuer. The reasons mask is
1184  * also used to determine if the CRL is suitable: if no new reasons the CRL
1185  * is rejected, otherwise reasons is updated.
1186  */
1187
1188 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1189                          unsigned int *preasons, X509_CRL *crl, X509 *x)
1190 {
1191
1192     int crl_score = 0;
1193     unsigned int tmp_reasons = *preasons, crl_reasons;
1194
1195     /* First see if we can reject CRL straight away */
1196
1197     /* Invalid IDP cannot be processed */
1198     if (crl->idp_flags & IDP_INVALID)
1199         return 0;
1200     /* Reason codes or indirect CRLs need extended CRL support */
1201     if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT)) {
1202         if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1203             return 0;
1204     } else if (crl->idp_flags & IDP_REASONS) {
1205         /* If no new reasons reject */
1206         if (!(crl->idp_reasons & ~tmp_reasons))
1207             return 0;
1208     }
1209     /* Don't process deltas at this stage */
1210     else if (crl->base_crl_number)
1211         return 0;
1212     /* If issuer name doesn't match certificate need indirect CRL */
1213     if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl))) {
1214         if (!(crl->idp_flags & IDP_INDIRECT))
1215             return 0;
1216     } else
1217         crl_score |= CRL_SCORE_ISSUER_NAME;
1218
1219     if (!(crl->flags & EXFLAG_CRITICAL))
1220         crl_score |= CRL_SCORE_NOCRITICAL;
1221
1222     /* Check expiry */
1223     if (check_crl_time(ctx, crl, 0))
1224         crl_score |= CRL_SCORE_TIME;
1225
1226     /* Check authority key ID and locate certificate issuer */
1227     crl_akid_check(ctx, crl, pissuer, &crl_score);
1228
1229     /* If we can't locate certificate issuer at this point forget it */
1230
1231     if (!(crl_score & CRL_SCORE_AKID))
1232         return 0;
1233
1234     /* Check cert for matching CRL distribution points */
1235
1236     if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1237         /* If no new reasons reject */
1238         if (!(crl_reasons & ~tmp_reasons))
1239             return 0;
1240         tmp_reasons |= crl_reasons;
1241         crl_score |= CRL_SCORE_SCOPE;
1242     }
1243
1244     *preasons = tmp_reasons;
1245
1246     return crl_score;
1247
1248 }
1249
1250 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1251                            X509 **pissuer, int *pcrl_score)
1252 {
1253     X509 *crl_issuer = NULL;
1254     const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1255     int cidx = ctx->error_depth;
1256     int i;
1257
1258     if (cidx != sk_X509_num(ctx->chain) - 1)
1259         cidx++;
1260
1261     crl_issuer = sk_X509_value(ctx->chain, cidx);
1262
1263     if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1264         if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1265             *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1266             *pissuer = crl_issuer;
1267             return;
1268         }
1269     }
1270
1271     for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1272         crl_issuer = sk_X509_value(ctx->chain, cidx);
1273         if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1274             continue;
1275         if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1276             *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1277             *pissuer = crl_issuer;
1278             return;
1279         }
1280     }
1281
1282     /* Anything else needs extended CRL support */
1283
1284     if (!(ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT))
1285         return;
1286
1287     /*
1288      * Otherwise the CRL issuer is not on the path. Look for it in the set of
1289      * untrusted certificates.
1290      */
1291     for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1292         crl_issuer = sk_X509_value(ctx->untrusted, i);
1293         if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1294             continue;
1295         if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1296             *pissuer = crl_issuer;
1297             *pcrl_score |= CRL_SCORE_AKID;
1298             return;
1299         }
1300     }
1301 }
1302
1303 /*
1304  * Check the path of a CRL issuer certificate. This creates a new
1305  * X509_STORE_CTX and populates it with most of the parameters from the
1306  * parent. This could be optimised somewhat since a lot of path checking will
1307  * be duplicated by the parent, but this will rarely be used in practice.
1308  */
1309
1310 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1311 {
1312     X509_STORE_CTX crl_ctx;
1313     int ret;
1314
1315     /* Don't allow recursive CRL path validation */
1316     if (ctx->parent)
1317         return 0;
1318     if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted))
1319         return -1;
1320
1321     crl_ctx.crls = ctx->crls;
1322     /* Copy verify params across */
1323     X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1324
1325     crl_ctx.parent = ctx;
1326     crl_ctx.verify_cb = ctx->verify_cb;
1327
1328     /* Verify CRL issuer */
1329     ret = X509_verify_cert(&crl_ctx);
1330     if (ret <= 0)
1331         goto err;
1332
1333     /* Check chain is acceptable */
1334     ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1335  err:
1336     X509_STORE_CTX_cleanup(&crl_ctx);
1337     return ret;
1338 }
1339
1340 /*
1341  * RFC3280 says nothing about the relationship between CRL path and
1342  * certificate path, which could lead to situations where a certificate could
1343  * be revoked or validated by a CA not authorised to do so. RFC5280 is more
1344  * strict and states that the two paths must end in the same trust anchor,
1345  * though some discussions remain... until this is resolved we use the
1346  * RFC5280 version
1347  */
1348
1349 static int check_crl_chain(X509_STORE_CTX *ctx,
1350                            STACK_OF(X509) *cert_path,
1351                            STACK_OF(X509) *crl_path)
1352 {
1353     X509 *cert_ta, *crl_ta;
1354     cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1355     crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1356     if (!X509_cmp(cert_ta, crl_ta))
1357         return 1;
1358     return 0;
1359 }
1360
1361 /*-
1362  * Check for match between two dist point names: three separate cases.
1363  * 1. Both are relative names and compare X509_NAME types.
1364  * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1365  * 3. Both are full names and compare two GENERAL_NAMES.
1366  * 4. One is NULL: automatic match.
1367  */
1368
1369 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1370 {
1371     X509_NAME *nm = NULL;
1372     GENERAL_NAMES *gens = NULL;
1373     GENERAL_NAME *gena, *genb;
1374     int i, j;
1375     if (!a || !b)
1376         return 1;
1377     if (a->type == 1) {
1378         if (!a->dpname)
1379             return 0;
1380         /* Case 1: two X509_NAME */
1381         if (b->type == 1) {
1382             if (!b->dpname)
1383                 return 0;
1384             if (!X509_NAME_cmp(a->dpname, b->dpname))
1385                 return 1;
1386             else
1387                 return 0;
1388         }
1389         /* Case 2: set name and GENERAL_NAMES appropriately */
1390         nm = a->dpname;
1391         gens = b->name.fullname;
1392     } else if (b->type == 1) {
1393         if (!b->dpname)
1394             return 0;
1395         /* Case 2: set name and GENERAL_NAMES appropriately */
1396         gens = a->name.fullname;
1397         nm = b->dpname;
1398     }
1399
1400     /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1401     if (nm) {
1402         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1403             gena = sk_GENERAL_NAME_value(gens, i);
1404             if (gena->type != GEN_DIRNAME)
1405                 continue;
1406             if (!X509_NAME_cmp(nm, gena->d.directoryName))
1407                 return 1;
1408         }
1409         return 0;
1410     }
1411
1412     /* Else case 3: two GENERAL_NAMES */
1413
1414     for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1415         gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1416         for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1417             genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1418             if (!GENERAL_NAME_cmp(gena, genb))
1419                 return 1;
1420         }
1421     }
1422
1423     return 0;
1424
1425 }
1426
1427 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1428 {
1429     int i;
1430     const X509_NAME *nm = X509_CRL_get_issuer(crl);
1431     /* If no CRLissuer return is successful iff don't need a match */
1432     if (!dp->CRLissuer)
1433         return ! !(crl_score & CRL_SCORE_ISSUER_NAME);
1434     for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1435         GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1436         if (gen->type != GEN_DIRNAME)
1437             continue;
1438         if (!X509_NAME_cmp(gen->d.directoryName, nm))
1439             return 1;
1440     }
1441     return 0;
1442 }
1443
1444 /* Check CRLDP and IDP */
1445
1446 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1447                            unsigned int *preasons)
1448 {
1449     int i;
1450     if (crl->idp_flags & IDP_ONLYATTR)
1451         return 0;
1452     if (x->ex_flags & EXFLAG_CA) {
1453         if (crl->idp_flags & IDP_ONLYUSER)
1454             return 0;
1455     } else {
1456         if (crl->idp_flags & IDP_ONLYCA)
1457             return 0;
1458     }
1459     *preasons = crl->idp_reasons;
1460     for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1461         DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1462         if (crldp_check_crlissuer(dp, crl, crl_score)) {
1463             if (!crl->idp || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1464                 *preasons &= dp->dp_reasons;
1465                 return 1;
1466             }
1467         }
1468     }
1469     if ((!crl->idp || !crl->idp->distpoint)
1470         && (crl_score & CRL_SCORE_ISSUER_NAME))
1471         return 1;
1472     return 0;
1473 }
1474
1475 /*
1476  * Retrieve CRL corresponding to current certificate. If deltas enabled try
1477  * to find a delta CRL too
1478  */
1479
1480 static int get_crl_delta(X509_STORE_CTX *ctx,
1481                          X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1482 {
1483     int ok;
1484     X509 *issuer = NULL;
1485     int crl_score = 0;
1486     unsigned int reasons;
1487     X509_CRL *crl = NULL, *dcrl = NULL;
1488     STACK_OF(X509_CRL) *skcrl;
1489     const X509_NAME *nm = X509_get_issuer_name(x);
1490
1491     reasons = ctx->current_reasons;
1492     ok = get_crl_sk(ctx, &crl, &dcrl,
1493                     &issuer, &crl_score, &reasons, ctx->crls);
1494     if (ok)
1495         goto done;
1496
1497     /* Lookup CRLs from store */
1498
1499     skcrl = ctx->lookup_crls(ctx, nm);
1500
1501     /* If no CRLs found and a near match from get_crl_sk use that */
1502     if (!skcrl && crl)
1503         goto done;
1504
1505     get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1506
1507     sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1508
1509  done:
1510     /* If we got any kind of CRL use it and return success */
1511     if (crl) {
1512         ctx->current_issuer = issuer;
1513         ctx->current_crl_score = crl_score;
1514         ctx->current_reasons = reasons;
1515         *pcrl = crl;
1516         *pdcrl = dcrl;
1517         return 1;
1518     }
1519     return 0;
1520 }
1521
1522 /* Check CRL validity */
1523 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1524 {
1525     X509 *issuer = NULL;
1526     EVP_PKEY *ikey = NULL;
1527     int cnum = ctx->error_depth;
1528     int chnum = sk_X509_num(ctx->chain) - 1;
1529
1530     /* if we have an alternative CRL issuer cert use that */
1531     if (ctx->current_issuer)
1532         issuer = ctx->current_issuer;
1533     /*
1534      * Else find CRL issuer: if not last certificate then issuer is next
1535      * certificate in chain.
1536      */
1537     else if (cnum < chnum)
1538         issuer = sk_X509_value(ctx->chain, cnum + 1);
1539     else {
1540         issuer = sk_X509_value(ctx->chain, chnum);
1541         /* If not self signed, can't check signature */
1542         if (!ctx->check_issued(ctx, issuer, issuer) &&
1543             !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
1544             return 0;
1545     }
1546
1547     if (issuer == NULL)
1548         return 1;
1549
1550     /*
1551      * Skip most tests for deltas because they have already been done
1552      */
1553     if (!crl->base_crl_number) {
1554         /* Check for cRLSign bit if keyUsage present */
1555         if ((issuer->ex_flags & EXFLAG_KUSAGE) &&
1556             !(issuer->ex_kusage & KU_CRL_SIGN) &&
1557             !verify_cb_crl(ctx, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN))
1558             return 0;
1559
1560         if (!(ctx->current_crl_score & CRL_SCORE_SCOPE) &&
1561             !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
1562             return 0;
1563
1564         if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH) &&
1565             check_crl_path(ctx, ctx->current_issuer) <= 0 &&
1566             !verify_cb_crl(ctx, X509_V_ERR_CRL_PATH_VALIDATION_ERROR))
1567             return 0;
1568
1569         if ((crl->idp_flags & IDP_INVALID) &&
1570             !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
1571             return 0;
1572     }
1573
1574     if (!(ctx->current_crl_score & CRL_SCORE_TIME) &&
1575         !check_crl_time(ctx, crl, 1))
1576         return 0;
1577
1578     /* Attempt to get issuer certificate public key */
1579     ikey = X509_get0_pubkey(issuer);
1580
1581     if (!ikey &&
1582         !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1583         return 0;
1584
1585     if (ikey) {
1586         int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1587
1588         if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
1589             return 0;
1590         /* Verify CRL signature */
1591         if (X509_CRL_verify(crl, ikey) <= 0 &&
1592             !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
1593             return 0;
1594     }
1595     return 1;
1596 }
1597
1598 /* Check certificate against CRL */
1599 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1600 {
1601     X509_REVOKED *rev;
1602
1603     /*
1604      * The rules changed for this... previously if a CRL contained unhandled
1605      * critical extensions it could still be used to indicate a certificate
1606      * was revoked. This has since been changed since critical extensions can
1607      * change the meaning of CRL entries.
1608      */
1609     if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL)
1610         && (crl->flags & EXFLAG_CRITICAL) &&
1611         !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
1612         return 0;
1613     /*
1614      * Look for serial number of certificate in CRL.  If found, make sure
1615      * reason is not removeFromCRL.
1616      */
1617     if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1618         if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1619             return 2;
1620         if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
1621             return 0;
1622     }
1623
1624     return 1;
1625 }
1626
1627 static int check_policy(X509_STORE_CTX *ctx)
1628 {
1629     int ret;
1630
1631     if (ctx->parent)
1632         return 1;
1633     /*
1634      * With DANE, the trust anchor might be a bare public key, not a
1635      * certificate!  In that case our chain does not have the trust anchor
1636      * certificate as a top-most element.  This comports well with RFC5280
1637      * chain verification, since there too, the trust anchor is not part of the
1638      * chain to be verified.  In particular, X509_policy_check() does not look
1639      * at the TA cert, but assumes that it is present as the top-most chain
1640      * element.  We therefore temporarily push a NULL cert onto the chain if it
1641      * was verified via a bare public key, and pop it off right after the
1642      * X509_policy_check() call.
1643      */
1644     if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
1645         X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1646         ctx->error = X509_V_ERR_OUT_OF_MEM;
1647         return 0;
1648     }
1649     ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1650                             ctx->param->policies, ctx->param->flags);
1651     if (ctx->bare_ta_signed)
1652         sk_X509_pop(ctx->chain);
1653
1654     if (ret == X509_PCY_TREE_INTERNAL) {
1655         X509err(X509_F_CHECK_POLICY, ERR_R_MALLOC_FAILURE);
1656         ctx->error = X509_V_ERR_OUT_OF_MEM;
1657         return 0;
1658     }
1659     /* Invalid or inconsistent extensions */
1660     if (ret == X509_PCY_TREE_INVALID) {
1661         int i;
1662
1663         /* Locate certificates with bad extensions and notify callback. */
1664         for (i = 1; i < sk_X509_num(ctx->chain); i++) {
1665             X509 *x = sk_X509_value(ctx->chain, i);
1666
1667             if (!(x->ex_flags & EXFLAG_INVALID_POLICY))
1668                 continue;
1669             if (!verify_cb_cert(ctx, x, i,
1670                                 X509_V_ERR_INVALID_POLICY_EXTENSION))
1671                 return 0;
1672         }
1673         return 1;
1674     }
1675     if (ret == X509_PCY_TREE_FAILURE) {
1676         ctx->current_cert = NULL;
1677         ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1678         return ctx->verify_cb(0, ctx);
1679     }
1680     if (ret != X509_PCY_TREE_VALID) {
1681         X509err(X509_F_CHECK_POLICY, ERR_R_INTERNAL_ERROR);
1682         return 0;
1683     }
1684
1685     if (ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) {
1686         ctx->current_cert = NULL;
1687         /*
1688          * Verification errors need to be "sticky", a callback may have allowed
1689          * an SSL handshake to continue despite an error, and we must then
1690          * remain in an error state.  Therefore, we MUST NOT clear earlier
1691          * verification errors by setting the error to X509_V_OK.
1692          */
1693         if (!ctx->verify_cb(2, ctx))
1694             return 0;
1695     }
1696
1697     return 1;
1698 }
1699
1700 /*-
1701  * Check certificate validity times.
1702  * If depth >= 0, invoke verification callbacks on error, otherwise just return
1703  * the validation status.
1704  *
1705  * Return 1 on success, 0 otherwise.
1706  */
1707 int x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1708 {
1709     time_t *ptime;
1710     int i;
1711
1712     if (ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME)
1713         ptime = &ctx->param->check_time;
1714     else if (ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME)
1715         return 1;
1716     else
1717         ptime = NULL;
1718
1719     i = X509_cmp_time(X509_get0_notBefore(x), ptime);
1720     if (i >= 0 && depth < 0)
1721         return 0;
1722     if (i == 0 && !verify_cb_cert(ctx, x, depth,
1723                                   X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD))
1724         return 0;
1725     if (i > 0 && !verify_cb_cert(ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID))
1726         return 0;
1727
1728     i = X509_cmp_time(X509_get0_notAfter(x), ptime);
1729     if (i <= 0 && depth < 0)
1730         return 0;
1731     if (i == 0 && !verify_cb_cert(ctx, x, depth,
1732                                   X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD))
1733         return 0;
1734     if (i < 0 && !verify_cb_cert(ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED))
1735         return 0;
1736     return 1;
1737 }
1738
1739 static int internal_verify(X509_STORE_CTX *ctx)
1740 {
1741     int n = sk_X509_num(ctx->chain) - 1;
1742     X509 *xi = sk_X509_value(ctx->chain, n);
1743     X509 *xs;
1744
1745     /*
1746      * With DANE-verified bare public key TA signatures, it remains only to
1747      * check the timestamps of the top certificate.  We report the issuer as
1748      * NULL, since all we have is a bare key.
1749      */
1750     if (ctx->bare_ta_signed) {
1751         xs = xi;
1752         xi = NULL;
1753         goto check_cert;
1754     }
1755
1756     if (ctx->check_issued(ctx, xi, xi))
1757         xs = xi;
1758     else {
1759         if (ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) {
1760             xs = xi;
1761             goto check_cert;
1762         }
1763         if (n <= 0)
1764             return verify_cb_cert(ctx, xi, 0,
1765                                   X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1766         n--;
1767         ctx->error_depth = n;
1768         xs = sk_X509_value(ctx->chain, n);
1769     }
1770
1771     /*
1772      * Do not clear ctx->error=0, it must be "sticky", only the user's callback
1773      * is allowed to reset errors (at its own peril).
1774      */
1775     while (n >= 0) {
1776         EVP_PKEY *pkey;
1777
1778         /*
1779          * Skip signature check for self signed certificates unless explicitly
1780          * asked for.  It doesn't add any security and just wastes time.  If
1781          * the issuer's public key is unusable, report the issuer certificate
1782          * and its depth (rather than the depth of the subject).
1783          */
1784         if (xs != xi || (ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE)) {
1785             if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1786                 if (!verify_cb_cert(ctx, xi, xi != xs ? n+1 : n,
1787                         X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1788                     return 0;
1789             } else if (X509_verify_ex(xs, pkey, ctx->libctx, ctx->propq) <= 0) {
1790                 if (!verify_cb_cert(ctx, xs, n,
1791                                     X509_V_ERR_CERT_SIGNATURE_FAILURE))
1792                     return 0;
1793             }
1794         }
1795
1796  check_cert:
1797         /* Calls verify callback as needed */
1798         if (!x509_check_cert_time(ctx, xs, n))
1799             return 0;
1800
1801         /*
1802          * Signal success at this depth.  However, the previous error (if any)
1803          * is retained.
1804          */
1805         ctx->current_issuer = xi;
1806         ctx->current_cert = xs;
1807         ctx->error_depth = n;
1808         if (!ctx->verify_cb(1, ctx))
1809             return 0;
1810
1811         if (--n >= 0) {
1812             xi = xs;
1813             xs = sk_X509_value(ctx->chain, n);
1814         }
1815     }
1816     return 1;
1817 }
1818
1819 int X509_cmp_current_time(const ASN1_TIME *ctm)
1820 {
1821     return X509_cmp_time(ctm, NULL);
1822 }
1823
1824 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
1825 {
1826     static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
1827     static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
1828     ASN1_TIME *asn1_cmp_time = NULL;
1829     int i, day, sec, ret = 0;
1830 #ifdef CHARSET_EBCDIC
1831     const char upper_z = 0x5A;
1832 #else
1833     const char upper_z = 'Z';
1834 #endif
1835     /*
1836      * Note that ASN.1 allows much more slack in the time format than RFC5280.
1837      * In RFC5280, the representation is fixed:
1838      * UTCTime: YYMMDDHHMMSSZ
1839      * GeneralizedTime: YYYYMMDDHHMMSSZ
1840      *
1841      * We do NOT currently enforce the following RFC 5280 requirement:
1842      * "CAs conforming to this profile MUST always encode certificate
1843      *  validity dates through the year 2049 as UTCTime; certificate validity
1844      *  dates in 2050 or later MUST be encoded as GeneralizedTime."
1845      */
1846     switch (ctm->type) {
1847     case V_ASN1_UTCTIME:
1848         if (ctm->length != (int)(utctime_length))
1849             return 0;
1850         break;
1851     case V_ASN1_GENERALIZEDTIME:
1852         if (ctm->length != (int)(generalizedtime_length))
1853             return 0;
1854         break;
1855     default:
1856         return 0;
1857     }
1858
1859     /**
1860      * Verify the format: the ASN.1 functions we use below allow a more
1861      * flexible format than what's mandated by RFC 5280.
1862      * Digit and date ranges will be verified in the conversion methods.
1863      */
1864     for (i = 0; i < ctm->length - 1; i++) {
1865         if (!ascii_isdigit(ctm->data[i]))
1866             return 0;
1867     }
1868     if (ctm->data[ctm->length - 1] != upper_z)
1869         return 0;
1870
1871     /*
1872      * There is ASN1_UTCTIME_cmp_time_t but no
1873      * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
1874      * so we go through ASN.1
1875      */
1876     asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
1877     if (asn1_cmp_time == NULL)
1878         goto err;
1879     if (!ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time))
1880         goto err;
1881
1882     /*
1883      * X509_cmp_time comparison is <=.
1884      * The return value 0 is reserved for errors.
1885      */
1886     ret = (day >= 0 && sec >= 0) ? -1 : 1;
1887
1888  err:
1889     ASN1_TIME_free(asn1_cmp_time);
1890     return ret;
1891 }
1892
1893 /*
1894  * Return 0 if time should not be checked or reference time is in range,
1895  * or else 1 if it is past the end, or -1 if it is before the start
1896  */
1897 int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
1898                        const ASN1_TIME *start, const ASN1_TIME *end)
1899 {
1900     time_t ref_time;
1901     time_t *time = NULL;
1902     unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
1903
1904     if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
1905         ref_time = X509_VERIFY_PARAM_get_time(vpm);
1906         time = &ref_time;
1907     } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
1908         return 0; /* this means ok */
1909     } /* else reference time is the current time */
1910
1911     if (end != NULL && X509_cmp_time(end, time) < 0)
1912         return 1;
1913     if (start != NULL && X509_cmp_time(start, time) > 0)
1914         return -1;
1915     return 0;
1916 }
1917
1918 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
1919 {
1920     return X509_time_adj(s, adj, NULL);
1921 }
1922
1923 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
1924 {
1925     return X509_time_adj_ex(s, 0, offset_sec, in_tm);
1926 }
1927
1928 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
1929                             int offset_day, long offset_sec, time_t *in_tm)
1930 {
1931     time_t t;
1932
1933     if (in_tm)
1934         t = *in_tm;
1935     else
1936         time(&t);
1937
1938     if (s && !(s->flags & ASN1_STRING_FLAG_MSTRING)) {
1939         if (s->type == V_ASN1_UTCTIME)
1940             return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
1941         if (s->type == V_ASN1_GENERALIZEDTIME)
1942             return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
1943     }
1944     return ASN1_TIME_adj(s, t, offset_day, offset_sec);
1945 }
1946
1947 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
1948 {
1949     EVP_PKEY *ktmp = NULL, *ktmp2;
1950     int i, j;
1951
1952     if ((pkey != NULL) && !EVP_PKEY_missing_parameters(pkey))
1953         return 1;
1954
1955     for (i = 0; i < sk_X509_num(chain); i++) {
1956         ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
1957         if (ktmp == NULL) {
1958             X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1959                     X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
1960             return 0;
1961         }
1962         if (!EVP_PKEY_missing_parameters(ktmp))
1963             break;
1964     }
1965     if (ktmp == NULL) {
1966         X509err(X509_F_X509_GET_PUBKEY_PARAMETERS,
1967                 X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
1968         return 0;
1969     }
1970
1971     /* first, populate the other certs */
1972     for (j = i - 1; j >= 0; j--) {
1973         ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
1974         EVP_PKEY_copy_parameters(ktmp2, ktmp);
1975     }
1976
1977     if (pkey != NULL)
1978         EVP_PKEY_copy_parameters(pkey, ktmp);
1979     return 1;
1980 }
1981
1982 /* Make a delta CRL as the diff between two full CRLs */
1983
1984 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
1985                         EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
1986 {
1987     X509_CRL *crl = NULL;
1988     int i;
1989     STACK_OF(X509_REVOKED) *revs = NULL;
1990     /* CRLs can't be delta already */
1991     if (base->base_crl_number || newer->base_crl_number) {
1992         X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA);
1993         return NULL;
1994     }
1995     /* Base and new CRL must have a CRL number */
1996     if (!base->crl_number || !newer->crl_number) {
1997         X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER);
1998         return NULL;
1999     }
2000     /* Issuer names must match */
2001     if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) {
2002         X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH);
2003         return NULL;
2004     }
2005     /* AKID and IDP must match */
2006     if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
2007         X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH);
2008         return NULL;
2009     }
2010     if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
2011         X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH);
2012         return NULL;
2013     }
2014     /* Newer CRL number must exceed full CRL number */
2015     if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
2016         X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER);
2017         return NULL;
2018     }
2019     /* CRLs must verify */
2020     if (skey && (X509_CRL_verify(base, skey) <= 0 ||
2021                  X509_CRL_verify(newer, skey) <= 0)) {
2022         X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE);
2023         return NULL;
2024     }
2025     /* Create new CRL */
2026     crl = X509_CRL_new();
2027     if (crl == NULL || !X509_CRL_set_version(crl, 1))
2028         goto memerr;
2029     /* Set issuer name */
2030     if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer)))
2031         goto memerr;
2032
2033     if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer)))
2034         goto memerr;
2035     if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer)))
2036         goto memerr;
2037
2038     /* Set base CRL number: must be critical */
2039
2040     if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0))
2041         goto memerr;
2042
2043     /*
2044      * Copy extensions across from newest CRL to delta: this will set CRL
2045      * number to correct value too.
2046      */
2047
2048     for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2049         X509_EXTENSION *ext;
2050         ext = X509_CRL_get_ext(newer, i);
2051         if (!X509_CRL_add_ext(crl, ext, -1))
2052             goto memerr;
2053     }
2054
2055     /* Go through revoked entries, copying as needed */
2056
2057     revs = X509_CRL_get_REVOKED(newer);
2058
2059     for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2060         X509_REVOKED *rvn, *rvtmp;
2061         rvn = sk_X509_REVOKED_value(revs, i);
2062         /*
2063          * Add only if not also in base. TODO: need something cleverer here
2064          * for some more complex CRLs covering multiple CAs.
2065          */
2066         if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2067             rvtmp = X509_REVOKED_dup(rvn);
2068             if (!rvtmp)
2069                 goto memerr;
2070             if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2071                 X509_REVOKED_free(rvtmp);
2072                 goto memerr;
2073             }
2074         }
2075     }
2076     /* TODO: optionally prune deleted entries */
2077
2078     if (skey && md && !X509_CRL_sign(crl, skey, md))
2079         goto memerr;
2080
2081     return crl;
2082
2083  memerr:
2084     X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE);
2085     X509_CRL_free(crl);
2086     return NULL;
2087 }
2088
2089 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2090 {
2091     return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2092 }
2093
2094 void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2095 {
2096     return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2097 }
2098
2099 int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2100 {
2101     return ctx->error;
2102 }
2103
2104 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2105 {
2106     ctx->error = err;
2107 }
2108
2109 int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2110 {
2111     return ctx->error_depth;
2112 }
2113
2114 void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2115 {
2116     ctx->error_depth = depth;
2117 }
2118
2119 X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2120 {
2121     return ctx->current_cert;
2122 }
2123
2124 void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2125 {
2126     ctx->current_cert = x;
2127 }
2128
2129 STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2130 {
2131     return ctx->chain;
2132 }
2133
2134 STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2135 {
2136     if (!ctx->chain)
2137         return NULL;
2138     return X509_chain_up_ref(ctx->chain);
2139 }
2140
2141 X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2142 {
2143     return ctx->current_issuer;
2144 }
2145
2146 X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2147 {
2148     return ctx->current_crl;
2149 }
2150
2151 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2152 {
2153     return ctx->parent;
2154 }
2155
2156 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2157 {
2158     ctx->cert = x;
2159 }
2160
2161 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2162 {
2163     ctx->crls = sk;
2164 }
2165
2166 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2167 {
2168     /*
2169      * XXX: Why isn't this function always used to set the associated trust?
2170      * Should there even be a VPM->trust field at all?  Or should the trust
2171      * always be inferred from the purpose by X509_STORE_CTX_init().
2172      */
2173     return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2174 }
2175
2176 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2177 {
2178     /*
2179      * XXX: See above, this function would only be needed when the default
2180      * trust for the purpose needs an override in a corner case.
2181      */
2182     return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2183 }
2184
2185 /*
2186  * This function is used to set the X509_STORE_CTX purpose and trust values.
2187  * This is intended to be used when another structure has its own trust and
2188  * purpose values which (if set) will be inherited by the ctx. If they aren't
2189  * set then we will usually have a default purpose in mind which should then
2190  * be used to set the trust value. An example of this is SSL use: an SSL
2191  * structure will have its own purpose and trust settings which the
2192  * application can set: if they aren't set then we use the default of SSL
2193  * client/server.
2194  */
2195
2196 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2197                                    int purpose, int trust)
2198 {
2199     int idx;
2200     /* If purpose not set use default */
2201     if (purpose == 0)
2202         purpose = def_purpose;
2203     /* If we have a purpose then check it is valid */
2204     if (purpose != 0) {
2205         X509_PURPOSE *ptmp;
2206         idx = X509_PURPOSE_get_by_id(purpose);
2207         if (idx == -1) {
2208             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2209                     X509_R_UNKNOWN_PURPOSE_ID);
2210             return 0;
2211         }
2212         ptmp = X509_PURPOSE_get0(idx);
2213         if (ptmp->trust == X509_TRUST_DEFAULT) {
2214             idx = X509_PURPOSE_get_by_id(def_purpose);
2215             /*
2216              * XXX: In the two callers above def_purpose is always 0, which is
2217              * not a known value, so idx will always be -1.  How is the
2218              * X509_TRUST_DEFAULT case actually supposed to be handled?
2219              */
2220             if (idx == -1) {
2221                 X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2222                         X509_R_UNKNOWN_PURPOSE_ID);
2223                 return 0;
2224             }
2225             ptmp = X509_PURPOSE_get0(idx);
2226         }
2227         /* If trust not set then get from purpose default */
2228         if (!trust)
2229             trust = ptmp->trust;
2230     }
2231     if (trust) {
2232         idx = X509_TRUST_get_by_id(trust);
2233         if (idx == -1) {
2234             X509err(X509_F_X509_STORE_CTX_PURPOSE_INHERIT,
2235                     X509_R_UNKNOWN_TRUST_ID);
2236             return 0;
2237         }
2238     }
2239
2240     if (purpose && !ctx->param->purpose)
2241         ctx->param->purpose = purpose;
2242     if (trust && !ctx->param->trust)
2243         ctx->param->trust = trust;
2244     return 1;
2245 }
2246
2247 X509_STORE_CTX *X509_STORE_CTX_new_with_libctx(OPENSSL_CTX *libctx,
2248                                                const char *propq)
2249 {
2250     X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2251
2252     if (ctx == NULL) {
2253         X509err(0, ERR_R_MALLOC_FAILURE);
2254         return NULL;
2255     }
2256
2257     ctx->libctx = libctx;
2258     if (propq != NULL) {
2259         ctx->propq = OPENSSL_strdup(propq);
2260         if (ctx->propq == NULL) {
2261             OPENSSL_free(ctx);
2262             X509err(0, ERR_R_MALLOC_FAILURE);
2263             return NULL;
2264         }
2265     }
2266
2267     return ctx;
2268 }
2269
2270 X509_STORE_CTX *X509_STORE_CTX_new(void)
2271 {
2272     return X509_STORE_CTX_new_with_libctx(NULL, NULL);
2273 }
2274
2275
2276 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2277 {
2278     if (ctx == NULL)
2279         return;
2280
2281     X509_STORE_CTX_cleanup(ctx);
2282
2283     /* libctx and propq survive X509_STORE_CTX_cleanup() */
2284     OPENSSL_free(ctx->propq);
2285
2286     OPENSSL_free(ctx);
2287 }
2288
2289 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2290                         STACK_OF(X509) *chain)
2291 {
2292     int ret = 1;
2293
2294     ctx->store = store;
2295     ctx->cert = x509;
2296     ctx->untrusted = chain;
2297     ctx->crls = NULL;
2298     ctx->num_untrusted = 0;
2299     ctx->other_ctx = NULL;
2300     ctx->valid = 0;
2301     ctx->chain = NULL;
2302     ctx->error = 0;
2303     ctx->explicit_policy = 0;
2304     ctx->error_depth = 0;
2305     ctx->current_cert = NULL;
2306     ctx->current_issuer = NULL;
2307     ctx->current_crl = NULL;
2308     ctx->current_crl_score = 0;
2309     ctx->current_reasons = 0;
2310     ctx->tree = NULL;
2311     ctx->parent = NULL;
2312     ctx->dane = NULL;
2313     ctx->bare_ta_signed = 0;
2314     /* Zero ex_data to make sure we're cleanup-safe */
2315     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2316
2317     /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2318     if (store)
2319         ctx->cleanup = store->cleanup;
2320     else
2321         ctx->cleanup = 0;
2322
2323     if (store && store->check_issued)
2324         ctx->check_issued = store->check_issued;
2325     else
2326         ctx->check_issued = check_issued;
2327
2328     if (store && store->get_issuer)
2329         ctx->get_issuer = store->get_issuer;
2330     else
2331         ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2332
2333     if (store && store->verify_cb)
2334         ctx->verify_cb = store->verify_cb;
2335     else
2336         ctx->verify_cb = null_callback;
2337
2338     if (store && store->verify)
2339         ctx->verify = store->verify;
2340     else
2341         ctx->verify = internal_verify;
2342
2343     if (store && store->check_revocation)
2344         ctx->check_revocation = store->check_revocation;
2345     else
2346         ctx->check_revocation = check_revocation;
2347
2348     if (store && store->get_crl)
2349         ctx->get_crl = store->get_crl;
2350     else
2351         ctx->get_crl = NULL;
2352
2353     if (store && store->check_crl)
2354         ctx->check_crl = store->check_crl;
2355     else
2356         ctx->check_crl = check_crl;
2357
2358     if (store && store->cert_crl)
2359         ctx->cert_crl = store->cert_crl;
2360     else
2361         ctx->cert_crl = cert_crl;
2362
2363     if (store && store->check_policy)
2364         ctx->check_policy = store->check_policy;
2365     else
2366         ctx->check_policy = check_policy;
2367
2368     if (store && store->lookup_certs)
2369         ctx->lookup_certs = store->lookup_certs;
2370     else
2371         ctx->lookup_certs = X509_STORE_CTX_get1_certs;
2372
2373     if (store && store->lookup_crls)
2374         ctx->lookup_crls = store->lookup_crls;
2375     else
2376         ctx->lookup_crls = X509_STORE_CTX_get1_crls;
2377
2378     ctx->param = X509_VERIFY_PARAM_new();
2379     if (ctx->param == NULL) {
2380         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2381         goto err;
2382     }
2383
2384     /*
2385      * Inherit callbacks and flags from X509_STORE if not set use defaults.
2386      */
2387     if (store)
2388         ret = X509_VERIFY_PARAM_inherit(ctx->param, store->param);
2389     else
2390         ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2391
2392     if (ret)
2393         ret = X509_VERIFY_PARAM_inherit(ctx->param,
2394                                         X509_VERIFY_PARAM_lookup("default"));
2395
2396     if (ret == 0) {
2397         X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2398         goto err;
2399     }
2400
2401     /*
2402      * XXX: For now, continue to inherit trust from VPM, but infer from the
2403      * purpose if this still yields the default value.
2404      */
2405     if (ctx->param->trust == X509_TRUST_DEFAULT) {
2406         int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2407         X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2408
2409         if (xp != NULL)
2410             ctx->param->trust = X509_PURPOSE_get_trust(xp);
2411     }
2412
2413     if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2414                            &ctx->ex_data))
2415         return 1;
2416     X509err(X509_F_X509_STORE_CTX_INIT, ERR_R_MALLOC_FAILURE);
2417
2418  err:
2419     /*
2420      * On error clean up allocated storage, if the store context was not
2421      * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2422      */
2423     X509_STORE_CTX_cleanup(ctx);
2424     return 0;
2425 }
2426
2427 /*
2428  * Set alternative lookup method: just a STACK of trusted certificates. This
2429  * avoids X509_STORE nastiness where it isn't needed.
2430  */
2431 void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2432 {
2433     ctx->other_ctx = sk;
2434     ctx->get_issuer = get_issuer_sk;
2435     ctx->lookup_certs = lookup_certs_sk;
2436 }
2437
2438 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2439 {
2440     /*
2441      * We need to be idempotent because, unfortunately, free() also calls
2442      * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2443      * calls cleanup() for the same object twice!  Thus we must zero the
2444      * pointers below after they're freed!
2445      */
2446     /* Seems to always be 0 in OpenSSL, do this at most once. */
2447     if (ctx->cleanup != NULL) {
2448         ctx->cleanup(ctx);
2449         ctx->cleanup = NULL;
2450     }
2451     if (ctx->param != NULL) {
2452         if (ctx->parent == NULL)
2453             X509_VERIFY_PARAM_free(ctx->param);
2454         ctx->param = NULL;
2455     }
2456     X509_policy_tree_free(ctx->tree);
2457     ctx->tree = NULL;
2458     sk_X509_pop_free(ctx->chain, X509_free);
2459     ctx->chain = NULL;
2460     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2461     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2462 }
2463
2464 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2465 {
2466     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2467 }
2468
2469 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2470 {
2471     X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2472 }
2473
2474 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2475                              time_t t)
2476 {
2477     X509_VERIFY_PARAM_set_time(ctx->param, t);
2478 }
2479
2480 X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
2481 {
2482     return ctx->cert;
2483 }
2484
2485 STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
2486 {
2487     return ctx->untrusted;
2488 }
2489
2490 void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2491 {
2492     ctx->untrusted = sk;
2493 }
2494
2495 void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2496 {
2497     sk_X509_pop_free(ctx->chain, X509_free);
2498     ctx->chain = sk;
2499 }
2500
2501 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2502                                   X509_STORE_CTX_verify_cb verify_cb)
2503 {
2504     ctx->verify_cb = verify_cb;
2505 }
2506
2507 X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
2508 {
2509     return ctx->verify_cb;
2510 }
2511
2512 void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
2513                                X509_STORE_CTX_verify_fn verify)
2514 {
2515     ctx->verify = verify;
2516 }
2517
2518 X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
2519 {
2520     return ctx->verify;
2521 }
2522
2523 X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
2524 {
2525     return ctx->get_issuer;
2526 }
2527
2528 X509_STORE_CTX_check_issued_fn
2529    X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
2530 {
2531     return ctx->check_issued;
2532 }
2533
2534 X509_STORE_CTX_check_revocation_fn
2535     X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
2536 {
2537     return ctx->check_revocation;
2538 }
2539
2540 X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
2541 {
2542     return ctx->get_crl;
2543 }
2544
2545 X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
2546 {
2547     return ctx->check_crl;
2548 }
2549
2550 X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
2551 {
2552     return ctx->cert_crl;
2553 }
2554
2555 X509_STORE_CTX_check_policy_fn
2556     X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
2557 {
2558     return ctx->check_policy;
2559 }
2560
2561 X509_STORE_CTX_lookup_certs_fn
2562     X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
2563 {
2564     return ctx->lookup_certs;
2565 }
2566
2567 X509_STORE_CTX_lookup_crls_fn
2568     X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
2569 {
2570     return ctx->lookup_crls;
2571 }
2572
2573 X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
2574 {
2575     return ctx->cleanup;
2576 }
2577
2578 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
2579 {
2580     return ctx->tree;
2581 }
2582
2583 int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
2584 {
2585     return ctx->explicit_policy;
2586 }
2587
2588 int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
2589 {
2590     return ctx->num_untrusted;
2591 }
2592
2593 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2594 {
2595     const X509_VERIFY_PARAM *param;
2596
2597     param = X509_VERIFY_PARAM_lookup(name);
2598     if (param == NULL)
2599         return 0;
2600     return X509_VERIFY_PARAM_inherit(ctx->param, param);
2601 }
2602
2603 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
2604 {
2605     return ctx->param;
2606 }
2607
2608 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2609 {
2610     X509_VERIFY_PARAM_free(ctx->param);
2611     ctx->param = param;
2612 }
2613
2614 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
2615 {
2616     ctx->dane = dane;
2617 }
2618
2619 static unsigned char *dane_i2d(
2620     X509 *cert,
2621     uint8_t selector,
2622     unsigned int *i2dlen)
2623 {
2624     unsigned char *buf = NULL;
2625     int len;
2626
2627     /*
2628      * Extract ASN.1 DER form of certificate or public key.
2629      */
2630     switch (selector) {
2631     case DANETLS_SELECTOR_CERT:
2632         len = i2d_X509(cert, &buf);
2633         break;
2634     case DANETLS_SELECTOR_SPKI:
2635         len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2636         break;
2637     default:
2638         X509err(X509_F_DANE_I2D, X509_R_BAD_SELECTOR);
2639         return NULL;
2640     }
2641
2642     if (len < 0 || buf == NULL) {
2643         X509err(X509_F_DANE_I2D, ERR_R_MALLOC_FAILURE);
2644         return NULL;
2645     }
2646
2647     *i2dlen = (unsigned int)len;
2648     return buf;
2649 }
2650
2651 #define DANETLS_NONE 256        /* impossible uint8_t */
2652
2653 static int dane_match(X509_STORE_CTX *ctx, X509 *cert, int depth)
2654 {
2655     SSL_DANE *dane = ctx->dane;
2656     unsigned usage = DANETLS_NONE;
2657     unsigned selector = DANETLS_NONE;
2658     unsigned ordinal = DANETLS_NONE;
2659     unsigned mtype = DANETLS_NONE;
2660     unsigned char *i2dbuf = NULL;
2661     unsigned int i2dlen = 0;
2662     unsigned char mdbuf[EVP_MAX_MD_SIZE];
2663     unsigned char *cmpbuf = NULL;
2664     unsigned int cmplen = 0;
2665     int i;
2666     int recnum;
2667     int matched = 0;
2668     danetls_record *t = NULL;
2669     uint32_t mask;
2670
2671     mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2672
2673     /*
2674      * The trust store is not applicable with DANE-TA(2)
2675      */
2676     if (depth >= ctx->num_untrusted)
2677         mask &= DANETLS_PKIX_MASK;
2678
2679     /*
2680      * If we've previously matched a PKIX-?? record, no need to test any
2681      * further PKIX-?? records, it remains to just build the PKIX chain.
2682      * Had the match been a DANE-?? record, we'd be done already.
2683      */
2684     if (dane->mdpth >= 0)
2685         mask &= ~DANETLS_PKIX_MASK;
2686
2687     /*-
2688      * https://tools.ietf.org/html/rfc7671#section-5.1
2689      * https://tools.ietf.org/html/rfc7671#section-5.2
2690      * https://tools.ietf.org/html/rfc7671#section-5.3
2691      * https://tools.ietf.org/html/rfc7671#section-5.4
2692      *
2693      * We handle DANE-EE(3) records first as they require no chain building
2694      * and no expiration or hostname checks.  We also process digests with
2695      * higher ordinals first and ignore lower priorities except Full(0) which
2696      * is always processed (last).  If none match, we then process PKIX-EE(1).
2697      *
2698      * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2699      * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2700      * priorities.  See twin comment in ssl/ssl_lib.c.
2701      *
2702      * We expect that most TLSA RRsets will have just a single usage, so we
2703      * don't go out of our way to cache multiple selector-specific i2d buffers
2704      * across usages, but if the selector happens to remain the same as switch
2705      * usages, that's OK.  Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2706      * records would result in us generating each of the certificate and public
2707      * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2708      * or multiple "3 0 1" records.
2709      *
2710      * As soon as we find a match at any given depth, we stop, because either
2711      * we've matched a DANE-?? record and the peer is authenticated, or, after
2712      * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
2713      * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2714      */
2715     recnum = (dane->umask & mask) ? sk_danetls_record_num(dane->trecs) : 0;
2716     for (i = 0; matched == 0 && i < recnum; ++i) {
2717         t = sk_danetls_record_value(dane->trecs, i);
2718         if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2719             continue;
2720         if (t->usage != usage) {
2721             usage = t->usage;
2722
2723             /* Reset digest agility for each usage/selector pair */
2724             mtype = DANETLS_NONE;
2725             ordinal = dane->dctx->mdord[t->mtype];
2726         }
2727         if (t->selector != selector) {
2728             selector = t->selector;
2729
2730             /* Update per-selector state */
2731             OPENSSL_free(i2dbuf);
2732             i2dbuf = dane_i2d(cert, selector, &i2dlen);
2733             if (i2dbuf == NULL)
2734                 return -1;
2735
2736             /* Reset digest agility for each usage/selector pair */
2737             mtype = DANETLS_NONE;
2738             ordinal = dane->dctx->mdord[t->mtype];
2739         } else if (t->mtype != DANETLS_MATCHING_FULL) {
2740             /*-
2741              * Digest agility:
2742              *
2743              *     <https://tools.ietf.org/html/rfc7671#section-9>
2744              *
2745              * For a fixed selector, after processing all records with the
2746              * highest mtype ordinal, ignore all mtypes with lower ordinals
2747              * other than "Full".
2748              */
2749             if (dane->dctx->mdord[t->mtype] < ordinal)
2750                 continue;
2751         }
2752
2753         /*
2754          * Each time we hit a (new selector or) mtype, re-compute the relevant
2755          * digest, more complex caching is not worth the code space.
2756          */
2757         if (t->mtype != mtype) {
2758             const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2759             cmpbuf = i2dbuf;
2760             cmplen = i2dlen;
2761
2762             if (md != NULL) {
2763                 cmpbuf = mdbuf;
2764                 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2765                     matched = -1;
2766                     break;
2767                 }
2768             }
2769         }
2770
2771         /*
2772          * Squirrel away the certificate and depth if we have a match.  Any
2773          * DANE match is dispositive, but with PKIX we still need to build a
2774          * full chain.
2775          */
2776         if (cmplen == t->dlen &&
2777             memcmp(cmpbuf, t->data, cmplen) == 0) {
2778             if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
2779                 matched = 1;
2780             if (matched || dane->mdpth < 0) {
2781                 dane->mdpth = depth;
2782                 dane->mtlsa = t;
2783                 OPENSSL_free(dane->mcert);
2784                 dane->mcert = cert;
2785                 X509_up_ref(cert);
2786             }
2787             break;
2788         }
2789     }
2790
2791     /* Clear the one-element DER cache */
2792     OPENSSL_free(i2dbuf);
2793     return matched;
2794 }
2795
2796 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
2797 {
2798     SSL_DANE *dane = ctx->dane;
2799     int matched = 0;
2800     X509 *cert;
2801
2802     if (!DANETLS_HAS_TA(dane) || depth == 0)
2803         return  X509_TRUST_UNTRUSTED;
2804
2805     /*
2806      * Record any DANE trust-anchor matches, for the first depth to test, if
2807      * there's one at that depth. (This'll be false for length 1 chains looking
2808      * for an exact match for the leaf certificate).
2809      */
2810     cert = sk_X509_value(ctx->chain, depth);
2811     if (cert != NULL && (matched = dane_match(ctx, cert, depth)) < 0)
2812         return  X509_TRUST_REJECTED;
2813     if (matched > 0) {
2814         ctx->num_untrusted = depth - 1;
2815         return  X509_TRUST_TRUSTED;
2816     }
2817
2818     return  X509_TRUST_UNTRUSTED;
2819 }
2820
2821 static int check_dane_pkeys(X509_STORE_CTX *ctx)
2822 {
2823     SSL_DANE *dane = ctx->dane;
2824     danetls_record *t;
2825     int num = ctx->num_untrusted;
2826     X509 *cert = sk_X509_value(ctx->chain, num - 1);
2827     int recnum = sk_danetls_record_num(dane->trecs);
2828     int i;
2829
2830     for (i = 0; i < recnum; ++i) {
2831         t = sk_danetls_record_value(dane->trecs, i);
2832         if (t->usage != DANETLS_USAGE_DANE_TA ||
2833             t->selector != DANETLS_SELECTOR_SPKI ||
2834             t->mtype != DANETLS_MATCHING_FULL ||
2835             X509_verify_ex(cert, t->spki, ctx->libctx, ctx->propq) <= 0)
2836             continue;
2837
2838         /* Clear any PKIX-?? matches that failed to extend to a full chain */
2839         X509_free(dane->mcert);
2840         dane->mcert = NULL;
2841
2842         /* Record match via a bare TA public key */
2843         ctx->bare_ta_signed = 1;
2844         dane->mdpth = num - 1;
2845         dane->mtlsa = t;
2846
2847         /* Prune any excess chain certificates */
2848         num = sk_X509_num(ctx->chain);
2849         for (; num > ctx->num_untrusted; --num)
2850             X509_free(sk_X509_pop(ctx->chain));
2851
2852         return X509_TRUST_TRUSTED;
2853     }
2854
2855     return X509_TRUST_UNTRUSTED;
2856 }
2857
2858 static void dane_reset(SSL_DANE *dane)
2859 {
2860     /*
2861      * Reset state to verify another chain, or clear after failure.
2862      */
2863     X509_free(dane->mcert);
2864     dane->mcert = NULL;
2865     dane->mtlsa = NULL;
2866     dane->mdpth = -1;
2867     dane->pdpth = -1;
2868 }
2869
2870 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
2871 {
2872     int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
2873
2874     if (err == X509_V_OK)
2875         return 1;
2876     return verify_cb_cert(ctx, cert, 0, err);
2877 }
2878
2879 static int dane_verify(X509_STORE_CTX *ctx)
2880 {
2881     X509 *cert = ctx->cert;
2882     SSL_DANE *dane = ctx->dane;
2883     int matched;
2884     int done;
2885
2886     dane_reset(dane);
2887
2888     /*-
2889      * When testing the leaf certificate, if we match a DANE-EE(3) record,
2890      * dane_match() returns 1 and we're done.  If however we match a PKIX-EE(1)
2891      * record, the match depth and matching TLSA record are recorded, but the
2892      * return value is 0, because we still need to find a PKIX trust-anchor.
2893      * Therefore, when DANE authentication is enabled (required), we're done
2894      * if:
2895      *   + matched < 0, internal error.
2896      *   + matched == 1, we matched a DANE-EE(3) record
2897      *   + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
2898      *     DANE-TA(2) or PKIX-TA(0) to test.
2899      */
2900     matched = dane_match(ctx, ctx->cert, 0);
2901     done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
2902
2903     if (done)
2904         X509_get_pubkey_parameters(NULL, ctx->chain);
2905
2906     if (matched > 0) {
2907         /* Callback invoked as needed */
2908         if (!check_leaf_suiteb(ctx, cert))
2909             return 0;
2910         /* Callback invoked as needed */
2911         if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 &&
2912             !check_id(ctx))
2913             return 0;
2914         /* Bypass internal_verify(), issue depth 0 success callback */
2915         ctx->error_depth = 0;
2916         ctx->current_cert = cert;
2917         return ctx->verify_cb(1, ctx);
2918     }
2919
2920     if (matched < 0) {
2921         ctx->error_depth = 0;
2922         ctx->current_cert = cert;
2923         ctx->error = X509_V_ERR_OUT_OF_MEM;
2924         return -1;
2925     }
2926
2927     if (done) {
2928         /* Fail early, TA-based success is not possible */
2929         if (!check_leaf_suiteb(ctx, cert))
2930             return 0;
2931         return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
2932     }
2933
2934     /*
2935      * Chain verification for usages 0/1/2.  TLSA record matching of depth > 0
2936      * certificates happens in-line with building the rest of the chain.
2937      */
2938     return verify_chain(ctx);
2939 }
2940
2941 /* Get issuer, without duplicate suppression */
2942 static int get_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
2943 {
2944     STACK_OF(X509) *saved_chain = ctx->chain;
2945     int ok;
2946
2947     ctx->chain = NULL;
2948     ok = ctx->get_issuer(issuer, ctx, cert);
2949     ctx->chain = saved_chain;
2950
2951     return ok;
2952 }
2953
2954 static int build_chain(X509_STORE_CTX *ctx)
2955 {
2956     SSL_DANE *dane = ctx->dane;
2957     int num = sk_X509_num(ctx->chain);
2958     X509 *cert = sk_X509_value(ctx->chain, num - 1);
2959     int ss;
2960     STACK_OF(X509) *sktmp = NULL;
2961     unsigned int search;
2962     int may_trusted = 0;
2963     int may_alternate = 0;
2964     int trust = X509_TRUST_UNTRUSTED;
2965     int alt_untrusted = 0;
2966     int depth;
2967     int ok = 0;
2968     int i;
2969
2970     /* Our chain starts with a single untrusted element. */
2971     if (!ossl_assert(num == 1 && ctx->num_untrusted == num))  {
2972         X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
2973         ctx->error = X509_V_ERR_UNSPECIFIED;
2974         return 0;
2975     }
2976
2977     ss = cert_self_signed(ctx, cert);
2978     if (ss < 0) {
2979         X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
2980         ctx->error = X509_V_ERR_UNSPECIFIED;
2981         return 0;
2982     }
2983
2984 #define S_DOUNTRUSTED      (1 << 0)     /* Search untrusted chain */
2985 #define S_DOTRUSTED        (1 << 1)     /* Search trusted store */
2986 #define S_DOALTERNATE      (1 << 2)     /* Retry with pruned alternate chain */
2987     /*
2988      * Set up search policy, untrusted if possible, trusted-first if enabled.
2989      * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
2990      * trust_store, otherwise we might look there first.  If not trusted-first,
2991      * and alternate chains are not disabled, try building an alternate chain
2992      * if no luck with untrusted first.
2993      */
2994     search = (ctx->untrusted != NULL) ? S_DOUNTRUSTED : 0;
2995     if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
2996         if (search == 0 || ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST)
2997             search |= S_DOTRUSTED;
2998         else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
2999             may_alternate = 1;
3000         may_trusted = 1;
3001     }
3002
3003     /*
3004      * Shallow-copy the stack of untrusted certificates (with TLS, this is
3005      * typically the content of the peer's certificate message) so can make
3006      * multiple passes over it, while free to remove elements as we go.
3007      */
3008     if (ctx->untrusted && (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
3009         X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3010         ctx->error = X509_V_ERR_OUT_OF_MEM;
3011         return 0;
3012     }
3013
3014     /*
3015      * If we got any "DANE-TA(2) Cert(0) Full(0)" trust-anchors from DNS, add
3016      * them to our working copy of the untrusted certificate stack.  Since the
3017      * caller of X509_STORE_CTX_init() may have provided only a leaf cert with
3018      * no corresponding stack of untrusted certificates, we may need to create
3019      * an empty stack first.  [ At present only the ssl library provides DANE
3020      * support, and ssl_verify_cert_chain() always provides a non-null stack
3021      * containing at least the leaf certificate, but we must be prepared for
3022      * this to change. ]
3023      */
3024     if (DANETLS_ENABLED(dane) && dane->certs != NULL) {
3025         if (sktmp == NULL && (sktmp = sk_X509_new_null()) == NULL) {
3026             X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3027             ctx->error = X509_V_ERR_OUT_OF_MEM;
3028             return 0;
3029         }
3030         for (i = 0; i < sk_X509_num(dane->certs); ++i) {
3031             if (!sk_X509_push(sktmp, sk_X509_value(dane->certs, i))) {
3032                 sk_X509_free(sktmp);
3033                 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3034                 ctx->error = X509_V_ERR_OUT_OF_MEM;
3035                 return 0;
3036             }
3037         }
3038     }
3039
3040     /*
3041      * Still absurdly large, but arithmetically safe, a lower hard upper bound
3042      * might be reasonable.
3043      */
3044     if (ctx->param->depth > INT_MAX/2)
3045         ctx->param->depth = INT_MAX/2;
3046
3047     /*
3048      * Try to Extend the chain until we reach an ultimately trusted issuer.
3049      * Build chains up to one longer the limit, later fail if we hit the limit,
3050      * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3051      */
3052     depth = ctx->param->depth + 1;
3053
3054     while (search != 0) {
3055         X509 *x;
3056         X509 *xtmp = NULL;
3057
3058         /*
3059          * Look in the trust store if enabled for first lookup, or we've run
3060          * out of untrusted issuers and search here is not disabled.  When we
3061          * reach the depth limit, we stop extending the chain, if by that point
3062          * we've not found a trust-anchor, any trusted chain would be too long.
3063          *
3064          * The error reported to the application verify callback is at the
3065          * maximal valid depth with the current certificate equal to the last
3066          * not ultimately-trusted issuer.  For example, with verify_depth = 0,
3067          * the callback will report errors at depth=1 when the immediate issuer
3068          * of the leaf certificate is not a trust anchor.  No attempt will be
3069          * made to locate an issuer for that certificate, since such a chain
3070          * would be a-priori too long.
3071          */
3072         if ((search & S_DOTRUSTED) != 0) {
3073             i = num = sk_X509_num(ctx->chain);
3074             if ((search & S_DOALTERNATE) != 0) {
3075                 /*
3076                  * As high up the chain as we can, look for an alternative
3077                  * trusted issuer of an untrusted certificate that currently
3078                  * has an untrusted issuer.  We use the alt_untrusted variable
3079                  * to track how far up the chain we find the first match.  It
3080                  * is only if and when we find a match, that we prune the chain
3081                  * and reset ctx->num_untrusted to the reduced count of
3082                  * untrusted certificates.  While we're searching for such a
3083                  * match (which may never be found), it is neither safe nor
3084                  * wise to preemptively modify either the chain or
3085                  * ctx->num_untrusted.
3086                  *
3087                  * Note, like ctx->num_untrusted, alt_untrusted is a count of
3088                  * untrusted certificates, not a "depth".
3089                  */
3090                 i = alt_untrusted;
3091             }
3092             x = sk_X509_value(ctx->chain, i-1);
3093
3094             ok = (depth < num) ? 0 : get_issuer(&xtmp, ctx, x);
3095
3096             if (ok < 0) {
3097                 trust = X509_TRUST_REJECTED;
3098                 ctx->error = X509_V_ERR_STORE_LOOKUP;
3099                 search = 0;
3100                 continue;
3101             }
3102
3103             if (ok > 0) {
3104                 /*
3105                  * Alternative trusted issuer for a mid-chain untrusted cert?
3106                  * Pop the untrusted cert's successors and retry.  We might now
3107                  * be able to complete a valid chain via the trust store.  Note
3108                  * that despite the current trust-store match we might still
3109                  * fail complete the chain to a suitable trust-anchor, in which
3110                  * case we may prune some more untrusted certificates and try
3111                  * again.  Thus the S_DOALTERNATE bit may yet be turned on
3112                  * again with an even shorter untrusted chain!
3113                  *
3114                  * If in the process we threw away our matching PKIX-TA trust
3115                  * anchor, reset DANE trust.  We might find a suitable trusted
3116                  * certificate among the ones from the trust store.
3117                  */
3118                 if ((search & S_DOALTERNATE) != 0) {
3119                     if (!ossl_assert(num > i && i > 0 && ss == 0)) {
3120                         X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3121                         X509_free(xtmp);
3122                         trust = X509_TRUST_REJECTED;
3123                         ctx->error = X509_V_ERR_UNSPECIFIED;
3124                         search = 0;
3125                         continue;
3126                     }
3127                     search &= ~S_DOALTERNATE;
3128                     for (; num > i; --num)
3129                         X509_free(sk_X509_pop(ctx->chain));
3130                     ctx->num_untrusted = num;
3131
3132                     if (DANETLS_ENABLED(dane) &&
3133                         dane->mdpth >= ctx->num_untrusted) {
3134                         dane->mdpth = -1;
3135                         X509_free(dane->mcert);
3136                         dane->mcert = NULL;
3137                     }
3138                     if (DANETLS_ENABLED(dane) &&
3139                         dane->pdpth >= ctx->num_untrusted)
3140                         dane->pdpth = -1;
3141                 }
3142
3143                 /*
3144                  * Self-signed untrusted certificates get replaced by their
3145                  * trusted matching issuer.  Otherwise, grow the chain.
3146                  */
3147                 if (ss == 0) {
3148                     if (!sk_X509_push(ctx->chain, x = xtmp)) {
3149                         X509_free(xtmp);
3150                         X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3151                         trust = X509_TRUST_REJECTED;
3152                         ctx->error = X509_V_ERR_OUT_OF_MEM;
3153                         search = 0;
3154                         continue;
3155                     }
3156                     ss = cert_self_signed(ctx, x);
3157                     if (ss < 0) {
3158                         X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3159                         ctx->error = X509_V_ERR_UNSPECIFIED;
3160                         return 0;
3161                     }
3162                 } else if (num == ctx->num_untrusted) {
3163                     /*
3164                      * We have a self-signed certificate that has the same
3165                      * subject name (and perhaps keyid and/or serial number) as
3166                      * a trust-anchor.  We must have an exact match to avoid
3167                      * possible impersonation via key substitution etc.
3168                      */
3169                     if (X509_cmp(x, xtmp) != 0) {
3170                         /* Self-signed untrusted mimic. */
3171                         X509_free(xtmp);
3172                         ok = 0;
3173                     } else {
3174                         X509_free(x);
3175                         ctx->num_untrusted = --num;
3176                         (void) sk_X509_set(ctx->chain, num, x = xtmp);
3177                     }
3178                 }
3179
3180                 /*
3181                  * We've added a new trusted certificate to the chain, recheck
3182                  * trust.  If not done, and not self-signed look deeper.
3183                  * Whether or not we're doing "trusted first", we no longer
3184                  * look for untrusted certificates from the peer's chain.
3185                  *
3186                  * At this point ctx->num_trusted and num must reflect the
3187                  * correct number of untrusted certificates, since the DANE
3188                  * logic in check_trust() depends on distinguishing CAs from
3189                  * "the wire" from CAs from the trust store.  In particular, the
3190                  * certificate at depth "num" should be the new trusted
3191                  * certificate with ctx->num_untrusted <= num.
3192                  */
3193                 if (ok) {
3194                     if (!ossl_assert(ctx->num_untrusted <= num)) {
3195                         X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3196                         trust = X509_TRUST_REJECTED;
3197                         ctx->error = X509_V_ERR_UNSPECIFIED;
3198                         search = 0;
3199                         continue;
3200                     }
3201                     search &= ~S_DOUNTRUSTED;
3202                     switch (trust = check_trust(ctx, num)) {
3203                     case X509_TRUST_TRUSTED:
3204                     case X509_TRUST_REJECTED:
3205                         search = 0;
3206                         continue;
3207                     }
3208                     if (ss == 0)
3209                         continue;
3210                 }
3211             }
3212
3213             /*
3214              * No dispositive decision, and either self-signed or no match, if
3215              * we were doing untrusted-first, and alt-chains are not disabled,
3216              * do that, by repeatedly losing one untrusted element at a time,
3217              * and trying to extend the shorted chain.
3218              */
3219             if ((search & S_DOUNTRUSTED) == 0) {
3220                 /* Continue search for a trusted issuer of a shorter chain? */
3221                 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3222                     continue;
3223                 /* Still no luck and no fallbacks left? */
3224                 if (!may_alternate || (search & S_DOALTERNATE) != 0 ||
3225                     ctx->num_untrusted < 2)
3226                     break;
3227                 /* Search for a trusted issuer of a shorter chain */
3228                 search |= S_DOALTERNATE;
3229                 alt_untrusted = ctx->num_untrusted - 1;
3230                 ss = 0;
3231             }
3232         }
3233
3234         /*
3235          * Extend chain with peer-provided certificates
3236          */
3237         if ((search & S_DOUNTRUSTED) != 0) {
3238             num = sk_X509_num(ctx->chain);
3239             if (!ossl_assert(num == ctx->num_untrusted)) {
3240                 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3241                 trust = X509_TRUST_REJECTED;
3242                 ctx->error = X509_V_ERR_UNSPECIFIED;
3243                 search = 0;
3244                 continue;
3245             }
3246             x = sk_X509_value(ctx->chain, num-1);
3247
3248             /*
3249              * Once we run out of untrusted issuers, we stop looking for more
3250              * and start looking only in the trust store if enabled.
3251              */
3252             xtmp = (ss || depth < num) ? NULL : find_issuer(ctx, sktmp, x);
3253             if (xtmp == NULL) {
3254                 search &= ~S_DOUNTRUSTED;
3255                 if (may_trusted)
3256                     search |= S_DOTRUSTED;
3257                 continue;
3258             }
3259
3260             /* Drop this issuer from future consideration */
3261             (void) sk_X509_delete_ptr(sktmp, xtmp);
3262
3263             if (!X509_up_ref(xtmp)) {
3264                 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3265                 trust = X509_TRUST_REJECTED;
3266                 ctx->error = X509_V_ERR_UNSPECIFIED;
3267                 search = 0;
3268                 continue;
3269             }
3270
3271             if (!sk_X509_push(ctx->chain, xtmp)) {
3272                 X509_free(xtmp);
3273                 X509err(X509_F_BUILD_CHAIN, ERR_R_MALLOC_FAILURE);
3274                 trust = X509_TRUST_REJECTED;
3275                 ctx->error = X509_V_ERR_OUT_OF_MEM;
3276                 search = 0;
3277                 continue;
3278             }
3279
3280             x = xtmp;
3281             ++ctx->num_untrusted;
3282             ss = cert_self_signed(ctx, xtmp);
3283             if (ss < 0) {
3284                 X509err(X509_F_BUILD_CHAIN, ERR_R_INTERNAL_ERROR);
3285                 ctx->error = X509_V_ERR_UNSPECIFIED;
3286                 sk_X509_free(sktmp);
3287                 return 0;
3288             }
3289
3290             /*
3291              * Check for DANE-TA trust of the topmost untrusted certificate.
3292              */
3293             switch (trust = check_dane_issuer(ctx, ctx->num_untrusted - 1)) {
3294             case X509_TRUST_TRUSTED:
3295             case X509_TRUST_REJECTED:
3296                 search = 0;
3297                 continue;
3298             }
3299         }
3300     }
3301     sk_X509_free(sktmp);
3302
3303     /*
3304      * Last chance to make a trusted chain, either bare DANE-TA public-key
3305      * signers, or else direct leaf PKIX trust.
3306      */
3307     num = sk_X509_num(ctx->chain);
3308     if (num <= depth) {
3309         if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3310             trust = check_dane_pkeys(ctx);
3311         if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3312             trust = check_trust(ctx, num);
3313     }
3314
3315     switch (trust) {
3316     case X509_TRUST_TRUSTED:
3317         return 1;
3318     case X509_TRUST_REJECTED:
3319         /* Callback already issued */
3320         return 0;
3321     case X509_TRUST_UNTRUSTED:
3322     default:
3323         num = sk_X509_num(ctx->chain);
3324         if (num > depth)
3325             return verify_cb_cert(ctx, NULL, num-1,
3326                                   X509_V_ERR_CERT_CHAIN_TOO_LONG);
3327         if (DANETLS_ENABLED(dane) &&
3328             (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0))
3329             return verify_cb_cert(ctx, NULL, num-1, X509_V_ERR_DANE_NO_MATCH);
3330         if (ss && sk_X509_num(ctx->chain) == 1)
3331             return verify_cb_cert(ctx, NULL, num-1,
3332                                   X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT);
3333         if (ss)
3334             return verify_cb_cert(ctx, NULL, num-1,
3335                                   X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
3336         if (ctx->num_untrusted < num)
3337             return verify_cb_cert(ctx, NULL, num-1,
3338                                   X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT);
3339         return verify_cb_cert(ctx, NULL, num-1,
3340                               X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
3341     }
3342 }
3343
3344 static const int minbits_table[] = { 80, 112, 128, 192, 256 };
3345 static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
3346
3347 /*
3348  * Check whether the public key of ``cert`` meets the security level of
3349  * ``ctx``.
3350  *
3351  * Returns 1 on success, 0 otherwise.
3352  */
3353 static int check_key_level(X509_STORE_CTX *ctx, X509 *cert)
3354 {
3355     EVP_PKEY *pkey = X509_get0_pubkey(cert);
3356     int level = ctx->param->auth_level;
3357
3358     /*
3359      * At security level zero, return without checking for a supported public
3360      * key type.  Some engines support key types not understood outside the
3361      * engine, and we only need to understand the key when enforcing a security
3362      * floor.
3363      */
3364     if (level <= 0)
3365         return 1;
3366
3367     /* Unsupported or malformed keys are not secure */
3368     if (pkey == NULL)
3369         return 0;
3370
3371     if (level > NUM_AUTH_LEVELS)
3372         level = NUM_AUTH_LEVELS;
3373
3374     return EVP_PKEY_security_bits(pkey) >= minbits_table[level - 1];
3375 }
3376
3377 /*
3378  * Check whether the signature digest algorithm of ``cert`` meets the security
3379  * level of ``ctx``.  Should not be checked for trust anchors (whether
3380  * self-signed or otherwise).
3381  *
3382  * Returns 1 on success, 0 otherwise.
3383  */
3384 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
3385 {
3386     int secbits = -1;
3387     int level = ctx->param->auth_level;
3388
3389     if (level <= 0)
3390         return 1;
3391     if (level > NUM_AUTH_LEVELS)
3392         level = NUM_AUTH_LEVELS;
3393
3394     if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
3395         return 0;
3396
3397     return secbits >= minbits_table[level - 1];
3398 }