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