Coverage Report

Created: 2026-09-12 06:55

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