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