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