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