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