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