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