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