xref: /freebsd/crypto/openssl/crypto/x509/x509_vfy.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 1995-2025 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         X509_CRL_free(crl);
1127         X509_CRL_free(dcrl);
1128         crl = NULL;
1129         dcrl = NULL;
1130         /*
1131          * If reasons not updated we won't get anywhere by another iteration,
1132          * so exit loop.
1133          */
1134         if (last_reasons == ctx->current_reasons) {
1135             ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
1136             goto done;
1137         }
1138     }
1139 done:
1140     X509_CRL_free(crl);
1141     X509_CRL_free(dcrl);
1142 
1143     ctx->current_crl = NULL;
1144     return ok;
1145 }
1146 
1147 /* Check CRL times against values in X509_STORE_CTX */
check_crl_time(X509_STORE_CTX * ctx,X509_CRL * crl,int notify)1148 static int check_crl_time(X509_STORE_CTX *ctx, X509_CRL *crl, int notify)
1149 {
1150     time_t *ptime;
1151     int i;
1152 
1153     if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
1154         ptime = &ctx->param->check_time;
1155     else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
1156         return 1;
1157     else
1158         ptime = NULL;
1159     if (notify)
1160         ctx->current_crl = crl;
1161 
1162     i = X509_cmp_time(X509_CRL_get0_lastUpdate(crl), ptime);
1163     if (i == 0) {
1164         if (!notify)
1165             return 0;
1166         if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD))
1167             return 0;
1168     }
1169 
1170     if (i > 0) {
1171         if (!notify)
1172             return 0;
1173         if (!verify_cb_crl(ctx, X509_V_ERR_CRL_NOT_YET_VALID))
1174             return 0;
1175     }
1176 
1177     if (X509_CRL_get0_nextUpdate(crl)) {
1178         i = X509_cmp_time(X509_CRL_get0_nextUpdate(crl), ptime);
1179 
1180         if (i == 0) {
1181             if (!notify)
1182                 return 0;
1183             if (!verify_cb_crl(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD))
1184                 return 0;
1185         }
1186         /* Ignore expiration of base CRL is delta is valid */
1187         if (i < 0 && (ctx->current_crl_score & CRL_SCORE_TIME_DELTA) == 0) {
1188             if (!notify || !verify_cb_crl(ctx, X509_V_ERR_CRL_HAS_EXPIRED))
1189                 return 0;
1190         }
1191     }
1192 
1193     if (notify)
1194         ctx->current_crl = NULL;
1195 
1196     return 1;
1197 }
1198 
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)1199 static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl,
1200     X509 **pissuer, int *pscore, unsigned int *preasons,
1201     STACK_OF(X509_CRL) *crls)
1202 {
1203     int i, crl_score, best_score = *pscore;
1204     unsigned int reasons, best_reasons = 0;
1205     X509 *x = ctx->current_cert;
1206     X509_CRL *crl, *best_crl = NULL;
1207     X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1208 
1209     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1210         crl = sk_X509_CRL_value(crls, i);
1211         reasons = *preasons;
1212         crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1213         if (crl_score < best_score || crl_score == 0)
1214             continue;
1215         /* If current CRL is equivalent use it if it is newer */
1216         if (crl_score == best_score && best_crl != NULL) {
1217             int day, sec;
1218 
1219             if (ASN1_TIME_diff(&day, &sec, X509_CRL_get0_lastUpdate(best_crl),
1220                     X509_CRL_get0_lastUpdate(crl))
1221                 == 0)
1222                 continue;
1223             /*
1224              * ASN1_TIME_diff never returns inconsistent signs for |day|
1225              * and |sec|.
1226              */
1227             if (day <= 0 && sec <= 0)
1228                 continue;
1229         }
1230         best_crl = crl;
1231         best_crl_issuer = crl_issuer;
1232         best_score = crl_score;
1233         best_reasons = reasons;
1234     }
1235 
1236     if (best_crl != NULL) {
1237         if (!X509_CRL_up_ref(best_crl))
1238             return 0;
1239         X509_CRL_free(*pcrl);
1240         *pcrl = best_crl;
1241         *pissuer = best_crl_issuer;
1242         *pscore = best_score;
1243         *preasons = best_reasons;
1244         X509_CRL_free(*pdcrl);
1245         *pdcrl = NULL;
1246         get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1247     }
1248 
1249     if (best_score >= CRL_SCORE_VALID)
1250         return 1;
1251 
1252     return 0;
1253 }
1254 
1255 /*
1256  * Compare two CRL extensions for delta checking purposes. They should be
1257  * both present or both absent. If both present all fields must be identical.
1258  */
crl_extension_match(X509_CRL * a,X509_CRL * b,int nid)1259 static int crl_extension_match(X509_CRL *a, X509_CRL *b, int nid)
1260 {
1261     ASN1_OCTET_STRING *exta = NULL, *extb = NULL;
1262     int i = X509_CRL_get_ext_by_NID(a, nid, -1);
1263 
1264     if (i >= 0) {
1265         /* Can't have multiple occurrences */
1266         if (X509_CRL_get_ext_by_NID(a, nid, i) != -1)
1267             return 0;
1268         exta = X509_EXTENSION_get_data(X509_CRL_get_ext(a, i));
1269     }
1270 
1271     i = X509_CRL_get_ext_by_NID(b, nid, -1);
1272     if (i >= 0) {
1273         if (X509_CRL_get_ext_by_NID(b, nid, i) != -1)
1274             return 0;
1275         extb = X509_EXTENSION_get_data(X509_CRL_get_ext(b, i));
1276     }
1277 
1278     if (exta == NULL && extb == NULL)
1279         return 1;
1280 
1281     if (exta == NULL || extb == NULL)
1282         return 0;
1283 
1284     return ASN1_OCTET_STRING_cmp(exta, extb) == 0;
1285 }
1286 
1287 /* See if a base and delta are compatible */
check_delta_base(X509_CRL * delta,X509_CRL * base)1288 static int check_delta_base(X509_CRL *delta, X509_CRL *base)
1289 {
1290     /* Delta CRL must be a delta */
1291     if (delta->base_crl_number == NULL)
1292         return 0;
1293     /* Base must have a CRL number */
1294     if (base->crl_number == NULL)
1295         return 0;
1296     /* Issuer names must match */
1297     if (X509_NAME_cmp(X509_CRL_get_issuer(base),
1298             X509_CRL_get_issuer(delta))
1299         != 0)
1300         return 0;
1301     /* AKID and IDP must match */
1302     if (!crl_extension_match(delta, base, NID_authority_key_identifier))
1303         return 0;
1304     if (!crl_extension_match(delta, base, NID_issuing_distribution_point))
1305         return 0;
1306     /* Delta CRL base number must not exceed Full CRL number. */
1307     if (ASN1_INTEGER_cmp(delta->base_crl_number, base->crl_number) > 0)
1308         return 0;
1309     /* Delta CRL number must exceed full CRL number */
1310     return ASN1_INTEGER_cmp(delta->crl_number, base->crl_number) > 0;
1311 }
1312 
1313 /*
1314  * For a given base CRL find a delta... maybe extend to delta scoring or
1315  * retrieve a chain of deltas...
1316  */
get_delta_sk(X509_STORE_CTX * ctx,X509_CRL ** dcrl,int * pscore,X509_CRL * base,STACK_OF (X509_CRL)* crls)1317 static void get_delta_sk(X509_STORE_CTX *ctx, X509_CRL **dcrl, int *pscore,
1318     X509_CRL *base, STACK_OF(X509_CRL) *crls)
1319 {
1320     X509_CRL *delta;
1321     int i;
1322 
1323     if ((ctx->param->flags & X509_V_FLAG_USE_DELTAS) == 0)
1324         return;
1325     if (((ctx->current_cert->ex_flags | base->flags) & EXFLAG_FRESHEST) == 0)
1326         return;
1327     for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1328         delta = sk_X509_CRL_value(crls, i);
1329         if (check_delta_base(delta, base)) {
1330             if (!X509_CRL_up_ref(delta)) {
1331                 *dcrl = NULL;
1332                 return;
1333             }
1334 
1335             *dcrl = delta;
1336 
1337             if (check_crl_time(ctx, delta, 0))
1338                 *pscore |= CRL_SCORE_TIME_DELTA;
1339 
1340             return;
1341         }
1342     }
1343     *dcrl = NULL;
1344 }
1345 
1346 /*
1347  * For a given CRL return how suitable it is for the supplied certificate
1348  * 'x'. The return value is a mask of several criteria. If the issuer is not
1349  * the certificate issuer this is returned in *pissuer. The reasons mask is
1350  * also used to determine if the CRL is suitable: if no new reasons the CRL
1351  * is rejected, otherwise reasons is updated.
1352  */
get_crl_score(X509_STORE_CTX * ctx,X509 ** pissuer,unsigned int * preasons,X509_CRL * crl,X509 * x)1353 static int get_crl_score(X509_STORE_CTX *ctx, X509 **pissuer,
1354     unsigned int *preasons, X509_CRL *crl, X509 *x)
1355 {
1356     int crl_score = 0;
1357     unsigned int tmp_reasons = *preasons, crl_reasons;
1358 
1359     /* First see if we can reject CRL straight away */
1360 
1361     /* Invalid IDP cannot be processed */
1362     if ((crl->idp_flags & IDP_INVALID) != 0)
1363         return 0;
1364     /* Reason codes or indirect CRLs need extended CRL support */
1365     if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) {
1366         if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1367             return 0;
1368     } else if ((crl->idp_flags & IDP_REASONS) != 0) {
1369         /* If no new reasons reject */
1370         if ((crl->idp_reasons & ~tmp_reasons) == 0)
1371             return 0;
1372     }
1373     /* Don't process deltas at this stage */
1374     else if (crl->base_crl_number != NULL)
1375         return 0;
1376     /* If issuer name doesn't match certificate need indirect CRL */
1377     if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl)) != 0) {
1378         if ((crl->idp_flags & IDP_INDIRECT) == 0)
1379             return 0;
1380     } else {
1381         crl_score |= CRL_SCORE_ISSUER_NAME;
1382     }
1383 
1384     if ((crl->flags & EXFLAG_CRITICAL) == 0)
1385         crl_score |= CRL_SCORE_NOCRITICAL;
1386 
1387     /* Check expiration */
1388     if (check_crl_time(ctx, crl, 0))
1389         crl_score |= CRL_SCORE_TIME;
1390 
1391     /* Check authority key ID and locate certificate issuer */
1392     crl_akid_check(ctx, crl, pissuer, &crl_score);
1393 
1394     /* If we can't locate certificate issuer at this point forget it */
1395     if ((crl_score & CRL_SCORE_AKID) == 0)
1396         return 0;
1397 
1398     /* Check cert for matching CRL distribution points */
1399     if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1400         /* If no new reasons reject */
1401         if ((crl_reasons & ~tmp_reasons) == 0)
1402             return 0;
1403         tmp_reasons |= crl_reasons;
1404         crl_score |= CRL_SCORE_SCOPE;
1405     }
1406 
1407     *preasons = tmp_reasons;
1408 
1409     return crl_score;
1410 }
1411 
crl_akid_check(X509_STORE_CTX * ctx,X509_CRL * crl,X509 ** pissuer,int * pcrl_score)1412 static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1413     X509 **pissuer, int *pcrl_score)
1414 {
1415     X509 *crl_issuer = NULL;
1416     const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1417     int cidx = ctx->error_depth;
1418     int i;
1419 
1420     if (cidx != sk_X509_num(ctx->chain) - 1)
1421         cidx++;
1422 
1423     crl_issuer = sk_X509_value(ctx->chain, cidx);
1424 
1425     if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1426         if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1427             *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1428             *pissuer = crl_issuer;
1429             return;
1430         }
1431     }
1432 
1433     for (cidx++; cidx < sk_X509_num(ctx->chain); cidx++) {
1434         crl_issuer = sk_X509_value(ctx->chain, cidx);
1435         if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm))
1436             continue;
1437         if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1438             *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_SAME_PATH;
1439             *pissuer = crl_issuer;
1440             return;
1441         }
1442     }
1443 
1444     /* Anything else needs extended CRL support */
1445     if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0)
1446         return;
1447 
1448     /*
1449      * Otherwise the CRL issuer is not on the path. Look for it in the set of
1450      * untrusted certificates.
1451      */
1452     for (i = 0; i < sk_X509_num(ctx->untrusted); i++) {
1453         crl_issuer = sk_X509_value(ctx->untrusted, i);
1454         if (X509_NAME_cmp(X509_get_subject_name(crl_issuer), cnm) != 0)
1455             continue;
1456         if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1457             *pissuer = crl_issuer;
1458             *pcrl_score |= CRL_SCORE_AKID;
1459             return;
1460         }
1461     }
1462 }
1463 
1464 /*
1465  * Check the path of a CRL issuer certificate. This creates a new
1466  * X509_STORE_CTX and populates it with most of the parameters from the
1467  * parent. This could be optimised somewhat since a lot of path checking will
1468  * be duplicated by the parent, but this will rarely be used in practice.
1469  */
check_crl_path(X509_STORE_CTX * ctx,X509 * x)1470 static int check_crl_path(X509_STORE_CTX *ctx, X509 *x)
1471 {
1472     X509_STORE_CTX crl_ctx = { 0 };
1473     int ret;
1474 
1475     /* Don't allow recursive CRL path validation */
1476     if (ctx->parent != NULL)
1477         return 0;
1478     if (!X509_STORE_CTX_init(&crl_ctx, ctx->store, x, ctx->untrusted))
1479         return -1;
1480 
1481     crl_ctx.crls = ctx->crls;
1482     /* Copy verify params across */
1483     X509_STORE_CTX_set0_param(&crl_ctx, ctx->param);
1484 
1485     crl_ctx.parent = ctx;
1486     crl_ctx.verify_cb = ctx->verify_cb;
1487 
1488     /* Verify CRL issuer */
1489     ret = X509_verify_cert(&crl_ctx);
1490     if (ret <= 0)
1491         goto err;
1492 
1493     /* Check chain is acceptable */
1494     ret = check_crl_chain(ctx, ctx->chain, crl_ctx.chain);
1495 err:
1496     X509_STORE_CTX_cleanup(&crl_ctx);
1497     return ret;
1498 }
1499 
1500 /*
1501  * RFC3280 says nothing about the relationship between CRL path and
1502  * certificate path, which could lead to situations where a certificate could
1503  * be revoked or validated by a CA not authorized to do so. RFC5280 is more
1504  * strict and states that the two paths must end in the same trust anchor,
1505  * though some discussions remain... until this is resolved we use the
1506  * RFC5280 version
1507  */
check_crl_chain(X509_STORE_CTX * ctx,STACK_OF (X509)* cert_path,STACK_OF (X509)* crl_path)1508 static int check_crl_chain(X509_STORE_CTX *ctx,
1509     STACK_OF(X509) *cert_path,
1510     STACK_OF(X509) *crl_path)
1511 {
1512     X509 *cert_ta = sk_X509_value(cert_path, sk_X509_num(cert_path) - 1);
1513     X509 *crl_ta = sk_X509_value(crl_path, sk_X509_num(crl_path) - 1);
1514 
1515     return X509_cmp(cert_ta, crl_ta) == 0;
1516 }
1517 
1518 /*-
1519  * Check for match between two dist point names: three separate cases.
1520  * 1. Both are relative names and compare X509_NAME types.
1521  * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1522  * 3. Both are full names and compare two GENERAL_NAMES.
1523  * 4. One is NULL: automatic match.
1524  */
idp_check_dp(DIST_POINT_NAME * a,DIST_POINT_NAME * b)1525 static int idp_check_dp(DIST_POINT_NAME *a, DIST_POINT_NAME *b)
1526 {
1527     X509_NAME *nm = NULL;
1528     GENERAL_NAMES *gens = NULL;
1529     GENERAL_NAME *gena, *genb;
1530     int i, j;
1531 
1532     if (a == NULL || b == NULL)
1533         return 1;
1534     if (a->type == 1) {
1535         if (a->dpname == NULL)
1536             return 0;
1537         /* Case 1: two X509_NAME */
1538         if (b->type == 1) {
1539             if (b->dpname == NULL)
1540                 return 0;
1541             return X509_NAME_cmp(a->dpname, b->dpname) == 0;
1542         }
1543         /* Case 2: set name and GENERAL_NAMES appropriately */
1544         nm = a->dpname;
1545         gens = b->name.fullname;
1546     } else if (b->type == 1) {
1547         if (b->dpname == NULL)
1548             return 0;
1549         /* Case 2: set name and GENERAL_NAMES appropriately */
1550         gens = a->name.fullname;
1551         nm = b->dpname;
1552     }
1553 
1554     /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1555     if (nm != NULL) {
1556         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1557             gena = sk_GENERAL_NAME_value(gens, i);
1558             if (gena->type != GEN_DIRNAME)
1559                 continue;
1560             if (X509_NAME_cmp(nm, gena->d.directoryName) == 0)
1561                 return 1;
1562         }
1563         return 0;
1564     }
1565 
1566     /* Else case 3: two GENERAL_NAMES */
1567 
1568     for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1569         gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1570         for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1571             genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1572             if (GENERAL_NAME_cmp(gena, genb) == 0)
1573                 return 1;
1574         }
1575     }
1576 
1577     return 0;
1578 }
1579 
crldp_check_crlissuer(DIST_POINT * dp,X509_CRL * crl,int crl_score)1580 static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1581 {
1582     int i;
1583     const X509_NAME *nm = X509_CRL_get_issuer(crl);
1584 
1585     /* If no CRLissuer return is successful iff don't need a match */
1586     if (dp->CRLissuer == NULL)
1587         return (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1588     for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1589         GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1590 
1591         if (gen->type != GEN_DIRNAME)
1592             continue;
1593         if (X509_NAME_cmp(gen->d.directoryName, nm) == 0)
1594             return 1;
1595     }
1596     return 0;
1597 }
1598 
1599 /* Check CRLDP and IDP */
crl_crldp_check(X509 * x,X509_CRL * crl,int crl_score,unsigned int * preasons)1600 static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1601     unsigned int *preasons)
1602 {
1603     int i;
1604 
1605     if ((crl->idp_flags & IDP_ONLYATTR) != 0)
1606         return 0;
1607     if ((x->ex_flags & EXFLAG_CA) != 0) {
1608         if ((crl->idp_flags & IDP_ONLYUSER) != 0)
1609             return 0;
1610     } else {
1611         if ((crl->idp_flags & IDP_ONLYCA) != 0)
1612             return 0;
1613     }
1614     *preasons = crl->idp_reasons;
1615     for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1616         DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1617 
1618         if (crldp_check_crlissuer(dp, crl, crl_score)) {
1619             if (crl->idp == NULL
1620                 || idp_check_dp(dp->distpoint, crl->idp->distpoint)) {
1621                 *preasons &= dp->dp_reasons;
1622                 return 1;
1623             }
1624         }
1625     }
1626     return (crl->idp == NULL || crl->idp->distpoint == NULL)
1627         && (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1628 }
1629 
1630 /*
1631  * Retrieve CRL corresponding to current certificate. If deltas enabled try
1632  * to find a delta CRL too
1633  */
get_crl_delta(X509_STORE_CTX * ctx,X509_CRL ** pcrl,X509_CRL ** pdcrl,X509 * x)1634 static int get_crl_delta(X509_STORE_CTX *ctx,
1635     X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1636 {
1637     int ok;
1638     X509 *issuer = NULL;
1639     int crl_score = 0;
1640     unsigned int reasons;
1641     X509_CRL *crl = NULL, *dcrl = NULL;
1642     STACK_OF(X509_CRL) *skcrl;
1643     const X509_NAME *nm = X509_get_issuer_name(x);
1644 
1645     reasons = ctx->current_reasons;
1646     ok = get_crl_sk(ctx, &crl, &dcrl,
1647         &issuer, &crl_score, &reasons, ctx->crls);
1648     if (ok)
1649         goto done;
1650 
1651     /* Lookup CRLs from store */
1652     skcrl = ctx->lookup_crls(ctx, nm);
1653 
1654     /* If no CRLs found and a near match from get_crl_sk use that */
1655     if (skcrl == NULL && crl != NULL)
1656         goto done;
1657 
1658     get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1659 
1660     sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1661 
1662 done:
1663     /* If we got any kind of CRL use it and return success */
1664     if (crl != NULL) {
1665         ctx->current_issuer = issuer;
1666         ctx->current_crl_score = crl_score;
1667         ctx->current_reasons = reasons;
1668         *pcrl = crl;
1669         *pdcrl = dcrl;
1670         return 1;
1671     }
1672     return 0;
1673 }
1674 
1675 /* Check CRL validity */
check_crl(X509_STORE_CTX * ctx,X509_CRL * crl)1676 static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1677 {
1678     X509 *issuer = NULL;
1679     EVP_PKEY *ikey = NULL;
1680     int cnum = ctx->error_depth;
1681     int chnum = sk_X509_num(ctx->chain) - 1;
1682 
1683     /* If we have an alternative CRL issuer cert use that */
1684     if (ctx->current_issuer != NULL) {
1685         issuer = ctx->current_issuer;
1686         /*
1687          * Else find CRL issuer: if not last certificate then issuer is next
1688          * certificate in chain.
1689          */
1690     } else if (cnum < chnum) {
1691         issuer = sk_X509_value(ctx->chain, cnum + 1);
1692     } else {
1693         issuer = sk_X509_value(ctx->chain, chnum);
1694         if (!ossl_assert(issuer != NULL))
1695             return 0;
1696         /* If not self-issued, can't check signature */
1697         if (!ctx->check_issued(ctx, issuer, issuer) && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
1698             return 0;
1699     }
1700 
1701     if (issuer == NULL)
1702         return 1;
1703 
1704     /*
1705      * Skip most tests for deltas because they have already been done
1706      */
1707     if (crl->base_crl_number == NULL) {
1708         /* Check for cRLSign bit if keyUsage present */
1709         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))
1710             return 0;
1711 
1712         if ((ctx->current_crl_score & CRL_SCORE_SCOPE) == 0 && !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
1713             return 0;
1714 
1715         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))
1716             return 0;
1717 
1718         if ((crl->idp_flags & IDP_INVALID) != 0 && !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
1719             return 0;
1720     }
1721 
1722     if ((ctx->current_crl_score & CRL_SCORE_TIME) == 0 && !check_crl_time(ctx, crl, 1))
1723         return 0;
1724 
1725     /* Attempt to get issuer certificate public key */
1726     ikey = X509_get0_pubkey(issuer);
1727     if (ikey == NULL && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
1728         return 0;
1729 
1730     if (ikey != NULL) {
1731         int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
1732 
1733         if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
1734             return 0;
1735         /* Verify CRL signature */
1736         if (X509_CRL_verify(crl, ikey) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
1737             return 0;
1738     }
1739     return 1;
1740 }
1741 
1742 /* Check certificate against CRL */
cert_crl(X509_STORE_CTX * ctx,X509_CRL * crl,X509 * x)1743 static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
1744 {
1745     X509_REVOKED *rev;
1746 
1747     /*
1748      * The rules changed for this... previously if a CRL contained unhandled
1749      * critical extensions it could still be used to indicate a certificate
1750      * was revoked. This has since been changed since critical extensions can
1751      * change the meaning of CRL entries.
1752      */
1753     if ((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
1754         && (crl->flags & EXFLAG_CRITICAL) != 0 && !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
1755         return 0;
1756     /*
1757      * Look for serial number of certificate in CRL.  If found, make sure
1758      * reason is not removeFromCRL.
1759      */
1760     if (X509_CRL_get0_by_cert(crl, &rev, x)) {
1761         if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
1762             return 2;
1763         if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
1764             return 0;
1765     }
1766 
1767     return 1;
1768 }
1769 
1770 /* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
check_policy(X509_STORE_CTX * ctx)1771 static int check_policy(X509_STORE_CTX *ctx)
1772 {
1773     int ret;
1774 
1775     if (ctx->parent)
1776         return 1;
1777     /*
1778      * With DANE, the trust anchor might be a bare public key, not a
1779      * certificate!  In that case our chain does not have the trust anchor
1780      * certificate as a top-most element.  This comports well with RFC5280
1781      * chain verification, since there too, the trust anchor is not part of the
1782      * chain to be verified.  In particular, X509_policy_check() does not look
1783      * at the TA cert, but assumes that it is present as the top-most chain
1784      * element.  We therefore temporarily push a NULL cert onto the chain if it
1785      * was verified via a bare public key, and pop it off right after the
1786      * X509_policy_check() call.
1787      */
1788     if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
1789         ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
1790         goto memerr;
1791     }
1792     ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
1793         ctx->param->policies, ctx->param->flags);
1794     if (ctx->bare_ta_signed)
1795         (void)sk_X509_pop(ctx->chain);
1796 
1797     if (ret == X509_PCY_TREE_INTERNAL) {
1798         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
1799         goto memerr;
1800     }
1801     /* Invalid or inconsistent extensions */
1802     if (ret == X509_PCY_TREE_INVALID) {
1803         int i, cbcalled = 0;
1804 
1805         /* Locate certificates with bad extensions and notify callback. */
1806         for (i = 0; i < sk_X509_num(ctx->chain); i++) {
1807             X509 *x = sk_X509_value(ctx->chain, i);
1808 
1809             if ((x->ex_flags & EXFLAG_INVALID_POLICY) != 0)
1810                 cbcalled = 1;
1811             CB_FAIL_IF((x->ex_flags & EXFLAG_INVALID_POLICY) != 0,
1812                 ctx, x, i, X509_V_ERR_INVALID_POLICY_EXTENSION);
1813         }
1814         if (!cbcalled) {
1815             /* Should not be able to get here */
1816             ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
1817             return 0;
1818         }
1819         /* The callback ignored the error so we return success */
1820         return 1;
1821     }
1822     if (ret == X509_PCY_TREE_FAILURE) {
1823         ctx->current_cert = NULL;
1824         ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
1825         return ctx->verify_cb(0, ctx);
1826     }
1827     if (ret != X509_PCY_TREE_VALID) {
1828         ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
1829         return 0;
1830     }
1831 
1832     if ((ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) != 0) {
1833         ctx->current_cert = NULL;
1834         /*
1835          * Verification errors need to be "sticky", a callback may have allowed
1836          * an SSL handshake to continue despite an error, and we must then
1837          * remain in an error state.  Therefore, we MUST NOT clear earlier
1838          * verification errors by setting the error to X509_V_OK.
1839          */
1840         if (!ctx->verify_cb(2, ctx))
1841             return 0;
1842     }
1843 
1844     return 1;
1845 
1846 memerr:
1847     ctx->error = X509_V_ERR_OUT_OF_MEM;
1848     return -1;
1849 }
1850 
1851 /*-
1852  * Check certificate validity times.
1853  * If depth >= 0, invoke verification callbacks on error, otherwise just return
1854  * the validation status.
1855  *
1856  * Return 1 on success, 0 otherwise.
1857  * Sadly, returns 0 also on internal error in ctx->verify_cb().
1858  */
ossl_x509_check_cert_time(X509_STORE_CTX * ctx,X509 * x,int depth)1859 int ossl_x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
1860 {
1861     time_t *ptime;
1862     int i;
1863 
1864     if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
1865         ptime = &ctx->param->check_time;
1866     else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
1867         return 1;
1868     else
1869         ptime = NULL;
1870 
1871     i = X509_cmp_time(X509_get0_notBefore(x), ptime);
1872     if (i >= 0 && depth < 0)
1873         return 0;
1874     CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
1875     CB_FAIL_IF(i > 0, ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID);
1876 
1877     i = X509_cmp_time(X509_get0_notAfter(x), ptime);
1878     if (i <= 0 && depth < 0)
1879         return 0;
1880     CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
1881     CB_FAIL_IF(i < 0, ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED);
1882     return 1;
1883 }
1884 
1885 /*
1886  * Verify the issuer signatures and cert times of ctx->chain.
1887  * Sadly, returns 0 also on internal error in ctx->verify_cb().
1888  */
internal_verify(X509_STORE_CTX * ctx)1889 static int internal_verify(X509_STORE_CTX *ctx)
1890 {
1891     int n;
1892     X509 *xi;
1893     X509 *xs;
1894 
1895     /* For RPK: just do the verify callback */
1896     if (ctx->rpk != NULL) {
1897         if (!ctx->verify_cb(ctx->error == X509_V_OK, ctx))
1898             return 0;
1899         return 1;
1900     }
1901     n = sk_X509_num(ctx->chain) - 1;
1902     xi = sk_X509_value(ctx->chain, n);
1903     xs = xi;
1904 
1905     ctx->error_depth = n;
1906     if (ctx->bare_ta_signed) {
1907         /*
1908          * With DANE-verified bare public key TA signatures,
1909          * on the top certificate we check only the timestamps.
1910          * We report the issuer as NULL because all we have is a bare key.
1911          */
1912         xi = NULL;
1913     } else if (ossl_x509_likely_issued(xi, xi) != X509_V_OK
1914         /* exceptional case: last cert in the chain is not self-issued */
1915         && ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0)) {
1916         if (n > 0) {
1917             n--;
1918             ctx->error_depth = n;
1919             xs = sk_X509_value(ctx->chain, n);
1920         } else {
1921             CB_FAIL_IF(1, ctx, xi, 0,
1922                 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
1923         }
1924         /*
1925          * The below code will certainly not do a
1926          * self-signature check on xi because it is not self-issued.
1927          */
1928     }
1929 
1930     /*
1931      * Do not clear error (by ctx->error = X509_V_OK), it must be "sticky",
1932      * only the user's callback is allowed to reset errors (at its own peril).
1933      */
1934     while (n >= 0) {
1935         /*-
1936          * For each iteration of this loop:
1937          * n is the subject depth
1938          * xs is the subject cert, for which the signature is to be checked
1939          * xi is NULL for DANE-verified bare public key TA signatures
1940          *       else the supposed issuer cert containing the public key to use
1941          * Initially xs == xi if the last cert in the chain is self-issued.
1942          */
1943         /*
1944          * Do signature check for self-signed certificates only if explicitly
1945          * asked for because it does not add any security and just wastes time.
1946          */
1947         if (xi != NULL
1948             && (xs != xi
1949                 || ((ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE) != 0
1950                     && (xi->ex_flags & EXFLAG_SS) != 0))) {
1951             EVP_PKEY *pkey;
1952             /*
1953              * If the issuer's public key is not available or its key usage
1954              * does not support issuing the subject cert, report the issuer
1955              * cert and its depth (rather than n, the depth of the subject).
1956              */
1957             int issuer_depth = n + (xs == xi ? 0 : 1);
1958             /*
1959              * According to https://tools.ietf.org/html/rfc5280#section-6.1.4
1960              * step (n) we must check any given key usage extension in a CA cert
1961              * when preparing the verification of a certificate issued by it.
1962              * According to https://tools.ietf.org/html/rfc5280#section-4.2.1.3
1963              * we must not verify a certificate signature if the key usage of
1964              * the CA certificate that issued the certificate prohibits signing.
1965              * In case the 'issuing' certificate is the last in the chain and is
1966              * not a CA certificate but a 'self-issued' end-entity cert (i.e.,
1967              * xs == xi && !(xi->ex_flags & EXFLAG_CA)) RFC 5280 does not apply
1968              * (see https://tools.ietf.org/html/rfc6818#section-2) and thus
1969              * we are free to ignore any key usage restrictions on such certs.
1970              */
1971             int ret = xs == xi && (xi->ex_flags & EXFLAG_CA) == 0
1972                 ? X509_V_OK
1973                 : ossl_x509_signing_allowed(xi, xs);
1974 
1975             CB_FAIL_IF(ret != X509_V_OK, ctx, xi, issuer_depth, ret);
1976             if ((pkey = X509_get0_pubkey(xi)) == NULL) {
1977                 CB_FAIL_IF(1, ctx, xi, issuer_depth,
1978                     X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
1979             } else {
1980                 CB_FAIL_IF(X509_verify(xs, pkey) <= 0,
1981                     ctx, xs, n, X509_V_ERR_CERT_SIGNATURE_FAILURE);
1982             }
1983         }
1984 
1985         /* In addition to RFC 5280 requirements do also for trust anchor cert */
1986         /* Calls verify callback as needed */
1987         if (!ossl_x509_check_cert_time(ctx, xs, n))
1988             return 0;
1989 
1990         /*
1991          * Signal success at this depth.  However, the previous error (if any)
1992          * is retained.
1993          */
1994         ctx->current_issuer = xi;
1995         ctx->current_cert = xs;
1996         ctx->error_depth = n;
1997         if (!ctx->verify_cb(1, ctx))
1998             return 0;
1999 
2000         if (--n >= 0) {
2001             xi = xs;
2002             xs = sk_X509_value(ctx->chain, n);
2003         }
2004     }
2005     return 1;
2006 }
2007 
X509_cmp_current_time(const ASN1_TIME * ctm)2008 int X509_cmp_current_time(const ASN1_TIME *ctm)
2009 {
2010     return X509_cmp_time(ctm, NULL);
2011 }
2012 
2013 /* returns 0 on error, otherwise 1 if ctm > cmp_time, else -1 */
X509_cmp_time(const ASN1_TIME * ctm,time_t * cmp_time)2014 int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
2015 {
2016     static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
2017     static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
2018     ASN1_TIME *asn1_cmp_time = NULL;
2019     int i, day, sec, ret = 0;
2020 #ifdef CHARSET_EBCDIC
2021     const char upper_z = 0x5A;
2022 #else
2023     const char upper_z = 'Z';
2024 #endif
2025 
2026     /*-
2027      * Note that ASN.1 allows much more slack in the time format than RFC5280.
2028      * In RFC5280, the representation is fixed:
2029      * UTCTime: YYMMDDHHMMSSZ
2030      * GeneralizedTime: YYYYMMDDHHMMSSZ
2031      *
2032      * We do NOT currently enforce the following RFC 5280 requirement:
2033      * "CAs conforming to this profile MUST always encode certificate
2034      *  validity dates through the year 2049 as UTCTime; certificate validity
2035      *  dates in 2050 or later MUST be encoded as GeneralizedTime."
2036      */
2037     switch (ctm->type) {
2038     case V_ASN1_UTCTIME:
2039         if (ctm->length != (int)(utctime_length))
2040             return 0;
2041         break;
2042     case V_ASN1_GENERALIZEDTIME:
2043         if (ctm->length != (int)(generalizedtime_length))
2044             return 0;
2045         break;
2046     default:
2047         return 0;
2048     }
2049 
2050     /**
2051      * Verify the format: the ASN.1 functions we use below allow a more
2052      * flexible format than what's mandated by RFC 5280.
2053      * Digit and date ranges will be verified in the conversion methods.
2054      */
2055     for (i = 0; i < ctm->length - 1; i++) {
2056         if (!ossl_ascii_isdigit(ctm->data[i]))
2057             return 0;
2058     }
2059     if (ctm->data[ctm->length - 1] != upper_z)
2060         return 0;
2061 
2062     /*
2063      * There is ASN1_UTCTIME_cmp_time_t but no
2064      * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
2065      * so we go through ASN.1
2066      */
2067     asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
2068     if (asn1_cmp_time == NULL)
2069         goto err;
2070     if (ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time) == 0)
2071         goto err;
2072 
2073     /*
2074      * X509_cmp_time comparison is <=.
2075      * The return value 0 is reserved for errors.
2076      */
2077     ret = (day >= 0 && sec >= 0) ? -1 : 1;
2078 
2079 err:
2080     ASN1_TIME_free(asn1_cmp_time);
2081     return ret;
2082 }
2083 
2084 /*
2085  * Return 0 if time should not be checked or reference time is in range,
2086  * or else 1 if it is past the end, or -1 if it is before the start
2087  */
X509_cmp_timeframe(const X509_VERIFY_PARAM * vpm,const ASN1_TIME * start,const ASN1_TIME * end)2088 int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
2089     const ASN1_TIME *start, const ASN1_TIME *end)
2090 {
2091     time_t ref_time;
2092     time_t *time = NULL;
2093     unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
2094 
2095     if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
2096         ref_time = X509_VERIFY_PARAM_get_time(vpm);
2097         time = &ref_time;
2098     } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
2099         return 0; /* this means ok */
2100     } /* else reference time is the current time */
2101 
2102     if (end != NULL && X509_cmp_time(end, time) < 0)
2103         return 1;
2104     if (start != NULL && X509_cmp_time(start, time) > 0)
2105         return -1;
2106     return 0;
2107 }
2108 
X509_gmtime_adj(ASN1_TIME * s,long adj)2109 ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
2110 {
2111     return X509_time_adj(s, adj, NULL);
2112 }
2113 
X509_time_adj(ASN1_TIME * s,long offset_sec,time_t * in_tm)2114 ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
2115 {
2116     return X509_time_adj_ex(s, 0, offset_sec, in_tm);
2117 }
2118 
X509_time_adj_ex(ASN1_TIME * s,int offset_day,long offset_sec,time_t * in_tm)2119 ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
2120     int offset_day, long offset_sec, time_t *in_tm)
2121 {
2122     time_t t;
2123 
2124     if (in_tm)
2125         t = *in_tm;
2126     else
2127         time(&t);
2128 
2129     if (s != NULL && (s->flags & ASN1_STRING_FLAG_MSTRING) == 0) {
2130         if (s->type == V_ASN1_UTCTIME)
2131             return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
2132         if (s->type == V_ASN1_GENERALIZEDTIME)
2133             return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
2134     }
2135     return ASN1_TIME_adj(s, t, offset_day, offset_sec);
2136 }
2137 
2138 /* Copy any missing public key parameters up the chain towards pkey */
X509_get_pubkey_parameters(EVP_PKEY * pkey,STACK_OF (X509)* chain)2139 int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
2140 {
2141     EVP_PKEY *ktmp = NULL, *ktmp2;
2142     int i, j;
2143 
2144     if (pkey != NULL && !EVP_PKEY_missing_parameters(pkey))
2145         return 1;
2146 
2147     for (i = 0; i < sk_X509_num(chain); i++) {
2148         ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
2149         if (ktmp == NULL) {
2150             ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
2151             return 0;
2152         }
2153         if (!EVP_PKEY_missing_parameters(ktmp))
2154             break;
2155         ktmp = NULL;
2156     }
2157     if (ktmp == NULL) {
2158         ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
2159         return 0;
2160     }
2161 
2162     /* first, populate the other certs */
2163     for (j = i - 1; j >= 0; j--) {
2164         ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
2165         if (!EVP_PKEY_copy_parameters(ktmp2, ktmp))
2166             return 0;
2167     }
2168 
2169     if (pkey != NULL)
2170         return EVP_PKEY_copy_parameters(pkey, ktmp);
2171     return 1;
2172 }
2173 
2174 /*
2175  * Make a delta CRL as the difference between two full CRLs.
2176  * Sadly, returns NULL also on internal error.
2177  */
X509_CRL_diff(X509_CRL * base,X509_CRL * newer,EVP_PKEY * skey,const EVP_MD * md,unsigned int flags)2178 X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
2179     EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
2180 {
2181     X509_CRL *crl = NULL;
2182     int i;
2183     STACK_OF(X509_REVOKED) *revs = NULL;
2184 
2185     /* CRLs can't be delta already */
2186     if (base->base_crl_number != NULL || newer->base_crl_number != NULL) {
2187         ERR_raise(ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA);
2188         return NULL;
2189     }
2190     /* Base and new CRL must have a CRL number */
2191     if (base->crl_number == NULL || newer->crl_number == NULL) {
2192         ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_NUMBER);
2193         return NULL;
2194     }
2195     /* Issuer names must match */
2196     if (X509_NAME_cmp(X509_CRL_get_issuer(base),
2197             X509_CRL_get_issuer(newer))
2198         != 0) {
2199         ERR_raise(ERR_LIB_X509, X509_R_ISSUER_MISMATCH);
2200         return NULL;
2201     }
2202     /* AKID and IDP must match */
2203     if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
2204         ERR_raise(ERR_LIB_X509, X509_R_AKID_MISMATCH);
2205         return NULL;
2206     }
2207     if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
2208         ERR_raise(ERR_LIB_X509, X509_R_IDP_MISMATCH);
2209         return NULL;
2210     }
2211     /* Newer CRL number must exceed full CRL number */
2212     if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
2213         ERR_raise(ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER);
2214         return NULL;
2215     }
2216     /* CRLs must verify */
2217     if (skey != NULL && (X509_CRL_verify(base, skey) <= 0 || X509_CRL_verify(newer, skey) <= 0)) {
2218         ERR_raise(ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE);
2219         return NULL;
2220     }
2221     /* Create new CRL */
2222     crl = X509_CRL_new_ex(base->libctx, base->propq);
2223     if (crl == NULL || !X509_CRL_set_version(crl, X509_CRL_VERSION_2)) {
2224         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2225         goto err;
2226     }
2227     /* Set issuer name */
2228     if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) {
2229         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2230         goto err;
2231     }
2232 
2233     if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer))) {
2234         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2235         goto err;
2236     }
2237     if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer))) {
2238         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2239         goto err;
2240     }
2241 
2242     /* Set base CRL number: must be critical */
2243     if (X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0) <= 0) {
2244         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2245         goto err;
2246     }
2247 
2248     /*
2249      * Copy extensions across from newest CRL to delta: this will set CRL
2250      * number to correct value too.
2251      */
2252     for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2253         X509_EXTENSION *ext = X509_CRL_get_ext(newer, i);
2254 
2255         if (!X509_CRL_add_ext(crl, ext, -1)) {
2256             ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2257             goto err;
2258         }
2259     }
2260 
2261     /* Go through revoked entries, copying as needed */
2262     revs = X509_CRL_get_REVOKED(newer);
2263 
2264     for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2265         X509_REVOKED *rvn, *rvtmp;
2266 
2267         rvn = sk_X509_REVOKED_value(revs, i);
2268         /*
2269          * Add only if not also in base.
2270          * Need something cleverer here for some more complex CRLs covering
2271          * multiple CAs.
2272          */
2273         if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2274             rvtmp = X509_REVOKED_dup(rvn);
2275             if (rvtmp == NULL) {
2276                 ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2277                 goto err;
2278             }
2279             if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2280                 X509_REVOKED_free(rvtmp);
2281                 ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2282                 goto err;
2283             }
2284         }
2285     }
2286 
2287     if (skey != NULL && md != NULL && !X509_CRL_sign(crl, skey, md)) {
2288         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2289         goto err;
2290     }
2291 
2292     return crl;
2293 
2294 err:
2295     X509_CRL_free(crl);
2296     return NULL;
2297 }
2298 
X509_STORE_CTX_set_ex_data(X509_STORE_CTX * ctx,int idx,void * data)2299 int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2300 {
2301     return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2302 }
2303 
X509_STORE_CTX_get_ex_data(const X509_STORE_CTX * ctx,int idx)2304 void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2305 {
2306     return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2307 }
2308 
X509_STORE_CTX_get_error(const X509_STORE_CTX * ctx)2309 int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2310 {
2311     return ctx->error;
2312 }
2313 
X509_STORE_CTX_set_error(X509_STORE_CTX * ctx,int err)2314 void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2315 {
2316     ctx->error = err;
2317 }
2318 
X509_STORE_CTX_get_error_depth(const X509_STORE_CTX * ctx)2319 int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2320 {
2321     return ctx->error_depth;
2322 }
2323 
X509_STORE_CTX_set_error_depth(X509_STORE_CTX * ctx,int depth)2324 void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2325 {
2326     ctx->error_depth = depth;
2327 }
2328 
X509_STORE_CTX_get_current_cert(const X509_STORE_CTX * ctx)2329 X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2330 {
2331     return ctx->current_cert;
2332 }
2333 
X509_STORE_CTX_set_current_cert(X509_STORE_CTX * ctx,X509 * x)2334 void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2335 {
2336     ctx->current_cert = x;
2337 }
2338 
STACK_OF(X509)2339 STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2340 {
2341     return ctx->chain;
2342 }
2343 
STACK_OF(X509)2344 STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2345 {
2346     if (ctx->chain == NULL)
2347         return NULL;
2348     return X509_chain_up_ref(ctx->chain);
2349 }
2350 
X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX * ctx)2351 X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2352 {
2353     return ctx->current_issuer;
2354 }
2355 
X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX * ctx)2356 X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2357 {
2358     return ctx->current_crl;
2359 }
2360 
X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX * ctx)2361 X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2362 {
2363     return ctx->parent;
2364 }
2365 
X509_STORE_CTX_set_cert(X509_STORE_CTX * ctx,X509 * x)2366 void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2367 {
2368     ctx->cert = x;
2369 }
2370 
X509_STORE_CTX_set0_rpk(X509_STORE_CTX * ctx,EVP_PKEY * rpk)2371 void X509_STORE_CTX_set0_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
2372 {
2373     ctx->rpk = rpk;
2374 }
2375 
X509_STORE_CTX_set0_crls(X509_STORE_CTX * ctx,STACK_OF (X509_CRL)* sk)2376 void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2377 {
2378     ctx->crls = sk;
2379 }
2380 
X509_STORE_CTX_set_purpose(X509_STORE_CTX * ctx,int purpose)2381 int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2382 {
2383     /*
2384      * XXX: Why isn't this function always used to set the associated trust?
2385      * Should there even be a VPM->trust field at all?  Or should the trust
2386      * always be inferred from the purpose by X509_STORE_CTX_init().
2387      */
2388     return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2389 }
2390 
X509_STORE_CTX_set_trust(X509_STORE_CTX * ctx,int trust)2391 int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2392 {
2393     /*
2394      * XXX: See above, this function would only be needed when the default
2395      * trust for the purpose needs an override in a corner case.
2396      */
2397     return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2398 }
2399 
2400 /*
2401  * This function is used to set the X509_STORE_CTX purpose and trust values.
2402  * This is intended to be used when another structure has its own trust and
2403  * purpose values which (if set) will be inherited by the ctx. If they aren't
2404  * set then we will usually have a default purpose in mind which should then
2405  * be used to set the trust value. An example of this is SSL use: an SSL
2406  * structure will have its own purpose and trust settings which the
2407  * application can set: if they aren't set then we use the default of SSL
2408  * client/server.
2409  */
X509_STORE_CTX_purpose_inherit(X509_STORE_CTX * ctx,int def_purpose,int purpose,int trust)2410 int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2411     int purpose, int trust)
2412 {
2413     int idx;
2414 
2415     /* If purpose not set use default */
2416     if (purpose == 0)
2417         purpose = def_purpose;
2418     /*
2419      * If purpose is set but we don't have a default then set the default to
2420      * the current purpose
2421      */
2422     else if (def_purpose == 0)
2423         def_purpose = purpose;
2424     /* If we have a purpose then check it is valid */
2425     if (purpose != 0) {
2426         X509_PURPOSE *ptmp;
2427 
2428         idx = X509_PURPOSE_get_by_id(purpose);
2429         if (idx == -1) {
2430             ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2431             return 0;
2432         }
2433         ptmp = X509_PURPOSE_get0(idx);
2434         if (ptmp->trust == X509_TRUST_DEFAULT) {
2435             idx = X509_PURPOSE_get_by_id(def_purpose);
2436             if (idx == -1) {
2437                 ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2438                 return 0;
2439             }
2440             ptmp = X509_PURPOSE_get0(idx);
2441         }
2442         /* If trust not set then get from purpose default */
2443         if (trust == 0)
2444             trust = ptmp->trust;
2445     }
2446     if (trust != 0) {
2447         idx = X509_TRUST_get_by_id(trust);
2448         if (idx == -1) {
2449             ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_TRUST_ID);
2450             return 0;
2451         }
2452     }
2453 
2454     if (ctx->param->purpose == 0 && purpose != 0)
2455         ctx->param->purpose = purpose;
2456     if (ctx->param->trust == 0 && trust != 0)
2457         ctx->param->trust = trust;
2458     return 1;
2459 }
2460 
X509_STORE_CTX_new_ex(OSSL_LIB_CTX * libctx,const char * propq)2461 X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
2462 {
2463     X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2464 
2465     if (ctx == NULL)
2466         return NULL;
2467 
2468     ctx->libctx = libctx;
2469     if (propq != NULL) {
2470         ctx->propq = OPENSSL_strdup(propq);
2471         if (ctx->propq == NULL) {
2472             OPENSSL_free(ctx);
2473             return NULL;
2474         }
2475     }
2476 
2477     return ctx;
2478 }
2479 
X509_STORE_CTX_new(void)2480 X509_STORE_CTX *X509_STORE_CTX_new(void)
2481 {
2482     return X509_STORE_CTX_new_ex(NULL, NULL);
2483 }
2484 
X509_STORE_CTX_free(X509_STORE_CTX * ctx)2485 void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2486 {
2487     if (ctx == NULL)
2488         return;
2489 
2490     X509_STORE_CTX_cleanup(ctx);
2491 
2492     /* libctx and propq survive X509_STORE_CTX_cleanup() */
2493     OPENSSL_free(ctx->propq);
2494     OPENSSL_free(ctx);
2495 }
2496 
X509_STORE_CTX_init_rpk(X509_STORE_CTX * ctx,X509_STORE * store,EVP_PKEY * rpk)2497 int X509_STORE_CTX_init_rpk(X509_STORE_CTX *ctx, X509_STORE *store, EVP_PKEY *rpk)
2498 {
2499     if (!X509_STORE_CTX_init(ctx, store, NULL, NULL))
2500         return 0;
2501     ctx->rpk = rpk;
2502     return 1;
2503 }
2504 
X509_STORE_CTX_init(X509_STORE_CTX * ctx,X509_STORE * store,X509 * x509,STACK_OF (X509)* chain)2505 int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2506     STACK_OF(X509) *chain)
2507 {
2508     if (ctx == NULL) {
2509         ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
2510         return 0;
2511     }
2512     X509_STORE_CTX_cleanup(ctx);
2513 
2514     ctx->store = store;
2515     ctx->cert = x509;
2516     ctx->untrusted = chain;
2517     ctx->crls = NULL;
2518     ctx->num_untrusted = 0;
2519     ctx->other_ctx = NULL;
2520     ctx->valid = 0;
2521     ctx->chain = NULL;
2522     ctx->error = X509_V_OK;
2523     ctx->explicit_policy = 0;
2524     ctx->error_depth = 0;
2525     ctx->current_cert = NULL;
2526     ctx->current_issuer = NULL;
2527     ctx->current_crl = NULL;
2528     ctx->current_crl_score = 0;
2529     ctx->current_reasons = 0;
2530     ctx->tree = NULL;
2531     ctx->parent = NULL;
2532     ctx->dane = NULL;
2533     ctx->bare_ta_signed = 0;
2534     ctx->rpk = NULL;
2535     /* Zero ex_data to make sure we're cleanup-safe */
2536     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2537 
2538     /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2539     if (store != NULL)
2540         ctx->cleanup = store->cleanup;
2541     else
2542         ctx->cleanup = NULL;
2543 
2544     if (store != NULL && store->check_issued != NULL)
2545         ctx->check_issued = store->check_issued;
2546     else
2547         ctx->check_issued = check_issued;
2548 
2549     if (store != NULL && store->get_issuer != NULL)
2550         ctx->get_issuer = store->get_issuer;
2551     else
2552         ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2553 
2554     if (store != NULL && store->verify_cb != NULL)
2555         ctx->verify_cb = store->verify_cb;
2556     else
2557         ctx->verify_cb = null_callback;
2558 
2559     if (store != NULL && store->verify != NULL)
2560         ctx->verify = store->verify;
2561     else
2562         ctx->verify = internal_verify;
2563 
2564     if (store != NULL && store->check_revocation != NULL)
2565         ctx->check_revocation = store->check_revocation;
2566     else
2567         ctx->check_revocation = check_revocation;
2568 
2569     if (store != NULL && store->get_crl != NULL)
2570         ctx->get_crl = store->get_crl;
2571     else
2572         ctx->get_crl = NULL;
2573 
2574     if (store != NULL && store->check_crl != NULL)
2575         ctx->check_crl = store->check_crl;
2576     else
2577         ctx->check_crl = check_crl;
2578 
2579     if (store != NULL && store->cert_crl != NULL)
2580         ctx->cert_crl = store->cert_crl;
2581     else
2582         ctx->cert_crl = cert_crl;
2583 
2584     if (store != NULL && store->check_policy != NULL)
2585         ctx->check_policy = store->check_policy;
2586     else
2587         ctx->check_policy = check_policy;
2588 
2589     if (store != NULL && store->lookup_certs != NULL)
2590         ctx->lookup_certs = store->lookup_certs;
2591     else
2592         ctx->lookup_certs = X509_STORE_CTX_get1_certs;
2593 
2594     if (store != NULL && store->lookup_crls != NULL)
2595         ctx->lookup_crls = store->lookup_crls;
2596     else
2597         ctx->lookup_crls = X509_STORE_CTX_get1_crls;
2598 
2599     ctx->param = X509_VERIFY_PARAM_new();
2600     if (ctx->param == NULL) {
2601         ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2602         goto err;
2603     }
2604 
2605     /* Inherit callbacks and flags from X509_STORE if not set use defaults. */
2606     if (store == NULL)
2607         ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2608     else if (X509_VERIFY_PARAM_inherit(ctx->param, store->param) == 0)
2609         goto err;
2610 
2611     if (!X509_STORE_CTX_set_default(ctx, "default"))
2612         goto err;
2613 
2614     /*
2615      * XXX: For now, continue to inherit trust from VPM, but infer from the
2616      * purpose if this still yields the default value.
2617      */
2618     if (ctx->param->trust == X509_TRUST_DEFAULT) {
2619         int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2620         X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2621 
2622         if (xp != NULL)
2623             ctx->param->trust = X509_PURPOSE_get_trust(xp);
2624     }
2625 
2626     if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2627             &ctx->ex_data))
2628         return 1;
2629     ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
2630 
2631 err:
2632     /*
2633      * On error clean up allocated storage, if the store context was not
2634      * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2635      */
2636     X509_STORE_CTX_cleanup(ctx);
2637     return 0;
2638 }
2639 
2640 /*
2641  * Set alternative get_issuer method: just from a STACK of trusted certificates.
2642  * This avoids the complexity of X509_STORE where it is not needed.
2643  */
X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX * ctx,STACK_OF (X509)* sk)2644 void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2645 {
2646     ctx->other_ctx = sk;
2647     ctx->get_issuer = get1_best_issuer_other_sk;
2648     ctx->lookup_certs = lookup_certs_sk;
2649 }
2650 
X509_STORE_CTX_cleanup(X509_STORE_CTX * ctx)2651 void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2652 {
2653     /*
2654      * We need to be idempotent because, unfortunately, free() also calls
2655      * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2656      * calls cleanup() for the same object twice!  Thus we must zero the
2657      * pointers below after they're freed!
2658      */
2659     /* Seems to always be NULL in OpenSSL, do this at most once. */
2660     if (ctx->cleanup != NULL) {
2661         ctx->cleanup(ctx);
2662         ctx->cleanup = NULL;
2663     }
2664     if (ctx->param != NULL) {
2665         if (ctx->parent == NULL)
2666             X509_VERIFY_PARAM_free(ctx->param);
2667         ctx->param = NULL;
2668     }
2669     X509_policy_tree_free(ctx->tree);
2670     ctx->tree = NULL;
2671     OSSL_STACK_OF_X509_free(ctx->chain);
2672     ctx->chain = NULL;
2673     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2674     memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2675 }
2676 
X509_STORE_CTX_set_depth(X509_STORE_CTX * ctx,int depth)2677 void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2678 {
2679     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2680 }
2681 
X509_STORE_CTX_set_flags(X509_STORE_CTX * ctx,unsigned long flags)2682 void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2683 {
2684     X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2685 }
2686 
X509_STORE_CTX_set_time(X509_STORE_CTX * ctx,unsigned long flags,time_t t)2687 void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2688     time_t t)
2689 {
2690     X509_VERIFY_PARAM_set_time(ctx->param, t);
2691 }
2692 
X509_STORE_CTX_set_current_reasons(X509_STORE_CTX * ctx,unsigned int current_reasons)2693 void X509_STORE_CTX_set_current_reasons(X509_STORE_CTX *ctx,
2694     unsigned int current_reasons)
2695 {
2696     ctx->current_reasons = current_reasons;
2697 }
2698 
X509_STORE_CTX_get0_cert(const X509_STORE_CTX * ctx)2699 X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
2700 {
2701     return ctx->cert;
2702 }
2703 
X509_STORE_CTX_get0_rpk(const X509_STORE_CTX * ctx)2704 EVP_PKEY *X509_STORE_CTX_get0_rpk(const X509_STORE_CTX *ctx)
2705 {
2706     return ctx->rpk;
2707 }
2708 
STACK_OF(X509)2709 STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
2710 {
2711     return ctx->untrusted;
2712 }
2713 
X509_STORE_CTX_set0_untrusted(X509_STORE_CTX * ctx,STACK_OF (X509)* sk)2714 void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2715 {
2716     ctx->untrusted = sk;
2717 }
2718 
X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX * ctx,STACK_OF (X509)* sk)2719 void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2720 {
2721     OSSL_STACK_OF_X509_free(ctx->chain);
2722     ctx->chain = sk;
2723 }
2724 
X509_STORE_CTX_set_verify_cb(X509_STORE_CTX * ctx,X509_STORE_CTX_verify_cb verify_cb)2725 void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
2726     X509_STORE_CTX_verify_cb verify_cb)
2727 {
2728     ctx->verify_cb = verify_cb;
2729 }
2730 
X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX * ctx)2731 X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
2732 {
2733     return ctx->verify_cb;
2734 }
2735 
X509_STORE_CTX_set_verify(X509_STORE_CTX * ctx,X509_STORE_CTX_verify_fn verify)2736 void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
2737     X509_STORE_CTX_verify_fn verify)
2738 {
2739     ctx->verify = verify;
2740 }
2741 
X509_STORE_CTX_get_verify(const X509_STORE_CTX * ctx)2742 X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
2743 {
2744     return ctx->verify;
2745 }
2746 
2747 X509_STORE_CTX_get_issuer_fn
X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX * ctx)2748 X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
2749 {
2750     return ctx->get_issuer;
2751 }
2752 
2753 X509_STORE_CTX_check_issued_fn
X509_STORE_CTX_get_check_issued(const X509_STORE_CTX * ctx)2754 X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
2755 {
2756     return ctx->check_issued;
2757 }
2758 
2759 X509_STORE_CTX_check_revocation_fn
X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX * ctx)2760 X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
2761 {
2762     return ctx->check_revocation;
2763 }
2764 
X509_STORE_CTX_get_get_crl(const X509_STORE_CTX * ctx)2765 X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
2766 {
2767     return ctx->get_crl;
2768 }
2769 
X509_STORE_CTX_set_get_crl(X509_STORE_CTX * ctx,X509_STORE_CTX_get_crl_fn get_crl)2770 void X509_STORE_CTX_set_get_crl(X509_STORE_CTX *ctx,
2771     X509_STORE_CTX_get_crl_fn get_crl)
2772 {
2773     ctx->get_crl = get_crl;
2774 }
2775 
2776 X509_STORE_CTX_check_crl_fn
X509_STORE_CTX_get_check_crl(const X509_STORE_CTX * ctx)2777 X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
2778 {
2779     return ctx->check_crl;
2780 }
2781 
2782 X509_STORE_CTX_cert_crl_fn
X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX * ctx)2783 X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
2784 {
2785     return ctx->cert_crl;
2786 }
2787 
2788 X509_STORE_CTX_check_policy_fn
X509_STORE_CTX_get_check_policy(const X509_STORE_CTX * ctx)2789 X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
2790 {
2791     return ctx->check_policy;
2792 }
2793 
2794 X509_STORE_CTX_lookup_certs_fn
X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX * ctx)2795 X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
2796 {
2797     return ctx->lookup_certs;
2798 }
2799 
2800 X509_STORE_CTX_lookup_crls_fn
X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX * ctx)2801 X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
2802 {
2803     return ctx->lookup_crls;
2804 }
2805 
X509_STORE_CTX_get_cleanup(const X509_STORE_CTX * ctx)2806 X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
2807 {
2808     return ctx->cleanup;
2809 }
2810 
X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX * ctx)2811 X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
2812 {
2813     return ctx->tree;
2814 }
2815 
X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX * ctx)2816 int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
2817 {
2818     return ctx->explicit_policy;
2819 }
2820 
X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX * ctx)2821 int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
2822 {
2823     return ctx->num_untrusted;
2824 }
2825 
X509_STORE_CTX_set_default(X509_STORE_CTX * ctx,const char * name)2826 int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
2827 {
2828     const X509_VERIFY_PARAM *param;
2829 
2830     param = X509_VERIFY_PARAM_lookup(name);
2831     if (param == NULL) {
2832         ERR_raise_data(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID, "name=%s", name);
2833         return 0;
2834     }
2835     return X509_VERIFY_PARAM_inherit(ctx->param, param);
2836 }
2837 
X509_STORE_CTX_get0_param(const X509_STORE_CTX * ctx)2838 X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
2839 {
2840     return ctx->param;
2841 }
2842 
X509_STORE_CTX_set0_param(X509_STORE_CTX * ctx,X509_VERIFY_PARAM * param)2843 void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
2844 {
2845     X509_VERIFY_PARAM_free(ctx->param);
2846     ctx->param = param;
2847 }
2848 
X509_STORE_CTX_set0_dane(X509_STORE_CTX * ctx,SSL_DANE * dane)2849 void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
2850 {
2851     ctx->dane = dane;
2852 }
2853 
dane_i2d(X509 * cert,uint8_t selector,unsigned int * i2dlen)2854 static unsigned char *dane_i2d(X509 *cert, uint8_t selector,
2855     unsigned int *i2dlen)
2856 {
2857     unsigned char *buf = NULL;
2858     int len;
2859 
2860     /*
2861      * Extract ASN.1 DER form of certificate or public key.
2862      */
2863     switch (selector) {
2864     case DANETLS_SELECTOR_CERT:
2865         len = i2d_X509(cert, &buf);
2866         break;
2867     case DANETLS_SELECTOR_SPKI:
2868         len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
2869         break;
2870     default:
2871         ERR_raise(ERR_LIB_X509, X509_R_BAD_SELECTOR);
2872         return NULL;
2873     }
2874 
2875     if (len < 0 || buf == NULL) {
2876         ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2877         return NULL;
2878     }
2879 
2880     *i2dlen = (unsigned int)len;
2881     return buf;
2882 }
2883 
2884 #define DANETLS_NONE 256 /* impossible uint8_t */
2885 
2886 /* Returns -1 on internal error */
dane_match_cert(X509_STORE_CTX * ctx,X509 * cert,int depth)2887 static int dane_match_cert(X509_STORE_CTX *ctx, X509 *cert, int depth)
2888 {
2889     SSL_DANE *dane = ctx->dane;
2890     unsigned usage = DANETLS_NONE;
2891     unsigned selector = DANETLS_NONE;
2892     unsigned ordinal = DANETLS_NONE;
2893     unsigned mtype = DANETLS_NONE;
2894     unsigned char *i2dbuf = NULL;
2895     unsigned int i2dlen = 0;
2896     unsigned char mdbuf[EVP_MAX_MD_SIZE];
2897     unsigned char *cmpbuf = NULL;
2898     unsigned int cmplen = 0;
2899     int i;
2900     int recnum;
2901     int matched = 0;
2902     danetls_record *t = NULL;
2903     uint32_t mask;
2904 
2905     mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
2906 
2907     /* The trust store is not applicable with DANE-TA(2) */
2908     if (depth >= ctx->num_untrusted)
2909         mask &= DANETLS_PKIX_MASK;
2910 
2911     /*
2912      * If we've previously matched a PKIX-?? record, no need to test any
2913      * further PKIX-?? records, it remains to just build the PKIX chain.
2914      * Had the match been a DANE-?? record, we'd be done already.
2915      */
2916     if (dane->mdpth >= 0)
2917         mask &= ~DANETLS_PKIX_MASK;
2918 
2919     /*-
2920      * https://tools.ietf.org/html/rfc7671#section-5.1
2921      * https://tools.ietf.org/html/rfc7671#section-5.2
2922      * https://tools.ietf.org/html/rfc7671#section-5.3
2923      * https://tools.ietf.org/html/rfc7671#section-5.4
2924      *
2925      * We handle DANE-EE(3) records first as they require no chain building
2926      * and no expiration or hostname checks.  We also process digests with
2927      * higher ordinals first and ignore lower priorities except Full(0) which
2928      * is always processed (last).  If none match, we then process PKIX-EE(1).
2929      *
2930      * NOTE: This relies on DANE usages sorting before the corresponding PKIX
2931      * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
2932      * priorities.  See twin comment in ssl/ssl_lib.c.
2933      *
2934      * We expect that most TLSA RRsets will have just a single usage, so we
2935      * don't go out of our way to cache multiple selector-specific i2d buffers
2936      * across usages, but if the selector happens to remain the same as switch
2937      * usages, that's OK.  Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
2938      * records would result in us generating each of the certificate and public
2939      * key DER forms twice, but more typically we'd just see multiple "3 1 1"
2940      * or multiple "3 0 1" records.
2941      *
2942      * As soon as we find a match at any given depth, we stop, because either
2943      * we've matched a DANE-?? record and the peer is authenticated, or, after
2944      * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
2945      * sufficient for DANE, and what remains to do is ordinary PKIX validation.
2946      */
2947     recnum = (dane->umask & mask) != 0 ? sk_danetls_record_num(dane->trecs) : 0;
2948     for (i = 0; matched == 0 && i < recnum; ++i) {
2949         t = sk_danetls_record_value(dane->trecs, i);
2950         if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
2951             continue;
2952         if (t->usage != usage) {
2953             usage = t->usage;
2954 
2955             /* Reset digest agility for each usage/selector pair */
2956             mtype = DANETLS_NONE;
2957             ordinal = dane->dctx->mdord[t->mtype];
2958         }
2959         if (t->selector != selector) {
2960             selector = t->selector;
2961 
2962             /* Update per-selector state */
2963             OPENSSL_free(i2dbuf);
2964             i2dbuf = dane_i2d(cert, selector, &i2dlen);
2965             if (i2dbuf == NULL)
2966                 return -1;
2967 
2968             /* Reset digest agility for each usage/selector pair */
2969             mtype = DANETLS_NONE;
2970             ordinal = dane->dctx->mdord[t->mtype];
2971         } else if (t->mtype != DANETLS_MATCHING_FULL) {
2972             /*-
2973              * Digest agility:
2974              *
2975              *     <https://tools.ietf.org/html/rfc7671#section-9>
2976              *
2977              * For a fixed selector, after processing all records with the
2978              * highest mtype ordinal, ignore all mtypes with lower ordinals
2979              * other than "Full".
2980              */
2981             if (dane->dctx->mdord[t->mtype] < ordinal)
2982                 continue;
2983         }
2984 
2985         /*
2986          * Each time we hit a (new selector or) mtype, re-compute the relevant
2987          * digest, more complex caching is not worth the code space.
2988          */
2989         if (t->mtype != mtype) {
2990             const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
2991 
2992             cmpbuf = i2dbuf;
2993             cmplen = i2dlen;
2994 
2995             if (md != NULL) {
2996                 cmpbuf = mdbuf;
2997                 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
2998                     matched = -1;
2999                     break;
3000                 }
3001             }
3002         }
3003 
3004         /*
3005          * Squirrel away the certificate and depth if we have a match.  Any
3006          * DANE match is dispositive, but with PKIX we still need to build a
3007          * full chain.
3008          */
3009         if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3010             if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
3011                 matched = 1;
3012             if (matched || dane->mdpth < 0) {
3013                 if (!X509_up_ref(cert)) {
3014                     matched = -1;
3015                     break;
3016                 }
3017 
3018                 OPENSSL_free(dane->mcert);
3019                 dane->mcert = cert;
3020                 dane->mdpth = depth;
3021                 dane->mtlsa = t;
3022             }
3023             break;
3024         }
3025     }
3026 
3027     /* Clear the one-element DER cache */
3028     OPENSSL_free(i2dbuf);
3029     return matched;
3030 }
3031 
3032 /* Returns -1 on internal error */
check_dane_issuer(X509_STORE_CTX * ctx,int depth)3033 static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
3034 {
3035     SSL_DANE *dane = ctx->dane;
3036     int matched = 0;
3037     X509 *cert;
3038 
3039     if (!DANETLS_HAS_TA(dane) || depth == 0)
3040         return X509_TRUST_UNTRUSTED;
3041 
3042     /*
3043      * Record any DANE trust anchor matches, for the first depth to test, if
3044      * there's one at that depth. (This'll be false for length 1 chains looking
3045      * for an exact match for the leaf certificate).
3046      */
3047     cert = sk_X509_value(ctx->chain, depth);
3048     if (cert != NULL && (matched = dane_match_cert(ctx, cert, depth)) < 0)
3049         return matched;
3050     if (matched > 0) {
3051         ctx->num_untrusted = depth - 1;
3052         return X509_TRUST_TRUSTED;
3053     }
3054 
3055     return X509_TRUST_UNTRUSTED;
3056 }
3057 
check_dane_pkeys(X509_STORE_CTX * ctx)3058 static int check_dane_pkeys(X509_STORE_CTX *ctx)
3059 {
3060     SSL_DANE *dane = ctx->dane;
3061     danetls_record *t;
3062     int num = ctx->num_untrusted;
3063     X509 *cert = sk_X509_value(ctx->chain, num - 1);
3064     int recnum = sk_danetls_record_num(dane->trecs);
3065     int i;
3066 
3067     for (i = 0; i < recnum; ++i) {
3068         t = sk_danetls_record_value(dane->trecs, i);
3069         if (t->usage != DANETLS_USAGE_DANE_TA || t->selector != DANETLS_SELECTOR_SPKI || t->mtype != DANETLS_MATCHING_FULL || X509_verify(cert, t->spki) <= 0)
3070             continue;
3071 
3072         /* Clear any PKIX-?? matches that failed to extend to a full chain */
3073         X509_free(dane->mcert);
3074         dane->mcert = NULL;
3075 
3076         /* Record match via a bare TA public key */
3077         ctx->bare_ta_signed = 1;
3078         dane->mdpth = num - 1;
3079         dane->mtlsa = t;
3080 
3081         /* Prune any excess chain certificates */
3082         num = sk_X509_num(ctx->chain);
3083         for (; num > ctx->num_untrusted; --num)
3084             X509_free(sk_X509_pop(ctx->chain));
3085 
3086         return X509_TRUST_TRUSTED;
3087     }
3088 
3089     return X509_TRUST_UNTRUSTED;
3090 }
3091 
3092 /*
3093  * Only DANE-EE and SPKI are supported
3094  * Returns -1 on internal error
3095  */
dane_match_rpk(X509_STORE_CTX * ctx,EVP_PKEY * rpk)3096 static int dane_match_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
3097 {
3098     SSL_DANE *dane = ctx->dane;
3099     danetls_record *t = NULL;
3100     int mtype = DANETLS_MATCHING_FULL;
3101     unsigned char *i2dbuf = NULL;
3102     unsigned int i2dlen = 0;
3103     unsigned char mdbuf[EVP_MAX_MD_SIZE];
3104     unsigned char *cmpbuf;
3105     unsigned int cmplen = 0;
3106     int len;
3107     int recnum = sk_danetls_record_num(dane->trecs);
3108     int i;
3109     int matched = 0;
3110 
3111     /* Calculate ASN.1 DER of RPK */
3112     if ((len = i2d_PUBKEY(rpk, &i2dbuf)) <= 0)
3113         return -1;
3114     cmplen = i2dlen = (unsigned int)len;
3115     cmpbuf = i2dbuf;
3116 
3117     for (i = 0; i < recnum; i++) {
3118         t = sk_danetls_record_value(dane->trecs, i);
3119         if (t->usage != DANETLS_USAGE_DANE_EE || t->selector != DANETLS_SELECTOR_SPKI)
3120             continue;
3121 
3122         /* Calculate hash - keep only one around */
3123         if (t->mtype != mtype) {
3124             const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
3125 
3126             cmpbuf = i2dbuf;
3127             cmplen = i2dlen;
3128 
3129             if (md != NULL) {
3130                 cmpbuf = mdbuf;
3131                 if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
3132                     matched = -1;
3133                     break;
3134                 }
3135             }
3136         }
3137         if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3138             matched = 1;
3139             dane->mdpth = 0;
3140             dane->mtlsa = t;
3141             break;
3142         }
3143     }
3144     OPENSSL_free(i2dbuf);
3145     return matched;
3146 }
3147 
dane_reset(SSL_DANE * dane)3148 static void dane_reset(SSL_DANE *dane)
3149 {
3150     /* Reset state to verify another chain, or clear after failure. */
3151     X509_free(dane->mcert);
3152     dane->mcert = NULL;
3153     dane->mtlsa = NULL;
3154     dane->mdpth = -1;
3155     dane->pdpth = -1;
3156 }
3157 
3158 /* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
check_leaf_suiteb(X509_STORE_CTX * ctx,X509 * cert)3159 static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
3160 {
3161     int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
3162 
3163     CB_FAIL_IF(err != X509_V_OK, ctx, cert, 0, err);
3164     return 1;
3165 }
3166 
3167 /* Returns -1 on internal error */
dane_verify_rpk(X509_STORE_CTX * ctx)3168 static int dane_verify_rpk(X509_STORE_CTX *ctx)
3169 {
3170     SSL_DANE *dane = ctx->dane;
3171     int matched;
3172 
3173     dane_reset(dane);
3174 
3175     /*
3176      * Look for a DANE record for RPK
3177      * If error, return -1
3178      * If found, call ctx->verify_cb(1, ctx)
3179      * If not found call ctx->verify_cb(0, ctx)
3180      */
3181     matched = dane_match_rpk(ctx, ctx->rpk);
3182     ctx->error_depth = 0;
3183 
3184     if (matched < 0) {
3185         ctx->error = X509_V_ERR_UNSPECIFIED;
3186         return -1;
3187     }
3188 
3189     if (matched > 0)
3190         ctx->error = X509_V_OK;
3191     else
3192         ctx->error = X509_V_ERR_DANE_NO_MATCH;
3193 
3194     return verify_rpk(ctx);
3195 }
3196 
3197 /* Returns -1 on internal error */
dane_verify(X509_STORE_CTX * ctx)3198 static int dane_verify(X509_STORE_CTX *ctx)
3199 {
3200     X509 *cert = ctx->cert;
3201     SSL_DANE *dane = ctx->dane;
3202     int matched;
3203     int done;
3204 
3205     dane_reset(dane);
3206 
3207     /*-
3208      * When testing the leaf certificate, if we match a DANE-EE(3) record,
3209      * dane_match() returns 1 and we're done.  If however we match a PKIX-EE(1)
3210      * record, the match depth and matching TLSA record are recorded, but the
3211      * return value is 0, because we still need to find a PKIX trust anchor.
3212      * Therefore, when DANE authentication is enabled (required), we're done
3213      * if:
3214      *   + matched < 0, internal error.
3215      *   + matched == 1, we matched a DANE-EE(3) record
3216      *   + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
3217      *     DANE-TA(2) or PKIX-TA(0) to test.
3218      */
3219     matched = dane_match_cert(ctx, ctx->cert, 0);
3220     done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
3221 
3222     if (done && !X509_get_pubkey_parameters(NULL, ctx->chain))
3223         return -1;
3224 
3225     if (matched > 0) {
3226         /* Callback invoked as needed */
3227         if (!check_leaf_suiteb(ctx, cert))
3228             return 0;
3229         /* Callback invoked as needed */
3230         if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 && !check_id(ctx))
3231             return 0;
3232         /* Bypass internal_verify(), issue depth 0 success callback */
3233         ctx->error_depth = 0;
3234         ctx->current_cert = cert;
3235         return ctx->verify_cb(1, ctx);
3236     }
3237 
3238     if (matched < 0) {
3239         ctx->error_depth = 0;
3240         ctx->current_cert = cert;
3241         ctx->error = X509_V_ERR_OUT_OF_MEM;
3242         return -1;
3243     }
3244 
3245     if (done) {
3246         /* Fail early, TA-based success is not possible */
3247         if (!check_leaf_suiteb(ctx, cert))
3248             return 0;
3249         return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
3250     }
3251 
3252     /*
3253      * Chain verification for usages 0/1/2.  TLSA record matching of depth > 0
3254      * certificates happens in-line with building the rest of the chain.
3255      */
3256     return verify_chain(ctx);
3257 }
3258 
3259 /*
3260  * Get trusted issuer, without duplicate suppression
3261  * Returns -1 on internal error.
3262  */
get1_trusted_issuer(X509 ** issuer,X509_STORE_CTX * ctx,X509 * cert)3263 static int get1_trusted_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
3264 {
3265     STACK_OF(X509) *saved_chain = ctx->chain;
3266     int ok;
3267 
3268     ctx->chain = NULL;
3269     ok = ctx->get_issuer(issuer, ctx, cert);
3270     ctx->chain = saved_chain;
3271 
3272     return ok;
3273 }
3274 
3275 /*-
3276  * Returns -1 on internal error.
3277  * Sadly, returns 0 also on internal error in ctx->verify_cb().
3278  */
build_chain(X509_STORE_CTX * ctx)3279 static int build_chain(X509_STORE_CTX *ctx)
3280 {
3281     SSL_DANE *dane = ctx->dane;
3282     int num = sk_X509_num(ctx->chain);
3283     STACK_OF(X509) *sk_untrusted = NULL;
3284     unsigned int search;
3285     int may_trusted = 0;
3286     int may_alternate = 0;
3287     int trust = X509_TRUST_UNTRUSTED;
3288     int alt_untrusted = 0;
3289     int max_depth;
3290     int ok = 0;
3291     int i;
3292 
3293     /* Our chain starts with a single untrusted element. */
3294     if (!ossl_assert(num == 1 && ctx->num_untrusted == num))
3295         goto int_err;
3296 
3297 #define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
3298 #define S_DOTRUSTED (1 << 1) /* Search trusted store */
3299 #define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
3300     /*
3301      * Set up search policy, untrusted if possible, trusted-first if enabled,
3302      * which is the default.
3303      * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
3304      * trust_store, otherwise we might look there first.  If not trusted-first,
3305      * and alternate chains are not disabled, try building an alternate chain
3306      * if no luck with untrusted first.
3307      */
3308     search = ctx->untrusted != NULL ? S_DOUNTRUSTED : 0;
3309     if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
3310         if (search == 0 || (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) != 0)
3311             search |= S_DOTRUSTED;
3312         else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
3313             may_alternate = 1;
3314         may_trusted = 1;
3315     }
3316 
3317     /* Initialize empty untrusted stack. */
3318     if ((sk_untrusted = sk_X509_new_null()) == NULL) {
3319         ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3320         goto memerr;
3321     }
3322 
3323     /*
3324      * If we got any "Cert(0) Full(0)" trust anchors from DNS, *prepend* them
3325      * to our working copy of the untrusted certificate stack.
3326      */
3327     if (DANETLS_ENABLED(dane) && dane->certs != NULL
3328         && !X509_add_certs(sk_untrusted, dane->certs, X509_ADD_FLAG_DEFAULT)) {
3329         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3330         goto memerr;
3331     }
3332 
3333     /*
3334      * Shallow-copy the stack of untrusted certificates (with TLS, this is
3335      * typically the content of the peer's certificate message) so we can make
3336      * multiple passes over it, while free to remove elements as we go.
3337      */
3338     if (!X509_add_certs(sk_untrusted, ctx->untrusted, X509_ADD_FLAG_DEFAULT)) {
3339         ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3340         goto memerr;
3341     }
3342 
3343     /*
3344      * Still absurdly large, but arithmetically safe, a lower hard upper bound
3345      * might be reasonable.
3346      */
3347     if (ctx->param->depth > INT_MAX / 2)
3348         ctx->param->depth = INT_MAX / 2;
3349 
3350     /*
3351      * Try to extend the chain until we reach an ultimately trusted issuer.
3352      * Build chains up to one longer the limit, later fail if we hit the limit,
3353      * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3354      */
3355     max_depth = ctx->param->depth + 1;
3356 
3357     while (search != 0) {
3358         X509 *curr, *issuer = NULL;
3359 
3360         num = sk_X509_num(ctx->chain);
3361         ctx->error_depth = num - 1;
3362         /*
3363          * Look in the trust store if enabled for first lookup, or we've run
3364          * out of untrusted issuers and search here is not disabled.  When we
3365          * reach the depth limit, we stop extending the chain, if by that point
3366          * we've not found a trust anchor, any trusted chain would be too long.
3367          *
3368          * The error reported to the application verify callback is at the
3369          * maximal valid depth with the current certificate equal to the last
3370          * not ultimately-trusted issuer.  For example, with verify_depth = 0,
3371          * the callback will report errors at depth=1 when the immediate issuer
3372          * of the leaf certificate is not a trust anchor.  No attempt will be
3373          * made to locate an issuer for that certificate, since such a chain
3374          * would be a-priori too long.
3375          */
3376         if ((search & S_DOTRUSTED) != 0) {
3377             i = num;
3378             if ((search & S_DOALTERNATE) != 0) {
3379                 /*
3380                  * As high up the chain as we can, look for an alternative
3381                  * trusted issuer of an untrusted certificate that currently
3382                  * has an untrusted issuer.  We use the alt_untrusted variable
3383                  * to track how far up the chain we find the first match.  It
3384                  * is only if and when we find a match, that we prune the chain
3385                  * and reset ctx->num_untrusted to the reduced count of
3386                  * untrusted certificates.  While we're searching for such a
3387                  * match (which may never be found), it is neither safe nor
3388                  * wise to preemptively modify either the chain or
3389                  * ctx->num_untrusted.
3390                  *
3391                  * Note, like ctx->num_untrusted, alt_untrusted is a count of
3392                  * untrusted certificates, not a "depth".
3393                  */
3394                 i = alt_untrusted;
3395             }
3396             curr = sk_X509_value(ctx->chain, i - 1);
3397 
3398             /* Note: get1_trusted_issuer() must be used even if self-signed. */
3399             ok = num > max_depth ? 0 : get1_trusted_issuer(&issuer, ctx, curr);
3400 
3401             if (ok < 0) {
3402                 trust = -1;
3403                 ctx->error = X509_V_ERR_STORE_LOOKUP;
3404                 break;
3405             }
3406 
3407             if (ok > 0) {
3408                 int self_signed = X509_self_signed(curr, 0);
3409 
3410                 if (self_signed < 0) {
3411                     X509_free(issuer);
3412                     goto int_err;
3413                 }
3414                 /*
3415                  * Alternative trusted issuer for a mid-chain untrusted cert?
3416                  * Pop the untrusted cert's successors and retry.  We might now
3417                  * be able to complete a valid chain via the trust store.  Note
3418                  * that despite the current trust store match we might still
3419                  * fail complete the chain to a suitable trust anchor, in which
3420                  * case we may prune some more untrusted certificates and try
3421                  * again.  Thus the S_DOALTERNATE bit may yet be turned on
3422                  * again with an even shorter untrusted chain!
3423                  *
3424                  * If in the process we threw away our matching PKIX-TA trust
3425                  * anchor, reset DANE trust.  We might find a suitable trusted
3426                  * certificate among the ones from the trust store.
3427                  */
3428                 if ((search & S_DOALTERNATE) != 0) {
3429                     if (!ossl_assert(num > i && i > 0 && !self_signed)) {
3430                         X509_free(issuer);
3431                         goto int_err;
3432                     }
3433                     search &= ~S_DOALTERNATE;
3434                     for (; num > i; --num)
3435                         X509_free(sk_X509_pop(ctx->chain));
3436                     ctx->num_untrusted = num;
3437 
3438                     if (DANETLS_ENABLED(dane) && dane->mdpth >= ctx->num_untrusted) {
3439                         dane->mdpth = -1;
3440                         X509_free(dane->mcert);
3441                         dane->mcert = NULL;
3442                     }
3443                     if (DANETLS_ENABLED(dane) && dane->pdpth >= ctx->num_untrusted)
3444                         dane->pdpth = -1;
3445                 }
3446 
3447                 if (!self_signed) { /* untrusted not self-signed certificate */
3448                     /* Grow the chain by trusted issuer */
3449                     if (!sk_X509_push(ctx->chain, issuer)) {
3450                         X509_free(issuer);
3451                         ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3452                         goto memerr;
3453                     }
3454                     if ((self_signed = X509_self_signed(issuer, 0)) < 0)
3455                         goto int_err;
3456                 } else {
3457                     /*
3458                      * We have a self-signed untrusted cert that has the same
3459                      * subject name (and perhaps keyid and/or serial number) as
3460                      * a trust anchor.  We must have an exact match to avoid
3461                      * possible impersonation via key substitution etc.
3462                      */
3463                     if (X509_cmp(curr, issuer) != 0) {
3464                         /* Self-signed untrusted mimic. */
3465                         X509_free(issuer);
3466                         ok = 0;
3467                     } else { /* curr "==" issuer */
3468                         /*
3469                          * Replace self-signed untrusted certificate
3470                          * by its trusted matching issuer.
3471                          */
3472                         X509_free(curr);
3473                         ctx->num_untrusted = --num;
3474                         (void)sk_X509_set(ctx->chain, num, issuer);
3475                     }
3476                 }
3477 
3478                 /*
3479                  * We've added a new trusted certificate to the chain, re-check
3480                  * trust.  If not done, and not self-signed look deeper.
3481                  * Whether or not we're doing "trusted first", we no longer
3482                  * look for untrusted certificates from the peer's chain.
3483                  *
3484                  * At this point ctx->num_trusted and num must reflect the
3485                  * correct number of untrusted certificates, since the DANE
3486                  * logic in check_trust() depends on distinguishing CAs from
3487                  * "the wire" from CAs from the trust store.  In particular, the
3488                  * certificate at depth "num" should be the new trusted
3489                  * certificate with ctx->num_untrusted <= num.
3490                  */
3491                 if (ok) {
3492                     if (!ossl_assert(ctx->num_untrusted <= num))
3493                         goto int_err;
3494                     search &= ~S_DOUNTRUSTED;
3495                     trust = check_trust(ctx, num);
3496                     if (trust != X509_TRUST_UNTRUSTED)
3497                         break;
3498                     if (!self_signed)
3499                         continue;
3500                 }
3501             }
3502 
3503             /*
3504              * No dispositive decision, and either self-signed or no match, if
3505              * we were doing untrusted-first, and alt-chains are not disabled,
3506              * do that, by repeatedly losing one untrusted element at a time,
3507              * and trying to extend the shorted chain.
3508              */
3509             if ((search & S_DOUNTRUSTED) == 0) {
3510                 /* Continue search for a trusted issuer of a shorter chain? */
3511                 if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3512                     continue;
3513                 /* Still no luck and no fallbacks left? */
3514                 if (!may_alternate || (search & S_DOALTERNATE) != 0 || ctx->num_untrusted < 2)
3515                     break;
3516                 /* Search for a trusted issuer of a shorter chain */
3517                 search |= S_DOALTERNATE;
3518                 alt_untrusted = ctx->num_untrusted - 1;
3519             }
3520         }
3521 
3522         /*
3523          * Try to extend chain with peer-provided untrusted certificate
3524          */
3525         if ((search & S_DOUNTRUSTED) != 0) {
3526             num = sk_X509_num(ctx->chain);
3527             if (!ossl_assert(num == ctx->num_untrusted))
3528                 goto int_err;
3529             curr = sk_X509_value(ctx->chain, num - 1);
3530             issuer = (X509_self_signed(curr, 0) > 0 || num > max_depth) ? NULL : get0_best_issuer_sk(ctx, 0, 1 /* no_dup */, sk_untrusted, curr);
3531             if (issuer == NULL) {
3532                 /*
3533                  * Once we have reached a self-signed cert or num > max_depth
3534                  * or can't find an issuer in the untrusted list we stop looking
3535                  * there and start looking only in the trust store if enabled.
3536                  */
3537                 search &= ~S_DOUNTRUSTED;
3538                 if (may_trusted)
3539                     search |= S_DOTRUSTED;
3540                 continue;
3541             }
3542 
3543             /* Drop this issuer from future consideration */
3544             (void)sk_X509_delete_ptr(sk_untrusted, issuer);
3545 
3546             /* Grow the chain by untrusted issuer */
3547             if (!X509_add_cert(ctx->chain, issuer, X509_ADD_FLAG_UP_REF))
3548                 goto int_err;
3549 
3550             ++ctx->num_untrusted;
3551 
3552             /* Check for DANE-TA trust of the topmost untrusted certificate. */
3553             trust = check_dane_issuer(ctx, ctx->num_untrusted - 1);
3554             if (trust == X509_TRUST_TRUSTED || trust == X509_TRUST_REJECTED)
3555                 break;
3556         }
3557     }
3558     sk_X509_free(sk_untrusted);
3559 
3560     if (trust < 0) /* internal error */
3561         return trust;
3562 
3563     /*
3564      * Last chance to make a trusted chain, either bare DANE-TA public-key
3565      * signers, or else direct leaf PKIX trust.
3566      */
3567     num = sk_X509_num(ctx->chain);
3568     if (num <= max_depth) {
3569         if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3570             trust = check_dane_pkeys(ctx);
3571         if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3572             trust = check_trust(ctx, num);
3573     }
3574 
3575     switch (trust) {
3576     case X509_TRUST_TRUSTED:
3577         return 1;
3578     case X509_TRUST_REJECTED:
3579         /* Callback already issued */
3580         return 0;
3581     case X509_TRUST_UNTRUSTED:
3582     default:
3583         switch (ctx->error) {
3584         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
3585         case X509_V_ERR_CERT_NOT_YET_VALID:
3586         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
3587         case X509_V_ERR_CERT_HAS_EXPIRED:
3588             return 0; /* Callback already done by ossl_x509_check_cert_time() */
3589         default: /* A preliminary error has become final */
3590             return verify_cb_cert(ctx, NULL, num - 1, ctx->error);
3591         case X509_V_OK:
3592             break;
3593         }
3594         CB_FAIL_IF(num > max_depth,
3595             ctx, NULL, num - 1, X509_V_ERR_CERT_CHAIN_TOO_LONG);
3596         CB_FAIL_IF(DANETLS_ENABLED(dane)
3597                 && (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0),
3598             ctx, NULL, num - 1, X509_V_ERR_DANE_NO_MATCH);
3599         if (X509_self_signed(sk_X509_value(ctx->chain, num - 1), 0) > 0)
3600             return verify_cb_cert(ctx, NULL, num - 1,
3601                 num == 1
3602                     ? X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
3603                     : X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
3604         return verify_cb_cert(ctx, NULL, num - 1,
3605             ctx->num_untrusted < num
3606                 ? X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
3607                 : X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
3608     }
3609 
3610 int_err:
3611     ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
3612     ctx->error = X509_V_ERR_UNSPECIFIED;
3613     sk_X509_free(sk_untrusted);
3614     return -1;
3615 
3616 memerr:
3617     ctx->error = X509_V_ERR_OUT_OF_MEM;
3618     sk_X509_free(sk_untrusted);
3619     return -1;
3620 }
3621 
STACK_OF(X509)3622 STACK_OF(X509) *X509_build_chain(X509 *target, STACK_OF(X509) *certs,
3623     X509_STORE *store, int with_self_signed,
3624     OSSL_LIB_CTX *libctx, const char *propq)
3625 {
3626     int finish_chain = store != NULL;
3627     X509_STORE_CTX *ctx;
3628     int flags = X509_ADD_FLAG_UP_REF;
3629     STACK_OF(X509) *result = NULL;
3630 
3631     if (target == NULL) {
3632         ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
3633         return NULL;
3634     }
3635 
3636     if ((ctx = X509_STORE_CTX_new_ex(libctx, propq)) == NULL)
3637         return NULL;
3638     if (!X509_STORE_CTX_init(ctx, store, target, finish_chain ? certs : NULL))
3639         goto err;
3640     if (!finish_chain)
3641         X509_STORE_CTX_set0_trusted_stack(ctx, certs);
3642     if (!ossl_x509_add_cert_new(&ctx->chain, target, X509_ADD_FLAG_UP_REF)) {
3643         ctx->error = X509_V_ERR_OUT_OF_MEM;
3644         goto err;
3645     }
3646     ctx->num_untrusted = 1;
3647 
3648     if (!build_chain(ctx) && finish_chain)
3649         goto err;
3650 
3651     /* result list to store the up_ref'ed certificates */
3652     if (sk_X509_num(ctx->chain) > 1 && !with_self_signed)
3653         flags |= X509_ADD_FLAG_NO_SS;
3654     if (!ossl_x509_add_certs_new(&result, ctx->chain, flags)) {
3655         sk_X509_free(result);
3656         result = NULL;
3657     }
3658 
3659 err:
3660     X509_STORE_CTX_free(ctx);
3661     return result;
3662 }
3663 
3664 /*
3665  * note that there's a corresponding minbits_table in ssl/ssl_cert.c
3666  * in ssl_get_security_level_bits that's used for selection of DH parameters
3667  */
3668 static const int minbits_table[] = { 80, 112, 128, 192, 256 };
3669 static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
3670 
3671 /*-
3672  * Check whether the given public key meets the security level of `ctx`.
3673  * Returns 1 on success, 0 otherwise.
3674  */
check_key_level(X509_STORE_CTX * ctx,EVP_PKEY * pkey)3675 static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey)
3676 {
3677     int level = ctx->param->auth_level;
3678 
3679     /*
3680      * At security level zero, return without checking for a supported public
3681      * key type.  Some engines support key types not understood outside the
3682      * engine, and we only need to understand the key when enforcing a security
3683      * floor.
3684      */
3685     if (level <= 0)
3686         return 1;
3687 
3688     /* Unsupported or malformed keys are not secure */
3689     if (pkey == NULL)
3690         return 0;
3691 
3692     if (level > NUM_AUTH_LEVELS)
3693         level = NUM_AUTH_LEVELS;
3694 
3695     return EVP_PKEY_get_security_bits(pkey) >= minbits_table[level - 1];
3696 }
3697 
3698 /*-
3699  * Check whether the public key of `cert` meets the security level of `ctx`.
3700  * Returns 1 on success, 0 otherwise.
3701  */
check_cert_key_level(X509_STORE_CTX * ctx,X509 * cert)3702 static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert)
3703 {
3704     return check_key_level(ctx, X509_get0_pubkey(cert));
3705 }
3706 
3707 /*-
3708  * Check whether the public key of ``cert`` does not use explicit params
3709  * for an elliptic curve.
3710  *
3711  * Returns 1 on success, 0 if check fails, -1 for other errors.
3712  */
check_curve(X509 * cert)3713 static int check_curve(X509 *cert)
3714 {
3715     EVP_PKEY *pkey = X509_get0_pubkey(cert);
3716     int ret, val;
3717 
3718     /* Unsupported or malformed key */
3719     if (pkey == NULL)
3720         return -1;
3721     if (EVP_PKEY_get_id(pkey) != EVP_PKEY_EC)
3722         return 1;
3723 
3724     ret = EVP_PKEY_get_int_param(pkey,
3725         OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS,
3726         &val);
3727     return ret == 1 ? !val : -1;
3728 }
3729 
3730 /*-
3731  * Check whether the signature digest algorithm of ``cert`` meets the security
3732  * level of ``ctx``.  Should not be checked for trust anchors (whether
3733  * self-signed or otherwise).
3734  *
3735  * Returns 1 on success, 0 otherwise.
3736  */
check_sig_level(X509_STORE_CTX * ctx,X509 * cert)3737 static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
3738 {
3739     int secbits = -1;
3740     int level = ctx->param->auth_level;
3741 
3742     if (level <= 0)
3743         return 1;
3744     if (level > NUM_AUTH_LEVELS)
3745         level = NUM_AUTH_LEVELS;
3746 
3747     if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
3748         return 0;
3749 
3750     return secbits >= minbits_table[level - 1];
3751 }
3752