Coverage Report

Created: 2026-10-28 06:28

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
10.0k
#define CRL_SCORE_NOCRITICAL 0x100 /* No unhandled critical extensions */
35
12.8k
#define CRL_SCORE_SCOPE 0x080 /* certificate is within CRL scope */
36
13.6k
#define CRL_SCORE_TIME 0x040 /* CRL times valid */
37
9.11k
#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
7.09k
    (CRL_SCORE_NOCRITICAL | CRL_SCORE_TIME | CRL_SCORE_SCOPE)
40
2.52k
#define CRL_SCORE_ISSUER_CERT 0x018 /* CRL issuer is certificate issuer */
41
2.82k
#define CRL_SCORE_SAME_PATH 0x008 /* CRL issuer is on certificate path */
42
6.22k
#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
63.3k
{
90
63.3k
    return ok;
91
63.3k
}
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
109k
{
102
109k
    EVP_PKEY *pkey;
103
104
109k
    if ((pkey = X509_get0_pubkey(cert)) == NULL) { /* handles cert == NULL */
105
4.90k
        ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
106
4.90k
        return -1;
107
4.90k
    }
108
104k
    if (!ossl_x509v3_cache_extensions(cert))
109
39.9k
        return -1;
110
65.0k
    if ((cert->ex_flags & EXFLAG_SS) == 0)
111
37.2k
        return 0;
112
27.8k
    if (!verify_signature)
113
27.8k
        return 1;
114
0
    return X509_verify(cert, pkey);
115
27.8k
}
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.85k
{
123
3.85k
    STACK_OF(X509) *certs;
124
3.85k
    X509 *xtmp = NULL;
125
3.85k
    int i, ret;
126
127
3.85k
    *result = NULL;
128
    /* Lookup all certs with matching subject name */
129
3.85k
    ERR_set_mark();
130
3.85k
    certs = ctx->lookup_certs(ctx, X509_get_subject_name(x));
131
3.85k
    ERR_pop_to_mark();
132
3.85k
    if (certs == NULL)
133
0
        return -1;
134
135
    /* Look for exact match */
136
5.36k
    for (i = 0; i < sk_X509_num(certs); i++) {
137
1.52k
        xtmp = sk_X509_value(certs, i);
138
1.52k
        if (X509_cmp(xtmp, x) == 0)
139
12
            break;
140
1.51k
        xtmp = NULL;
141
1.51k
    }
142
3.85k
    ret = xtmp != NULL;
143
3.85k
    if (ret) {
144
12
        if (!X509_up_ref(xtmp))
145
0
            ret = -1;
146
12
        else
147
12
            *result = xtmp;
148
12
    }
149
3.85k
    OSSL_STACK_OF_X509_free(certs);
150
3.85k
    return ret;
151
3.85k
}
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
84.9k
{
164
84.9k
    if (depth < 0)
165
0
        depth = ctx->error_depth;
166
84.9k
    else
167
84.9k
        ctx->error_depth = depth;
168
84.9k
    ctx->current_cert = x != NULL ? x : sk_X509_value(ctx->chain, depth);
169
84.9k
    if (err != X509_V_OK)
170
84.9k
        ctx->error = err;
171
84.9k
    return ctx->verify_cb(0, ctx);
172
84.9k
}
173
174
#define CB_FAIL_IF(cond, ctx, cert, depth, err)               \
175
267k
    if ((cond) && verify_cb_cert(ctx, cert, depth, err) == 0) \
176
267k
    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
7.33k
{
187
7.33k
    ctx->error = err;
188
7.33k
    return ctx->verify_cb(0, ctx);
189
7.33k
}
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
7.26k
{
211
7.26k
    int i;
212
7.26k
    int num = sk_X509_num(ctx->chain);
213
214
7.26k
    if (ctx->param->auth_level <= 0)
215
7.26k
        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
69.4k
{
255
69.4k
    int err;
256
69.4k
    int ok;
257
258
69.4k
    if ((ok = build_chain(ctx)) <= 0
259
7.26k
        || (ok = check_extensions(ctx)) <= 0
260
7.26k
        || (ok = check_auth_level(ctx)) <= 0
261
7.26k
        || (ok = check_id(ctx)) <= 0
262
7.26k
        || (ok = X509_get_pubkey_parameters(NULL, ctx->chain) ? 1 : -1) <= 0
263
5.50k
        || (ok = ctx->check_revocation(ctx)) <= 0)
264
63.9k
        return ok;
265
266
5.50k
    err = X509_chain_check_suiteb(&ctx->error_depth, NULL, ctx->chain,
267
5.50k
        ctx->param->flags);
268
5.50k
    CB_FAIL_IF(err != X509_V_OK, ctx, NULL, ctx->error_depth, err);
269
270
    /* Verify chain signatures and expiration times */
271
5.50k
    ok = ctx->verify != NULL ? ctx->verify(ctx) : internal_verify(ctx);
272
5.50k
    if (ok <= 0)
273
0
        return ok;
274
275
5.50k
    if ((ok = check_name_constraints(ctx)) <= 0)
276
6
        return ok;
277
278
5.49k
#ifndef OPENSSL_NO_RFC3779
279
    /* RFC 3779 path validation, now that CRL check has been done */
280
5.49k
    if ((ok = X509v3_asid_validate_path(ctx)) <= 0)
281
0
        return ok;
282
5.49k
    if ((ok = X509v3_addr_validate_path(ctx)) <= 0)
283
34
        return ok;
284
5.46k
#endif
285
286
    /* If we get this far evaluate policies */
287
5.46k
    if ((ctx->param->flags & X509_V_FLAG_POLICY_CHECK) != 0)
288
0
        ok = ctx->check_policy(ctx);
289
5.46k
    return ok;
290
5.49k
}
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
70.6k
{
307
70.6k
    if (ctx == NULL) {
308
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
309
0
        return -1;
310
0
    }
311
70.6k
    return (ctx->rpk != NULL) ? x509_verify_rpk(ctx) : x509_verify_x509(ctx);
312
70.6k
}
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
70.6k
{
348
70.6k
    int ret;
349
350
70.6k
    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
70.6k
    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
70.6k
    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
70.6k
    ctx->num_untrusted = 1;
371
372
    /* If the peer's public key is too weak, we can stop early. */
373
70.6k
    CB_FAIL_IF(!check_cert_key_level(ctx, ctx->cert),
374
70.6k
        ctx, ctx->cert, 0, X509_V_ERR_EE_KEY_TOO_SMALL);
375
376
69.4k
    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
69.4k
    if (ret <= 0 && ctx->error == X509_V_OK)
384
11
        ctx->error = X509_V_ERR_UNSPECIFIED;
385
69.4k
    return ret;
386
70.6k
}
387
388
static int sk_X509_contains(STACK_OF(X509) *sk, X509 *cert)
389
30.6k
{
390
30.6k
    int i, n = sk_X509_num(sk);
391
392
37.5k
    for (i = 0; i < n; i++)
393
31.5k
        if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
394
24.6k
            return 1;
395
5.98k
    return 0;
396
30.6k
}
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
31.1k
{
415
31.1k
    int i;
416
31.1k
    X509 *candidate, *issuer = NULL;
417
418
67.9k
    for (i = 0; i < sk_X509_num(sk); i++) {
419
36.9k
        candidate = sk_X509_value(sk, i);
420
36.9k
        if (no_dup
421
34.8k
            && !((x->ex_flags & EXFLAG_SI) != 0 && sk_X509_num(ctx->chain) == 1)
422
30.4k
            && sk_X509_contains(ctx->chain, candidate))
423
24.6k
            continue;
424
12.2k
        if (ctx->check_issued(ctx, x, candidate)) {
425
1.05k
            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
1.05k
            if (ossl_x509_check_cert_time(ctx, candidate, -1))
430
112
                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
938
            if (issuer == NULL
436
301
                || ASN1_TIME_compare(X509_get0_notAfter(candidate),
437
301
                       X509_get0_notAfter(issuer))
438
301
                    > 0)
439
662
                issuer = candidate;
440
938
        }
441
12.2k
    }
442
31.0k
    return issuer;
443
31.1k
}
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
85.1k
{
456
85.1k
    const X509_NAME *xn = X509_get_issuer_name(x);
457
85.1k
    X509_OBJECT *obj = X509_OBJECT_new();
458
85.1k
    STACK_OF(X509) *certs;
459
85.1k
    int ret;
460
461
85.1k
    *issuer = NULL;
462
85.1k
    if (obj == NULL)
463
0
        return -1;
464
85.1k
    ret = ossl_x509_store_ctx_get_by_subject(ctx, X509_LU_X509, xn, obj);
465
85.1k
    if (ret != 1)
466
80.1k
        goto end;
467
468
    /* quick happy path: certificate matches and is currently valid */
469
4.96k
    if (ctx->check_issued(ctx, x, obj->data.x509)) {
470
2.86k
        if (ossl_x509_check_cert_time(ctx, obj->data.x509, -1)) {
471
2.86k
            *issuer = obj->data.x509;
472
            /* |*issuer| has taken over the cert reference from |obj| */
473
2.86k
            obj->type = X509_LU_NONE;
474
2.86k
            goto end;
475
2.86k
        }
476
2.86k
    }
477
478
2.10k
    ret = -1;
479
2.10k
    if ((certs = X509_STORE_CTX_get1_certs(ctx, xn)) == NULL)
480
0
        goto end;
481
2.10k
    *issuer = get0_best_issuer_sk(ctx, 0, 0 /* allow duplicates */, certs, x);
482
2.10k
    ret = 0;
483
2.10k
    if (*issuer != NULL)
484
0
        ret = X509_up_ref(*issuer) ? 1 : -1;
485
2.10k
    OSSL_STACK_OF_X509_free(certs);
486
85.1k
end:
487
85.1k
    X509_OBJECT_free(obj);
488
85.1k
    return ret;
489
2.10k
}
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
27.2k
{
494
27.2k
    int err = ossl_x509_likely_issued(issuer, x);
495
496
27.2k
    if (err == X509_V_OK)
497
4.77k
        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
22.5k
    return 0;
503
27.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
543
{
550
543
    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
543
    if (depth >= ctx->num_untrusted && purpose == ctx->param->purpose)
571
143
        tr_ok = X509_check_trust(x, ctx->param->trust, X509_TRUST_NO_SS_COMPAT);
572
573
543
    switch (tr_ok) {
574
0
    case X509_TRUST_TRUSTED:
575
0
        return 1;
576
0
    case X509_TRUST_REJECTED:
577
0
        break;
578
543
    default: /* can only be X509_TRUST_UNTRUSTED */
579
543
        switch (X509_check_purpose(x, purpose, must_be_ca > 0)) {
580
322
        case 1:
581
322
            return 1;
582
164
        case 0:
583
164
            break;
584
57
        default:
585
57
            if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) == 0)
586
0
                return 1;
587
543
        }
588
221
        break;
589
543
    }
590
591
221
    return verify_cb_cert(ctx, x, depth, X509_V_ERR_INVALID_PURPOSE);
592
543
}
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.71k
{
600
2.71k
    int i, must_be_ca, plen = 0;
601
2.71k
    X509 *x;
602
2.71k
    int ret, proxy_path_length = 0;
603
2.71k
    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.71k
    must_be_ca = -1;
615
616
    /* CRL path validation */
617
2.71k
    if (ctx->parent != NULL) {
618
0
        allow_proxy_certs = 0;
619
0
        purpose = X509_PURPOSE_CRL_SIGN;
620
2.71k
    } else {
621
2.71k
        allow_proxy_certs = (ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS) != 0;
622
2.71k
        purpose = ctx->param->purpose;
623
2.71k
    }
624
625
6.83k
    for (i = 0; i < num; i++) {
626
4.12k
        x = sk_X509_value(ctx->chain, i);
627
4.12k
        CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
628
4.12k
                && (x->ex_flags & EXFLAG_CRITICAL) != 0,
629
4.12k
            ctx, x, i, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION);
630
4.12k
        CB_FAIL_IF(!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY) != 0,
631
4.12k
            ctx, x, i, X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED);
632
4.12k
        ret = X509_check_ca(x);
633
4.12k
        switch (must_be_ca) {
634
2.71k
        case -1:
635
2.71k
            CB_FAIL_IF((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
636
2.71k
                    && ret != 1 && ret != 0,
637
2.71k
                ctx, x, i, X509_V_ERR_INVALID_CA);
638
2.71k
            break;
639
2.71k
        case 0:
640
2
            CB_FAIL_IF(ret != 0, ctx, x, i, X509_V_ERR_INVALID_NON_CA);
641
2
            break;
642
1.41k
        default:
643
            /* X509_V_FLAG_X509_STRICT is implicit for intermediate CAs */
644
1.41k
            CB_FAIL_IF(ret == 0
645
1.41k
                    || ((i + 1 < num
646
1.41k
                            || (ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0)
647
1.41k
                        && ret != 1),
648
1.41k
                ctx, x, i, X509_V_ERR_INVALID_CA);
649
1.41k
            break;
650
4.12k
        }
651
4.12k
        if (num > 1) {
652
            /* Check for presence of explicit elliptic curve parameters */
653
2.81k
            ret = check_curve(x);
654
2.81k
            CB_FAIL_IF(ret < 0, ctx, x, i, X509_V_ERR_UNSPECIFIED);
655
2.81k
            CB_FAIL_IF(ret == 0, ctx, x, i, X509_V_ERR_EC_KEY_EXPLICIT_PARAMS);
656
2.81k
        }
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
4.12k
        if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) != 0
663
4.12k
            && 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.81k
            if (x->ex_pathlen != -1) {
670
19
                CB_FAIL_IF((x->ex_flags & EXFLAG_CA) == 0,
671
19
                    ctx, x, i, X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA);
672
19
                CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) == 0, ctx,
673
19
                    x, i, X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN);
674
19
            }
675
2.81k
            CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0
676
2.81k
                    && (x->ex_flags & EXFLAG_BCONS) != 0
677
2.81k
                    && (x->ex_flags & EXFLAG_BCONS_CRITICAL) == 0,
678
2.81k
                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.81k
            if ((x->ex_flags & EXFLAG_CA) != 0) {
681
219
                CB_FAIL_IF((x->ex_flags & EXFLAG_KUSAGE) == 0,
682
219
                    ctx, x, i, X509_V_ERR_CA_CERT_MISSING_KEY_USAGE);
683
2.59k
            } else {
684
2.59k
                CB_FAIL_IF((x->ex_kusage & KU_KEY_CERT_SIGN) != 0, ctx, x, i,
685
2.59k
                    X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA);
686
2.59k
            }
687
            /* Check issuer is non-empty acc. to RFC 5280 section 4.1.2.4 */
688
2.81k
            CB_FAIL_IF(X509_NAME_entry_count(X509_get_issuer_name(x)) == 0,
689
2.81k
                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.81k
            CB_FAIL_IF(((x->ex_flags & EXFLAG_CA) != 0
692
2.81k
                           || (x->ex_kusage & KU_CRL_SIGN) != 0
693
2.81k
                           || x->altname == NULL)
694
2.81k
                    && X509_NAME_entry_count(X509_get_subject_name(x)) == 0,
695
2.81k
                ctx, x, i, X509_V_ERR_SUBJECT_NAME_EMPTY);
696
2.81k
            CB_FAIL_IF(X509_NAME_entry_count(X509_get_subject_name(x)) == 0
697
2.81k
                    && x->altname != NULL
698
2.81k
                    && (x->ex_flags & EXFLAG_SAN_CRITICAL) == 0,
699
2.81k
                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.81k
            CB_FAIL_IF(x->altname != NULL
702
2.81k
                    && sk_GENERAL_NAME_num(x->altname) <= 0,
703
2.81k
                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.81k
            CB_FAIL_IF(X509_ALGOR_cmp(&x->sig_alg, &x->cert_info.signature) != 0,
706
2.81k
                ctx, x, i, X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY);
707
2.81k
            CB_FAIL_IF(x->akid != NULL
708
2.81k
                    && (x->ex_flags & EXFLAG_AKID_CRITICAL) != 0,
709
2.81k
                ctx, x, i, X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL);
710
2.81k
            CB_FAIL_IF(x->skid != NULL
711
2.81k
                    && (x->ex_flags & EXFLAG_SKID_CRITICAL) != 0,
712
2.81k
                ctx, x, i, X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL);
713
2.81k
            if (X509_get_version(x) >= X509_VERSION_3) {
714
                /* Check AKID presence acc. to RFC 5280 section 4.2.1.1 */
715
1.93k
                CB_FAIL_IF(i + 1 < num /*
716
                                        * this means not last cert in chain,
717
                                        * taken as "generated by conforming CAs"
718
                                        */
719
1.93k
                        && (x->akid == NULL || x->akid->keyid == NULL),
720
1.93k
                    ctx,
721
1.93k
                    x, i, X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER);
722
                /* Check SKID presence acc. to RFC 5280 section 4.2.1.2 */
723
1.93k
                CB_FAIL_IF((x->ex_flags & EXFLAG_CA) != 0 && x->skid == NULL,
724
1.93k
                    ctx, x, i, X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER);
725
1.93k
            } else {
726
880
                CB_FAIL_IF(sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0,
727
880
                    ctx, x, i, X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3);
728
880
            }
729
2.81k
        }
730
731
        /* check_purpose() makes the callback as needed */
732
4.12k
        if (purpose >= X509_PURPOSE_MIN && !check_purpose(ctx, x, purpose, i, must_be_ca))
733
0
            return 0;
734
        /* Check path length */
735
4.12k
        CB_FAIL_IF(i > 1 && x->ex_pathlen != -1
736
4.12k
                && plen > x->ex_pathlen + proxy_path_length,
737
4.12k
            ctx, x, i, X509_V_ERR_PATH_LENGTH_EXCEEDED);
738
        /* Increment path length if not a self-issued intermediate CA */
739
4.12k
        if (i > 0 && (x->ex_flags & EXFLAG_SI) == 0)
740
539
            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
4.12k
        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
51
                CB_FAIL_IF(proxy_path_length > x->ex_pcpathlen,
760
51
                    ctx, x, i, X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED);
761
51
                proxy_path_length = x->ex_pcpathlen;
762
51
            }
763
64
            proxy_path_length++;
764
64
            must_be_ca = 0;
765
4.05k
        } else {
766
4.05k
            must_be_ca = 1;
767
4.05k
        }
768
4.12k
    }
769
2.71k
    return 1;
770
2.71k
}
771
772
static int has_san_id(X509 *x, int gtype)
773
180
{
774
180
    int i;
775
180
    int ret = 0;
776
180
    GENERAL_NAMES *gs = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
777
778
180
    if (gs == NULL)
779
156
        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
180
}
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.88k
{
799
3.88k
    int i;
800
801
    /* Check name constraints for all certificates */
802
10.1k
    for (i = sk_X509_num(ctx->chain) - 1; i >= 0; i--) {
803
6.24k
        X509 *x = sk_X509_value(ctx->chain, i);
804
6.24k
        int j;
805
806
        /* Ignore self-issued certs unless last in chain */
807
6.24k
        if (i != 0 && (x->ex_flags & EXFLAG_SI) != 0)
808
1.24k
            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.99k
        if ((x->ex_flags & EXFLAG_PROXY) != 0) {
817
27
            X509_NAME *tmpsubject = X509_get_subject_name(x);
818
27
            X509_NAME *tmpissuer = X509_get_issuer_name(x);
819
27
            X509_NAME_ENTRY *tmpentry = NULL;
820
27
            int last_nid = 0;
821
27
            int err = X509_V_OK;
822
27
            int last_loc = X509_NAME_entry_count(tmpsubject) - 1;
823
824
            /* Check that there are at least two RDNs */
825
27
            if (last_loc < 1) {
826
23
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
827
23
                goto proxy_name_done;
828
23
            }
829
830
            /*
831
             * Check that there is exactly one more RDN in subject as
832
             * there is in issuer.
833
             */
834
4
            if (X509_NAME_entry_count(tmpsubject)
835
4
                != X509_NAME_entry_count(tmpissuer) + 1) {
836
4
                err = X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION;
837
4
                goto proxy_name_done;
838
4
            }
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
27
        proxy_name_done:
874
27
            CB_FAIL_IF(err != X509_V_OK, ctx, x, i, err);
875
27
        }
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
7.35k
        for (j = sk_X509_num(ctx->chain) - 1; j > i; j--) {
884
2.36k
            NAME_CONSTRAINTS *nc = sk_X509_value(ctx->chain, j)->nc;
885
886
2.36k
            if (nc) {
887
180
                int rv = NAME_CONSTRAINTS_check(x, nc);
888
180
                int ret = 1;
889
890
                /* If EE certificate check commonName too */
891
180
                if (rv == X509_V_OK && i == 0
892
180
                    && (ctx->param->hostflags
893
180
                           & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT)
894
180
                        == 0
895
180
                    && ((ctx->param->hostflags
896
180
                            & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT)
897
180
                            != 0
898
180
                        || (ret = has_san_id(x, GEN_DNS)) == 0))
899
180
                    rv = NAME_CONSTRAINTS_check_CN(x, nc);
900
180
                if (ret < 0)
901
0
                    return ret;
902
903
180
                switch (rv) {
904
168
                case X509_V_OK:
905
168
                    break;
906
6
                case X509_V_ERR_OUT_OF_MEM:
907
6
                    return -1;
908
6
                default:
909
6
                    CB_FAIL_IF(1, ctx, x, i, rv);
910
6
                    break;
911
180
                }
912
180
            }
913
2.36k
        }
914
4.99k
    }
915
3.88k
    return 1;
916
3.88k
}
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
4.15k
{
943
4.15k
    X509_VERIFY_PARAM *vpm = ctx->param;
944
4.15k
    X509 *x = ctx->cert;
945
946
4.15k
    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
4.15k
    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
4.15k
    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
4.15k
    return 1;
960
4.15k
}
961
962
/* Returns -1 on internal error */
963
static int check_trust(X509_STORE_CTX *ctx, int num_untrusted)
964
69.3k
{
965
69.3k
    int i, res;
966
69.3k
    X509 *x = NULL;
967
69.3k
    X509 *mx;
968
69.3k
    SSL_DANE *dane = ctx->dane;
969
69.3k
    int num = sk_X509_num(ctx->chain);
970
69.3k
    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
69.3k
    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
72.1k
    for (i = num_untrusted; i < num; i++) {
989
3.41k
        x = sk_X509_value(ctx->chain, i);
990
3.41k
        trust = X509_check_trust(x, ctx->param->trust, 0);
991
        /* If explicitly trusted (so not neutral nor rejected) return trusted */
992
3.41k
        if (trust == X509_TRUST_TRUSTED)
993
604
            goto trusted;
994
2.80k
        if (trust == X509_TRUST_REJECTED)
995
0
            goto rejected;
996
2.80k
    }
997
998
    /*
999
     * If we are looking at a trusted certificate, and accept partial chains,
1000
     * the chain is PKIX trusted.
1001
     */
1002
68.7k
    if (num_untrusted < num) {
1003
2.80k
        if ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) != 0)
1004
2.80k
            goto trusted;
1005
0
        return X509_TRUST_UNTRUSTED;
1006
2.80k
    }
1007
1008
65.9k
    if (num_untrusted == num
1009
65.9k
        && (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.85k
        i = 0;
1015
3.85k
        x = sk_X509_value(ctx->chain, i);
1016
3.85k
        res = lookup_cert_match(&mx, ctx, x);
1017
3.85k
        if (res < 0)
1018
0
            return res;
1019
3.85k
        if (res == 0)
1020
3.83k
            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
12
        trust = X509_check_trust(mx, ctx->param->trust, 0);
1027
12
        if (trust == X509_TRUST_REJECTED) {
1028
0
            X509_free(mx);
1029
0
            goto rejected;
1030
0
        }
1031
1032
        /* Replace leaf with trusted match */
1033
12
        (void)sk_X509_set(ctx->chain, 0, mx);
1034
12
        X509_free(x);
1035
12
        ctx->num_untrusted = 0;
1036
12
        goto trusted;
1037
12
    }
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
62.1k
    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
3.42k
trusted:
1051
3.42k
    if (!DANETLS_ENABLED(dane))
1052
3.42k
        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.71k
{
1064
1.71k
    int i = 0, last = 0, ok = 0;
1065
1.71k
    int crl_check_enabled = (ctx->param->flags & X509_V_FLAG_CRL_CHECK) != 0;
1066
1.71k
    int crl_check_all_enabled = crl_check_enabled && (ctx->param->flags & X509_V_FLAG_CRL_CHECK_ALL) != 0;
1067
1.71k
    int ocsp_check_enabled = (ctx->param->flags & X509_V_FLAG_OCSP_RESP_CHECK) != 0;
1068
1.71k
    int ocsp_check_all_enabled = ocsp_check_enabled && (ctx->param->flags & X509_V_FLAG_OCSP_RESP_CHECK_ALL) != 0;
1069
1070
1.71k
    if (!crl_check_enabled && !ocsp_check_enabled)
1071
0
        return 1;
1072
1073
1.71k
    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.71k
    if (crl_check_enabled && !ocsp_check_all_enabled) {
1143
        /* certificate status check with CRLs */
1144
1.71k
        if (crl_check_all_enabled) {
1145
0
            last = sk_X509_num(ctx->chain) - 1;
1146
1.71k
        } else {
1147
            /* If checking CRL paths this isn't the EE certificate */
1148
1.71k
            if (ctx->parent != NULL)
1149
0
                return 1;
1150
1.71k
            last = 0;
1151
1.71k
        }
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.71k
        if (ocsp_check_enabled && crl_check_all_enabled)
1159
0
            i = 1;
1160
1.71k
        else
1161
1.71k
            i = 0;
1162
3.42k
        for (; i <= last; i++) {
1163
1.71k
            ctx->error_depth = i;
1164
1.71k
            ok = check_cert_crl(ctx);
1165
1.71k
            if (!ok)
1166
0
                return ok;
1167
1.71k
        }
1168
1.71k
    }
1169
1170
1.71k
    return 1;
1171
1.71k
}
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
3.32k
{
1283
3.32k
    X509_CRL *crl = NULL, *dcrl = NULL;
1284
3.32k
    int ok = 0;
1285
3.32k
    int cnum = ctx->error_depth;
1286
3.32k
    X509 *x = sk_X509_value(ctx->chain, cnum);
1287
1288
3.32k
    ctx->current_cert = x;
1289
3.32k
    ctx->current_issuer = NULL;
1290
3.32k
    ctx->current_crl_score = 0;
1291
3.32k
    ctx->current_reasons = 0;
1292
1293
    /* skip if cert is apparently self-signed */
1294
3.32k
    if (ctx->current_cert->ex_flags & EXFLAG_SS)
1295
49
        return 1;
1296
3.28k
    if ((x->ex_flags & EXFLAG_PROXY) != 0)
1297
17
        return 1;
1298
1299
4.99k
    while (ctx->current_reasons != CRLDP_ALL_REASONS) {
1300
3.26k
        unsigned int last_reasons = ctx->current_reasons;
1301
1302
        /* Try to retrieve relevant CRL */
1303
3.26k
        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
3.26k
        } else {
1315
3.26k
            ok = get_crl_delta(ctx, &crl, &dcrl, x);
1316
3.26k
        }
1317
        /* If error looking up CRL, nothing we can do except notify callback */
1318
3.26k
        if (!ok) {
1319
1.01k
            ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
1320
1.01k
            goto done;
1321
1.01k
        }
1322
2.24k
        ctx->current_crl = crl;
1323
2.24k
        ok = ctx->check_crl(ctx, crl);
1324
2.24k
        if (!ok)
1325
0
            goto done;
1326
1327
2.24k
        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
2.24k
        } else {
1335
2.24k
            ok = 1;
1336
2.24k
        }
1337
1338
        /* Don't look in full CRL if delta reason is removefromCRL */
1339
2.24k
        if (ok != 2) {
1340
2.24k
            ok = ctx->cert_crl(ctx, crl, x);
1341
2.24k
            if (!ok)
1342
0
                goto done;
1343
2.24k
        }
1344
1345
2.24k
        ctx->current_crl = NULL;
1346
2.24k
        X509_CRL_free(crl);
1347
2.24k
        X509_CRL_free(dcrl);
1348
2.24k
        crl = NULL;
1349
2.24k
        dcrl = NULL;
1350
        /*
1351
         * If reasons not updated we won't get anywhere by another iteration,
1352
         * so exit loop.
1353
         */
1354
2.24k
        if (last_reasons == ctx->current_reasons) {
1355
513
            ok = verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL);
1356
513
            goto done;
1357
513
        }
1358
2.24k
    }
1359
3.26k
done:
1360
3.26k
    X509_CRL_free(crl);
1361
3.26k
    X509_CRL_free(dcrl);
1362
1363
3.26k
    ctx->current_crl = NULL;
1364
3.26k
    return ok;
1365
3.26k
}
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
2.05k
{
1370
2.05k
    time_t *ptime;
1371
2.05k
    int i;
1372
1373
2.05k
    if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
1374
0
        ptime = &ctx->param->check_time;
1375
2.05k
    else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
1376
2.05k
        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
7.09k
{
1423
7.09k
    int i, crl_score, best_score = *pscore;
1424
7.09k
    unsigned int reasons, best_reasons = 0;
1425
7.09k
    X509 *x = ctx->current_cert;
1426
7.09k
    X509_CRL *crl, *best_crl = NULL;
1427
7.09k
    X509 *crl_issuer = NULL, *best_crl_issuer = NULL;
1428
1429
11.2k
    for (i = 0; i < sk_X509_CRL_num(crls); i++) {
1430
4.11k
        crl = sk_X509_CRL_value(crls, i);
1431
4.11k
        reasons = *preasons;
1432
4.11k
        crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x);
1433
4.11k
        if (crl_score < best_score || crl_score == 0)
1434
1.29k
            continue;
1435
        /* If current CRL is equivalent use it if it is newer */
1436
2.82k
        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.82k
        best_crl = crl;
1451
2.82k
        best_crl_issuer = crl_issuer;
1452
2.82k
        best_score = crl_score;
1453
2.82k
        best_reasons = reasons;
1454
2.82k
    }
1455
1456
7.09k
    if (best_crl != NULL) {
1457
2.82k
        if (!X509_CRL_up_ref(best_crl))
1458
0
            return 0;
1459
2.82k
        X509_CRL_free(*pcrl);
1460
2.82k
        *pcrl = best_crl;
1461
2.82k
        *pissuer = best_crl_issuer;
1462
2.82k
        *pscore = best_score;
1463
2.82k
        *preasons = best_reasons;
1464
2.82k
        X509_CRL_free(*pdcrl);
1465
2.82k
        *pdcrl = NULL;
1466
2.82k
        get_delta_sk(ctx, pdcrl, pscore, best_crl, crls);
1467
2.82k
    }
1468
1469
7.09k
    if (best_score >= CRL_SCORE_VALID)
1470
1.67k
        return 1;
1471
1472
5.41k
    return 0;
1473
7.09k
}
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.82k
{
1542
2.82k
    X509_CRL *delta;
1543
2.82k
    int i;
1544
1545
2.82k
    if ((ctx->param->flags & X509_V_FLAG_USE_DELTAS) == 0)
1546
2.82k
        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
5.10k
{
1578
5.10k
    int crl_score = 0;
1579
5.10k
    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
5.10k
    if ((crl->idp_flags & IDP_INVALID) != 0)
1585
11
        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
5.08k
    if (crl->base_crl_number != NULL)
1591
145
        return 0;
1592
    /* Reason codes or indirect CRLs need extended CRL support */
1593
4.94k
    if ((ctx->param->flags & X509_V_FLAG_EXTENDED_CRL_SUPPORT) == 0) {
1594
4.94k
        if (crl->idp_flags & (IDP_INDIRECT | IDP_REASONS))
1595
26
            return 0;
1596
4.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
4.91k
    if (X509_NAME_cmp(X509_get_issuer_name(x), X509_CRL_get_issuer(crl)) != 0) {
1603
1.21k
        if ((crl->idp_flags & IDP_INDIRECT) == 0)
1604
1.21k
            return 0;
1605
3.69k
    } else {
1606
3.69k
        crl_score |= CRL_SCORE_ISSUER_NAME;
1607
3.69k
    }
1608
1609
3.69k
    if ((crl->flags & EXFLAG_CRITICAL) == 0)
1610
2.99k
        crl_score |= CRL_SCORE_NOCRITICAL;
1611
1612
    /* Check expiration */
1613
3.69k
    if (check_crl_time(ctx, crl, 0))
1614
3.69k
        crl_score |= CRL_SCORE_TIME;
1615
1616
    /* Check authority key ID and locate certificate issuer */
1617
3.69k
    crl_akid_check(ctx, crl, pissuer, &crl_score);
1618
1619
    /* If we can't locate certificate issuer at this point forget it */
1620
3.69k
    if ((crl_score & CRL_SCORE_AKID) == 0)
1621
113
        return 0;
1622
1623
    /* Check cert for matching CRL distribution points */
1624
3.58k
    if (crl_crldp_check(x, crl, crl_score, &crl_reasons)) {
1625
        /* If no new reasons reject */
1626
2.97k
        if ((crl_reasons & ~tmp_reasons) == 0)
1627
12
            return 0;
1628
2.96k
        tmp_reasons |= crl_reasons;
1629
2.96k
        crl_score |= CRL_SCORE_SCOPE;
1630
2.96k
    }
1631
1632
3.57k
    *preasons = tmp_reasons;
1633
1634
3.57k
    return crl_score;
1635
3.58k
}
1636
1637
static void crl_akid_check(X509_STORE_CTX *ctx, X509_CRL *crl,
1638
    X509 **pissuer, int *pcrl_score)
1639
2.52k
{
1640
2.52k
    X509 *crl_issuer = NULL;
1641
2.52k
    const X509_NAME *cnm = X509_CRL_get_issuer(crl);
1642
2.52k
    int cidx = ctx->error_depth;
1643
2.52k
    int i;
1644
1645
2.52k
    if (cidx != sk_X509_num(ctx->chain) - 1)
1646
1.66k
        cidx++;
1647
1648
2.52k
    crl_issuer = sk_X509_value(ctx->chain, cidx);
1649
1650
2.52k
    if (X509_check_akid(crl_issuer, crl->akid) == X509_V_OK) {
1651
2.52k
        if (*pcrl_score & CRL_SCORE_ISSUER_NAME) {
1652
2.52k
            *pcrl_score |= CRL_SCORE_AKID | CRL_SCORE_ISSUER_CERT;
1653
2.52k
            *pissuer = crl_issuer;
1654
2.52k
            return;
1655
2.52k
        }
1656
2.52k
    }
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
 * Return the full name of the certificate CRL distribution point dp, whose
1745
 * distpoint is a nameRelativeToCRLIssuer fragment: the CRL issuer name with
1746
 * the fragment appended.  The CRL issuer is the directoryName in
1747
 * dp->CRLissuer if there is one, else the issuer of the certificate.
1748
 *
1749
 * The result is a fresh X509_NAME owned by the caller.  It is deliberately
1750
 * not stored in dp->distpoint->dpname: once its extension cache has been
1751
 * published a certificate is shared between threads without locking, and
1752
 * computing the name here rather than when the certificate is parsed keeps
1753
 * a certificate with many relative distribution points from costing a copy
1754
 * of the issuer name per entry on every parse.  Returns NULL on error.
1755
 */
1756
static X509_NAME *crldp_full_name(const X509 *x, const DIST_POINT *dp)
1757
0
{
1758
0
    const X509_NAME *iname = NULL;
1759
0
    int i;
1760
1761
    /*
1762
     * Note that the below way of determining iname is not really compliant
1763
     * with https://tools.ietf.org/html/rfc5280#section-4.2.1.13
1764
     * According to it, sk_GENERAL_NAME_num(dp->CRLissuer) MUST be <= 1
1765
     * and any CRLissuer could be of type different to GEN_DIRNAME.
1766
     */
1767
0
    for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1768
0
        GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1769
1770
0
        if (gen->type == GEN_DIRNAME) {
1771
0
            iname = gen->d.directoryName;
1772
0
            break;
1773
0
        }
1774
0
    }
1775
0
    if (iname == NULL)
1776
0
        iname = X509_get_issuer_name(x);
1777
0
    return ossl_dist_point_name_full(dp->distpoint, iname);
1778
0
}
1779
1780
/*-
1781
 * Check for match between two dist point names: three separate cases.
1782
 * 1. Both are relative names and compare X509_NAME types.
1783
 * 2. One full, one relative. Compare X509_NAME to GENERAL_NAMES.
1784
 * 3. Both are full names and compare two GENERAL_NAMES.
1785
 * 4. One is NULL: automatic match.
1786
 *
1787
 * a is the certificate's distribution point name and b the CRL's issuing
1788
 * distribution point name.  When a is a relative name, aname is its full
1789
 * name as built by crldp_full_name(); a->dpname itself is not consulted.
1790
 * For b the full name is the cached b->dpname set when the CRL was parsed.
1791
 */
1792
static int idp_check_dp(DIST_POINT_NAME *a, const X509_NAME *aname,
1793
    DIST_POINT_NAME *b)
1794
756
{
1795
756
    const X509_NAME *nm = NULL;
1796
756
    GENERAL_NAMES *gens = NULL;
1797
756
    GENERAL_NAME *gena, *genb;
1798
756
    int i, j;
1799
1800
756
    if (a == NULL || b == NULL)
1801
10
        return 1;
1802
746
    if (a->type == 1) {
1803
0
        if (aname == NULL)
1804
0
            return 0;
1805
        /* Case 1: two X509_NAME */
1806
0
        if (b->type == 1) {
1807
0
            if (b->dpname == NULL)
1808
0
                return 0;
1809
0
            return X509_NAME_cmp(aname, b->dpname) == 0;
1810
0
        }
1811
        /* Case 2: set name and GENERAL_NAMES appropriately */
1812
0
        nm = aname;
1813
0
        gens = b->name.fullname;
1814
746
    } else if (b->type == 1) {
1815
3
        if (b->dpname == NULL)
1816
0
            return 0;
1817
        /* Case 2: set name and GENERAL_NAMES appropriately */
1818
3
        gens = a->name.fullname;
1819
3
        nm = b->dpname;
1820
3
    }
1821
1822
    /* Handle case 2 with one GENERAL_NAMES and one X509_NAME */
1823
746
    if (nm != NULL) {
1824
6
        for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1825
3
            gena = sk_GENERAL_NAME_value(gens, i);
1826
3
            if (gena->type != GEN_DIRNAME)
1827
3
                continue;
1828
0
            if (X509_NAME_cmp(nm, gena->d.directoryName) == 0)
1829
0
                return 1;
1830
0
        }
1831
3
        return 0;
1832
3
    }
1833
1834
    /* Else case 3: two GENERAL_NAMES */
1835
1836
1.46k
    for (i = 0; i < sk_GENERAL_NAME_num(a->name.fullname); i++) {
1837
745
        gena = sk_GENERAL_NAME_value(a->name.fullname, i);
1838
1.46k
        for (j = 0; j < sk_GENERAL_NAME_num(b->name.fullname); j++) {
1839
743
            genb = sk_GENERAL_NAME_value(b->name.fullname, j);
1840
743
            if (GENERAL_NAME_cmp(gena, genb) == 0)
1841
19
                return 1;
1842
743
        }
1843
745
    }
1844
1845
724
    return 0;
1846
743
}
1847
1848
static int crldp_check_crlissuer(DIST_POINT *dp, X509_CRL *crl, int crl_score)
1849
891
{
1850
891
    int i;
1851
891
    const X509_NAME *nm = X509_CRL_get_issuer(crl);
1852
1853
    /* If no CRLissuer return is successful iff don't need a match */
1854
891
    if (dp->CRLissuer == NULL)
1855
877
        return (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1856
27
    for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
1857
13
        GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
1858
1859
13
        if (gen->type != GEN_DIRNAME)
1860
13
            continue;
1861
0
        if (X509_NAME_cmp(gen->d.directoryName, nm) == 0)
1862
0
            return 1;
1863
0
    }
1864
14
    return 0;
1865
14
}
1866
1867
/* Check CRLDP and IDP */
1868
static int crl_crldp_check(X509 *x, X509_CRL *crl, int crl_score,
1869
    unsigned int *preasons)
1870
2.52k
{
1871
2.52k
    int i;
1872
1873
2.52k
    if ((crl->idp_flags & IDP_ONLYATTR) != 0)
1874
4
        return 0;
1875
2.51k
    if ((x->ex_flags & EXFLAG_CA) != 0) {
1876
5
        if ((crl->idp_flags & IDP_ONLYUSER) != 0)
1877
0
            return 0;
1878
2.51k
    } else {
1879
2.51k
        if ((crl->idp_flags & IDP_ONLYCA) != 0)
1880
4
            return 0;
1881
2.51k
    }
1882
2.51k
    *preasons = crl->idp_reasons;
1883
2.78k
    for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
1884
429
        DIST_POINT *dp = sk_DIST_POINT_value(x->crldp, i);
1885
429
        X509_NAME *dpname = NULL;
1886
429
        int match;
1887
1888
429
        if (!crldp_check_crlissuer(dp, crl, crl_score))
1889
14
            continue;
1890
415
        if (crl->idp == NULL) {
1891
139
            match = 1;
1892
276
        } else {
1893
            /*
1894
             * A relative distribution point name is only comparable in
1895
             * full form.  Build it for this one comparison and discard it;
1896
             * if that fails the entry simply does not match.
1897
             */
1898
276
            if (dp->distpoint != NULL && dp->distpoint->type == 1
1899
0
                && (dpname = crldp_full_name(x, dp)) == NULL)
1900
0
                continue;
1901
276
            match = idp_check_dp(dp->distpoint, dpname, crl->idp->distpoint);
1902
276
            X509_NAME_free(dpname);
1903
276
        }
1904
415
        if (match) {
1905
161
            *preasons &= dp->dp_reasons;
1906
161
            return 1;
1907
161
        }
1908
415
    }
1909
2.35k
    return (crl->idp == NULL || crl->idp->distpoint == NULL)
1910
2.02k
        && (crl_score & CRL_SCORE_ISSUER_NAME) != 0;
1911
2.51k
}
1912
1913
/*
1914
 * Retrieve CRL corresponding to current certificate. If deltas enabled try
1915
 * to find a delta CRL too
1916
 */
1917
static int get_crl_delta(X509_STORE_CTX *ctx,
1918
    X509_CRL **pcrl, X509_CRL **pdcrl, X509 *x)
1919
5.42k
{
1920
5.42k
    int ok;
1921
5.42k
    X509 *issuer = NULL;
1922
5.42k
    int crl_score = 0;
1923
5.42k
    unsigned int reasons;
1924
5.42k
    X509_CRL *crl = NULL, *dcrl = NULL;
1925
5.42k
    STACK_OF(X509_CRL) *skcrl;
1926
5.42k
    const X509_NAME *nm = X509_get_issuer_name(x);
1927
1928
5.42k
    reasons = ctx->current_reasons;
1929
5.42k
    ok = get_crl_sk(ctx, &crl, &dcrl,
1930
5.42k
        &issuer, &crl_score, &reasons, ctx->crls);
1931
5.42k
    if (ok)
1932
2.28k
        goto done;
1933
1934
    /* Lookup CRLs from store */
1935
3.13k
    skcrl = ctx->lookup_crls(ctx, nm);
1936
1937
    /* If no CRLs found and a near match from get_crl_sk use that */
1938
3.13k
    if (skcrl == NULL && crl != NULL)
1939
0
        goto done;
1940
1941
3.13k
    get_crl_sk(ctx, &crl, &dcrl, &issuer, &crl_score, &reasons, skcrl);
1942
1943
3.13k
    sk_X509_CRL_pop_free(skcrl, X509_CRL_free);
1944
1945
5.42k
done:
1946
    /* If we got any kind of CRL use it and return success */
1947
5.42k
    if (crl != NULL) {
1948
3.57k
        ctx->current_issuer = issuer;
1949
3.57k
        ctx->current_crl_score = crl_score;
1950
3.57k
        ctx->current_reasons = reasons;
1951
3.57k
        *pcrl = crl;
1952
3.57k
        *pdcrl = dcrl;
1953
3.57k
        return 1;
1954
3.57k
    }
1955
1.84k
    return 0;
1956
5.42k
}
1957
1958
/* Check CRL validity */
1959
static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl)
1960
2.82k
{
1961
2.82k
    X509 *issuer = NULL;
1962
2.82k
    EVP_PKEY *ikey = NULL;
1963
2.82k
    int cnum = ctx->error_depth;
1964
2.82k
    int chnum = sk_X509_num(ctx->chain) - 1;
1965
1966
    /* If we have an alternative CRL issuer cert use that */
1967
2.82k
    if (ctx->current_issuer != NULL) {
1968
2.82k
        issuer = ctx->current_issuer;
1969
        /*
1970
         * Else find CRL issuer: if not last certificate then issuer is next
1971
         * certificate in chain.
1972
         */
1973
2.82k
    } else if (cnum < chnum) {
1974
0
        issuer = sk_X509_value(ctx->chain, cnum + 1);
1975
0
    } else {
1976
0
        issuer = sk_X509_value(ctx->chain, chnum);
1977
0
        if (!ossl_assert(issuer != NULL))
1978
0
            return 0;
1979
        /* If not self-issued, can't check signature */
1980
0
        if (!ctx->check_issued(ctx, issuer, issuer) && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER))
1981
0
            return 0;
1982
0
    }
1983
1984
2.82k
    if (issuer == NULL)
1985
0
        return 1;
1986
1987
    /*
1988
     * Skip most tests for deltas because they have already been done
1989
     */
1990
2.82k
    if (crl->base_crl_number == NULL) {
1991
        /* Check for cRLSign bit if keyUsage present */
1992
2.82k
        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))
1993
0
            return 0;
1994
1995
2.82k
        if ((ctx->current_crl_score & CRL_SCORE_SCOPE) == 0 && !verify_cb_crl(ctx, X509_V_ERR_DIFFERENT_CRL_SCOPE))
1996
0
            return 0;
1997
1998
2.82k
        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))
1999
0
            return 0;
2000
2001
2.82k
        if ((crl->idp_flags & IDP_INVALID) != 0 && !verify_cb_crl(ctx, X509_V_ERR_INVALID_EXTENSION))
2002
0
            return 0;
2003
2.82k
    }
2004
2005
2.82k
    if ((ctx->current_crl_score & CRL_SCORE_TIME) == 0 && !check_crl_time(ctx, crl, 1))
2006
0
        return 0;
2007
2008
    /* Attempt to get issuer certificate public key */
2009
2.82k
    ikey = X509_get0_pubkey(issuer);
2010
2.82k
    if (ikey == NULL && !verify_cb_crl(ctx, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY))
2011
0
        return 0;
2012
2013
2.82k
    if (ikey != NULL) {
2014
2.82k
        int rv = X509_CRL_check_suiteb(crl, ikey, ctx->param->flags);
2015
2016
2.82k
        if (rv != X509_V_OK && !verify_cb_crl(ctx, rv))
2017
0
            return 0;
2018
        /* Verify CRL signature */
2019
2.82k
        if (X509_CRL_verify(crl, ikey) <= 0 && !verify_cb_crl(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE))
2020
0
            return 0;
2021
2.82k
    }
2022
2.82k
    return 1;
2023
2.82k
}
2024
2025
/* Check certificate against CRL */
2026
static int cert_crl(X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x)
2027
3.57k
{
2028
3.57k
    X509_REVOKED *rev;
2029
2030
    /*
2031
     * The rules changed for this... previously if a CRL contained unhandled
2032
     * critical extensions it could still be used to indicate a certificate
2033
     * was revoked. This has since been changed since critical extensions can
2034
     * change the meaning of CRL entries.
2035
     */
2036
3.57k
    if ((ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) == 0
2037
3.57k
        && (crl->flags & EXFLAG_CRITICAL) != 0 && !verify_cb_crl(ctx, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION))
2038
0
        return 0;
2039
    /*
2040
     * Look for serial number of certificate in CRL.  If found, make sure
2041
     * reason is not removeFromCRL.
2042
     */
2043
3.57k
    if (X509_CRL_get0_by_cert(crl, &rev, x)) {
2044
1
        if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
2045
0
            return 2;
2046
1
        if (!verify_cb_crl(ctx, X509_V_ERR_CERT_REVOKED))
2047
0
            return 0;
2048
1
    }
2049
2050
3.57k
    return 1;
2051
3.57k
}
2052
2053
/* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
2054
static int check_policy(X509_STORE_CTX *ctx)
2055
0
{
2056
0
    int ret;
2057
2058
0
    if (ctx->parent)
2059
0
        return 1;
2060
    /*
2061
     * With DANE, the trust anchor might be a bare public key, not a
2062
     * certificate!  In that case our chain does not have the trust anchor
2063
     * certificate as a top-most element.  This comports well with RFC5280
2064
     * chain verification, since there too, the trust anchor is not part of the
2065
     * chain to be verified.  In particular, X509_policy_check() does not look
2066
     * at the TA cert, but assumes that it is present as the top-most chain
2067
     * element.  We therefore temporarily push a NULL cert onto the chain if it
2068
     * was verified via a bare public key, and pop it off right after the
2069
     * X509_policy_check() call.
2070
     */
2071
0
    if (ctx->bare_ta_signed && !sk_X509_push(ctx->chain, NULL)) {
2072
0
        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
2073
0
        goto memerr;
2074
0
    }
2075
0
    ret = X509_policy_check(&ctx->tree, &ctx->explicit_policy, ctx->chain,
2076
0
        ctx->param->policies, ctx->param->flags);
2077
0
    if (ctx->bare_ta_signed)
2078
0
        (void)sk_X509_pop(ctx->chain);
2079
2080
0
    if (ret == X509_PCY_TREE_INTERNAL) {
2081
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2082
0
        goto memerr;
2083
0
    }
2084
    /* Invalid or inconsistent extensions */
2085
0
    if (ret == X509_PCY_TREE_INVALID) {
2086
0
        int i, cbcalled = 0;
2087
2088
        /* Locate certificates with bad extensions and notify callback. */
2089
0
        for (i = 0; i < sk_X509_num(ctx->chain); i++) {
2090
0
            X509 *x = sk_X509_value(ctx->chain, i);
2091
2092
0
            if ((x->ex_flags & EXFLAG_INVALID_POLICY) != 0)
2093
0
                cbcalled = 1;
2094
0
            CB_FAIL_IF((x->ex_flags & EXFLAG_INVALID_POLICY) != 0,
2095
0
                ctx, x, i, X509_V_ERR_INVALID_POLICY_EXTENSION);
2096
0
        }
2097
0
        if (!cbcalled) {
2098
            /* Should not be able to get here */
2099
0
            ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
2100
0
            return 0;
2101
0
        }
2102
        /* The callback ignored the error so we return success */
2103
0
        return 1;
2104
0
    }
2105
0
    if (ret == X509_PCY_TREE_FAILURE) {
2106
0
        ctx->current_cert = NULL;
2107
0
        ctx->error = X509_V_ERR_NO_EXPLICIT_POLICY;
2108
0
        return ctx->verify_cb(0, ctx);
2109
0
    }
2110
0
    if (ret != X509_PCY_TREE_VALID) {
2111
0
        ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
2112
0
        return 0;
2113
0
    }
2114
2115
0
    if ((ctx->param->flags & X509_V_FLAG_NOTIFY_POLICY) != 0) {
2116
0
        ctx->current_cert = NULL;
2117
        /*
2118
         * Verification errors need to be "sticky", a callback may have allowed
2119
         * an SSL handshake to continue despite an error, and we must then
2120
         * remain in an error state.  Therefore, we MUST NOT clear earlier
2121
         * verification errors by setting the error to X509_V_OK.
2122
         */
2123
0
        if (!ctx->verify_cb(2, ctx))
2124
0
            return 0;
2125
0
    }
2126
2127
0
    return 1;
2128
2129
0
memerr:
2130
0
    ctx->error = X509_V_ERR_OUT_OF_MEM;
2131
0
    return -1;
2132
0
}
2133
2134
/*-
2135
 * Check certificate validity times.
2136
 * If depth >= 0, invoke verification callbacks on error, otherwise just return
2137
 * the validation status.
2138
 *
2139
 * Return 1 on success, 0 otherwise.
2140
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
2141
 */
2142
int ossl_x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth)
2143
8.00k
{
2144
8.00k
    time_t *ptime;
2145
8.00k
    int i;
2146
2147
8.00k
    if ((ctx->param->flags & X509_V_FLAG_USE_CHECK_TIME) != 0)
2148
0
        ptime = &ctx->param->check_time;
2149
8.00k
    else if ((ctx->param->flags & X509_V_FLAG_NO_CHECK_TIME) != 0)
2150
7.37k
        return 1;
2151
638
    else
2152
638
        ptime = NULL;
2153
2154
638
    i = X509_cmp_time(X509_get0_notBefore(x), ptime);
2155
638
    if (i >= 0 && depth < 0)
2156
408
        return 0;
2157
230
    CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD);
2158
230
    CB_FAIL_IF(i > 0, ctx, x, depth, X509_V_ERR_CERT_NOT_YET_VALID);
2159
2160
230
    i = X509_cmp_time(X509_get0_notAfter(x), ptime);
2161
230
    if (i <= 0 && depth < 0)
2162
199
        return 0;
2163
31
    CB_FAIL_IF(i == 0, ctx, x, depth, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD);
2164
31
    CB_FAIL_IF(i < 0, ctx, x, depth, X509_V_ERR_CERT_HAS_EXPIRED);
2165
31
    return 1;
2166
31
}
2167
2168
/*
2169
 * Verify the issuer signatures and cert times of ctx->chain.
2170
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
2171
 */
2172
static int internal_verify(X509_STORE_CTX *ctx)
2173
5.50k
{
2174
5.50k
    int n;
2175
5.50k
    X509 *xi;
2176
5.50k
    X509 *xs;
2177
2178
    /* For RPK: just do the verify callback */
2179
5.50k
    if (ctx->rpk != NULL) {
2180
0
        if (!ctx->verify_cb(ctx->error == X509_V_OK, ctx))
2181
0
            return 0;
2182
0
        return 1;
2183
0
    }
2184
5.50k
    n = sk_X509_num(ctx->chain) - 1;
2185
5.50k
    xi = sk_X509_value(ctx->chain, n);
2186
5.50k
    xs = xi;
2187
2188
5.50k
    ctx->error_depth = n;
2189
5.50k
    if (ctx->bare_ta_signed) {
2190
        /*
2191
         * With DANE-verified bare public key TA signatures,
2192
         * on the top certificate we check only the timestamps.
2193
         * We report the issuer as NULL because all we have is a bare key.
2194
         */
2195
0
        xi = NULL;
2196
5.50k
    } else if (ossl_x509_likely_issued(xi, xi) != X509_V_OK
2197
        /* exceptional case: last cert in the chain is not self-issued */
2198
4.81k
        && ((ctx->param->flags & X509_V_FLAG_PARTIAL_CHAIN) == 0)) {
2199
0
        if (n > 0) {
2200
0
            n--;
2201
0
            ctx->error_depth = n;
2202
0
            xs = sk_X509_value(ctx->chain, n);
2203
0
        } else {
2204
0
            CB_FAIL_IF(1, ctx, xi, 0,
2205
0
                X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE);
2206
0
        }
2207
        /*
2208
         * The below code will certainly not do a
2209
         * self-signature check on xi because it is not self-issued.
2210
         */
2211
0
    }
2212
2213
    /*
2214
     * Do not clear error (by ctx->error = X509_V_OK), it must be "sticky",
2215
     * only the user's callback is allowed to reset errors (at its own peril).
2216
     */
2217
14.4k
    while (n >= 0) {
2218
        /*-
2219
         * For each iteration of this loop:
2220
         * n is the subject depth
2221
         * xs is the subject cert, for which the signature is to be checked
2222
         * xi is NULL for DANE-verified bare public key TA signatures
2223
         *       else the supposed issuer cert containing the public key to use
2224
         * Initially xs == xi if the last cert in the chain is self-issued.
2225
         */
2226
        /*
2227
         * Do signature check for self-signed certificates only if explicitly
2228
         * asked for because it does not add any security and just wastes time.
2229
         */
2230
8.99k
        if (xi != NULL
2231
8.99k
            && (xs != xi
2232
5.50k
                || ((ctx->param->flags & X509_V_FLAG_CHECK_SS_SIGNATURE) != 0
2233
3.48k
                    && (xi->ex_flags & EXFLAG_SS) != 0))) {
2234
3.48k
            EVP_PKEY *pkey;
2235
            /*
2236
             * If the issuer's public key is not available or its key usage
2237
             * does not support issuing the subject cert, report the issuer
2238
             * cert and its depth (rather than n, the depth of the subject).
2239
             */
2240
3.48k
            int issuer_depth = n + (xs == xi ? 0 : 1);
2241
            /*
2242
             * According to https://tools.ietf.org/html/rfc5280#section-6.1.4
2243
             * step (n) we must check any given key usage extension in a CA cert
2244
             * when preparing the verification of a certificate issued by it.
2245
             * According to https://tools.ietf.org/html/rfc5280#section-4.2.1.3
2246
             * we must not verify a certificate signature if the key usage of
2247
             * the CA certificate that issued the certificate prohibits signing.
2248
             * In case the 'issuing' certificate is the last in the chain and is
2249
             * not a CA certificate but a 'self-issued' end-entity cert (i.e.,
2250
             * xs == xi && !(xi->ex_flags & EXFLAG_CA)) RFC 5280 does not apply
2251
             * (see https://tools.ietf.org/html/rfc6818#section-2) and thus
2252
             * we are free to ignore any key usage restrictions on such certs.
2253
             */
2254
3.48k
            int ret = xs == xi && (xi->ex_flags & EXFLAG_CA) == 0
2255
3.48k
                ? X509_V_OK
2256
3.48k
                : ossl_x509_signing_allowed(xi, xs);
2257
2258
3.48k
            CB_FAIL_IF(ret != X509_V_OK, ctx, xi, issuer_depth, ret);
2259
3.48k
            if ((pkey = X509_get0_pubkey(xi)) == NULL) {
2260
0
                CB_FAIL_IF(1, ctx, xi, issuer_depth,
2261
0
                    X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY);
2262
3.48k
            } else {
2263
3.48k
                CB_FAIL_IF(X509_verify(xs, pkey) <= 0,
2264
3.48k
                    ctx, xs, n, X509_V_ERR_CERT_SIGNATURE_FAILURE);
2265
3.48k
            }
2266
3.48k
        }
2267
2268
        /* In addition to RFC 5280 requirements do also for trust anchor cert */
2269
        /* Calls verify callback as needed */
2270
8.99k
        if (!ossl_x509_check_cert_time(ctx, xs, n))
2271
0
            return 0;
2272
2273
        /*
2274
         * Signal success at this depth.  However, the previous error (if any)
2275
         * is retained.
2276
         */
2277
8.99k
        ctx->current_issuer = xi;
2278
8.99k
        ctx->current_cert = xs;
2279
8.99k
        ctx->error_depth = n;
2280
8.99k
        if (!ctx->verify_cb(1, ctx))
2281
0
            return 0;
2282
2283
8.99k
        if (--n >= 0) {
2284
3.48k
            xi = xs;
2285
3.48k
            xs = sk_X509_value(ctx->chain, n);
2286
3.48k
        }
2287
8.99k
    }
2288
5.50k
    return 1;
2289
5.50k
}
2290
2291
int X509_cmp_current_time(const ASN1_TIME *ctm)
2292
5.02k
{
2293
5.02k
    return X509_cmp_time(ctm, NULL);
2294
5.02k
}
2295
2296
/* returns 0 on error, otherwise 1 if ctm > cmp_time, else -1 */
2297
int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
2298
19.3k
{
2299
19.3k
    static const size_t utctime_length = sizeof("YYMMDDHHMMSSZ") - 1;
2300
19.3k
    static const size_t generalizedtime_length = sizeof("YYYYMMDDHHMMSSZ") - 1;
2301
19.3k
    ASN1_TIME *asn1_cmp_time = NULL;
2302
19.3k
    int i, day, sec, ret = 0;
2303
#ifdef CHARSET_EBCDIC
2304
    const char upper_z = 0x5A;
2305
#else
2306
19.3k
    const char upper_z = 'Z';
2307
19.3k
#endif
2308
2309
    /*-
2310
     * Note that ASN.1 allows much more slack in the time format than RFC5280.
2311
     * In RFC5280, the representation is fixed:
2312
     * UTCTime: YYMMDDHHMMSSZ
2313
     * GeneralizedTime: YYYYMMDDHHMMSSZ
2314
     *
2315
     * We do NOT currently enforce the following RFC 5280 requirement:
2316
     * "CAs conforming to this profile MUST always encode certificate
2317
     *  validity dates through the year 2049 as UTCTime; certificate validity
2318
     *  dates in 2050 or later MUST be encoded as GeneralizedTime."
2319
     */
2320
19.3k
    switch (ctm->type) {
2321
19.3k
    case V_ASN1_UTCTIME:
2322
19.3k
        if (ctm->length != (int)(utctime_length))
2323
0
            return 0;
2324
19.3k
        break;
2325
19.3k
    case V_ASN1_GENERALIZEDTIME:
2326
0
        if (ctm->length != (int)(generalizedtime_length))
2327
0
            return 0;
2328
0
        break;
2329
0
    default:
2330
0
        return 0;
2331
19.3k
    }
2332
2333
    /**
2334
     * Verify the format: the ASN.1 functions we use below allow a more
2335
     * flexible format than what's mandated by RFC 5280.
2336
     * Digit and date ranges will be verified in the conversion methods.
2337
     */
2338
199k
    for (i = 0; i < ctm->length - 1; i++) {
2339
187k
        if (!ossl_ascii_isdigit(ctm->data[i]))
2340
7.38k
            return 0;
2341
187k
    }
2342
11.9k
    if (ctm->data[ctm->length - 1] != upper_z)
2343
654
        return 0;
2344
2345
    /*
2346
     * There is ASN1_UTCTIME_cmp_time_t but no
2347
     * ASN1_GENERALIZEDTIME_cmp_time_t or ASN1_TIME_cmp_time_t,
2348
     * so we go through ASN.1
2349
     */
2350
11.2k
    asn1_cmp_time = X509_time_adj(NULL, 0, cmp_time);
2351
11.2k
    if (asn1_cmp_time == NULL)
2352
0
        goto err;
2353
11.2k
    if (ASN1_TIME_diff(&day, &sec, ctm, asn1_cmp_time) == 0)
2354
2.49k
        goto err;
2355
2356
    /*
2357
     * X509_cmp_time comparison is <=.
2358
     * The return value 0 is reserved for errors.
2359
     */
2360
8.78k
    ret = (day >= 0 && sec >= 0) ? -1 : 1;
2361
2362
11.2k
err:
2363
11.2k
    ASN1_TIME_free(asn1_cmp_time);
2364
11.2k
    return ret;
2365
8.78k
}
2366
2367
/*
2368
 * Return 0 if time should not be checked or reference time is in range,
2369
 * or else 1 if it is past the end, or -1 if it is before the start
2370
 */
2371
int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
2372
    const ASN1_TIME *start, const ASN1_TIME *end)
2373
8.79k
{
2374
8.79k
    time_t ref_time;
2375
8.79k
    time_t *time = NULL;
2376
8.79k
    unsigned long flags = vpm == NULL ? 0 : X509_VERIFY_PARAM_get_flags(vpm);
2377
2378
8.79k
    if ((flags & X509_V_FLAG_USE_CHECK_TIME) != 0) {
2379
0
        ref_time = X509_VERIFY_PARAM_get_time(vpm);
2380
0
        time = &ref_time;
2381
8.79k
    } else if ((flags & X509_V_FLAG_NO_CHECK_TIME) != 0) {
2382
0
        return 0; /* this means ok */
2383
0
    } /* else reference time is the current time */
2384
2385
8.79k
    if (end != NULL && X509_cmp_time(end, time) < 0)
2386
4.16k
        return 1;
2387
4.62k
    if (start != NULL && X509_cmp_time(start, time) > 0)
2388
486
        return -1;
2389
4.14k
    return 0;
2390
4.62k
}
2391
2392
ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj)
2393
0
{
2394
0
    return X509_time_adj(s, adj, NULL);
2395
0
}
2396
2397
ASN1_TIME *X509_time_adj(ASN1_TIME *s, long offset_sec, time_t *in_tm)
2398
11.2k
{
2399
11.2k
    return X509_time_adj_ex(s, 0, offset_sec, in_tm);
2400
11.2k
}
2401
2402
ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
2403
    int offset_day, long offset_sec, time_t *in_tm)
2404
11.2k
{
2405
11.2k
    time_t t;
2406
2407
11.2k
    if (in_tm)
2408
0
        t = *in_tm;
2409
11.2k
    else
2410
11.2k
        time(&t);
2411
2412
11.2k
    if (s != NULL && (s->flags & ASN1_STRING_FLAG_MSTRING) == 0) {
2413
0
        if (s->type == V_ASN1_UTCTIME)
2414
0
            return ASN1_UTCTIME_adj(s, t, offset_day, offset_sec);
2415
0
        if (s->type == V_ASN1_GENERALIZEDTIME)
2416
0
            return ASN1_GENERALIZEDTIME_adj(s, t, offset_day, offset_sec);
2417
0
    }
2418
11.2k
    return ASN1_TIME_adj(s, t, offset_day, offset_sec);
2419
11.2k
}
2420
2421
/* Copy any missing public key parameters up the chain towards pkey */
2422
int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain)
2423
7.26k
{
2424
7.26k
    EVP_PKEY *ktmp = NULL, *ktmp2;
2425
7.26k
    int i, j;
2426
2427
7.26k
    if (pkey != NULL && !EVP_PKEY_missing_parameters(pkey))
2428
0
        return 1;
2429
2430
7.26k
    for (i = 0; i < sk_X509_num(chain); i++) {
2431
7.26k
        ktmp = X509_get0_pubkey(sk_X509_value(chain, i));
2432
7.26k
        if (ktmp == NULL) {
2433
1.76k
            ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
2434
1.76k
            return 0;
2435
1.76k
        }
2436
5.50k
        if (!EVP_PKEY_missing_parameters(ktmp))
2437
5.50k
            break;
2438
0
        ktmp = NULL;
2439
0
    }
2440
5.50k
    if (ktmp == NULL) {
2441
0
        ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN);
2442
0
        return 0;
2443
0
    }
2444
2445
    /* first, populate the other certs */
2446
5.50k
    for (j = i - 1; j >= 0; j--) {
2447
0
        ktmp2 = X509_get0_pubkey(sk_X509_value(chain, j));
2448
0
        if (!EVP_PKEY_copy_parameters(ktmp2, ktmp))
2449
0
            return 0;
2450
0
    }
2451
2452
5.50k
    if (pkey != NULL)
2453
0
        return EVP_PKEY_copy_parameters(pkey, ktmp);
2454
5.50k
    return 1;
2455
5.50k
}
2456
2457
/*
2458
 * Make a delta CRL as the difference between two full CRLs.
2459
 * Sadly, returns NULL also on internal error.
2460
 */
2461
X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
2462
    EVP_PKEY *skey, const EVP_MD *md, unsigned int flags)
2463
0
{
2464
0
    X509_CRL *crl = NULL;
2465
0
    int i;
2466
0
    STACK_OF(X509_REVOKED) *revs = NULL;
2467
2468
    /* CRLs can't be delta already */
2469
0
    if (base->base_crl_number != NULL || newer->base_crl_number != NULL) {
2470
0
        ERR_raise(ERR_LIB_X509, X509_R_CRL_ALREADY_DELTA);
2471
0
        return NULL;
2472
0
    }
2473
    /* Base and new CRL must have a CRL number */
2474
0
    if (base->crl_number == NULL || newer->crl_number == NULL) {
2475
0
        ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_NUMBER);
2476
0
        return NULL;
2477
0
    }
2478
    /* Issuer names must match */
2479
0
    if (X509_NAME_cmp(X509_CRL_get_issuer(base),
2480
0
            X509_CRL_get_issuer(newer))
2481
0
        != 0) {
2482
0
        ERR_raise(ERR_LIB_X509, X509_R_ISSUER_MISMATCH);
2483
0
        return NULL;
2484
0
    }
2485
    /* AKID and IDP must match */
2486
0
    if (!crl_extension_match(base, newer, NID_authority_key_identifier)) {
2487
0
        ERR_raise(ERR_LIB_X509, X509_R_AKID_MISMATCH);
2488
0
        return NULL;
2489
0
    }
2490
0
    if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) {
2491
0
        ERR_raise(ERR_LIB_X509, X509_R_IDP_MISMATCH);
2492
0
        return NULL;
2493
0
    }
2494
    /* Newer CRL number must exceed full CRL number */
2495
0
    if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) {
2496
0
        ERR_raise(ERR_LIB_X509, X509_R_NEWER_CRL_NOT_NEWER);
2497
0
        return NULL;
2498
0
    }
2499
    /* CRLs must verify */
2500
0
    if (skey != NULL && (X509_CRL_verify(base, skey) <= 0 || X509_CRL_verify(newer, skey) <= 0)) {
2501
0
        ERR_raise(ERR_LIB_X509, X509_R_CRL_VERIFY_FAILURE);
2502
0
        return NULL;
2503
0
    }
2504
    /* Create new CRL */
2505
0
    crl = X509_CRL_new_ex(base->libctx, base->propq);
2506
0
    if (crl == NULL || !X509_CRL_set_version(crl, X509_CRL_VERSION_2)) {
2507
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2508
0
        goto err;
2509
0
    }
2510
    /* Set issuer name */
2511
0
    if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) {
2512
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2513
0
        goto err;
2514
0
    }
2515
2516
0
    if (!X509_CRL_set1_lastUpdate(crl, X509_CRL_get0_lastUpdate(newer))) {
2517
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2518
0
        goto err;
2519
0
    }
2520
0
    if (!X509_CRL_set1_nextUpdate(crl, X509_CRL_get0_nextUpdate(newer))) {
2521
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2522
0
        goto err;
2523
0
    }
2524
2525
    /* Set base CRL number: must be critical */
2526
0
    if (X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0) <= 0) {
2527
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2528
0
        goto err;
2529
0
    }
2530
2531
    /*
2532
     * Copy extensions across from newest CRL to delta: this will set CRL
2533
     * number to correct value too.
2534
     */
2535
0
    for (i = 0; i < X509_CRL_get_ext_count(newer); i++) {
2536
0
        X509_EXTENSION *ext = X509_CRL_get_ext(newer, i);
2537
2538
0
        if (!X509_CRL_add_ext(crl, ext, -1)) {
2539
0
            ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2540
0
            goto err;
2541
0
        }
2542
0
    }
2543
2544
    /* Go through revoked entries, copying as needed */
2545
0
    revs = X509_CRL_get_REVOKED(newer);
2546
2547
0
    for (i = 0; i < sk_X509_REVOKED_num(revs); i++) {
2548
0
        X509_REVOKED *rvn, *rvtmp;
2549
2550
0
        rvn = sk_X509_REVOKED_value(revs, i);
2551
        /*
2552
         * Add only if not also in base.
2553
         * Need something cleverer here for some more complex CRLs covering
2554
         * multiple CAs.
2555
         */
2556
0
        if (!X509_CRL_get0_by_serial(base, &rvtmp, &rvn->serialNumber)) {
2557
0
            rvtmp = X509_REVOKED_dup(rvn);
2558
0
            if (rvtmp == NULL) {
2559
0
                ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2560
0
                goto err;
2561
0
            }
2562
0
            if (!X509_CRL_add0_revoked(crl, rvtmp)) {
2563
0
                X509_REVOKED_free(rvtmp);
2564
0
                ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2565
0
                goto err;
2566
0
            }
2567
0
        }
2568
0
    }
2569
2570
0
    if (skey != NULL && md != NULL && !X509_CRL_sign(crl, skey, md)) {
2571
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
2572
0
        goto err;
2573
0
    }
2574
2575
0
    return crl;
2576
2577
0
err:
2578
0
    X509_CRL_free(crl);
2579
0
    return NULL;
2580
0
}
2581
2582
int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data)
2583
37.1k
{
2584
37.1k
    return CRYPTO_set_ex_data(&ctx->ex_data, idx, data);
2585
37.1k
}
2586
2587
void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx)
2588
0
{
2589
0
    return CRYPTO_get_ex_data(&ctx->ex_data, idx);
2590
0
}
2591
2592
int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx)
2593
37.1k
{
2594
37.1k
    return ctx->error;
2595
37.1k
}
2596
2597
void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
2598
0
{
2599
0
    ctx->error = err;
2600
0
}
2601
2602
int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx)
2603
0
{
2604
0
    return ctx->error_depth;
2605
0
}
2606
2607
void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth)
2608
0
{
2609
0
    ctx->error_depth = depth;
2610
0
}
2611
2612
X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx)
2613
0
{
2614
0
    return ctx->current_cert;
2615
0
}
2616
2617
void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x)
2618
0
{
2619
0
    ctx->current_cert = x;
2620
0
}
2621
2622
STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx)
2623
63.3k
{
2624
63.3k
    return ctx->chain;
2625
63.3k
}
2626
2627
STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx)
2628
37.4k
{
2629
37.4k
    if (ctx->chain == NULL)
2630
0
        return NULL;
2631
37.4k
    return X509_chain_up_ref(ctx->chain);
2632
37.4k
}
2633
2634
X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx)
2635
0
{
2636
0
    return ctx->current_issuer;
2637
0
}
2638
2639
X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx)
2640
0
{
2641
0
    return ctx->current_crl;
2642
0
}
2643
2644
X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx)
2645
0
{
2646
0
    return ctx->parent;
2647
0
}
2648
2649
void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *x)
2650
0
{
2651
0
    ctx->cert = x;
2652
0
}
2653
2654
void X509_STORE_CTX_set0_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
2655
0
{
2656
0
    ctx->rpk = rpk;
2657
0
}
2658
2659
void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk)
2660
7.01k
{
2661
7.01k
    ctx->crls = sk;
2662
7.01k
}
2663
2664
#ifndef OPENSSL_NO_OCSP
2665
void X509_STORE_CTX_set_ocsp_resp(X509_STORE_CTX *ctx, STACK_OF(OCSP_RESPONSE) *sk)
2666
0
{
2667
0
    ctx->ocsp_resp = sk;
2668
0
}
2669
#endif
2670
2671
int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose)
2672
324
{
2673
    /*
2674
     * XXX: Why isn't this function always used to set the associated trust?
2675
     * Should there even be a VPM->trust field at all?  Or should the trust
2676
     * always be inferred from the purpose by X509_STORE_CTX_init().
2677
     */
2678
324
    return X509_STORE_CTX_purpose_inherit(ctx, 0, purpose, 0);
2679
324
}
2680
2681
int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust)
2682
324
{
2683
    /*
2684
     * XXX: See above, this function would only be needed when the default
2685
     * trust for the purpose needs an override in a corner case.
2686
     */
2687
324
    return X509_STORE_CTX_purpose_inherit(ctx, 0, 0, trust);
2688
324
}
2689
2690
/*
2691
 * This function is used to set the X509_STORE_CTX purpose and trust values.
2692
 * This is intended to be used when another structure has its own trust and
2693
 * purpose values which (if set) will be inherited by the ctx. If they aren't
2694
 * set then we will usually have a default purpose in mind which should then
2695
 * be used to set the trust value. An example of this is SSL use: an SSL
2696
 * structure will have its own purpose and trust settings which the
2697
 * application can set: if they aren't set then we use the default of SSL
2698
 * client/server.
2699
 */
2700
int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
2701
    int purpose, int trust)
2702
648
{
2703
648
    int idx;
2704
2705
    /* If purpose not set use default */
2706
648
    if (purpose == 0)
2707
324
        purpose = def_purpose;
2708
    /*
2709
     * If purpose is set but we don't have a default then set the default to
2710
     * the current purpose
2711
     */
2712
324
    else if (def_purpose == 0)
2713
324
        def_purpose = purpose;
2714
    /* If we have a purpose then check it is valid */
2715
648
    if (purpose != 0) {
2716
324
        X509_PURPOSE *ptmp;
2717
2718
324
        idx = X509_PURPOSE_get_by_id(purpose);
2719
324
        if (idx == -1) {
2720
0
            ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2721
0
            return 0;
2722
0
        }
2723
324
        ptmp = X509_PURPOSE_get0(idx);
2724
324
        if (ptmp->trust == X509_TRUST_DEFAULT) {
2725
0
            idx = X509_PURPOSE_get_by_id(def_purpose);
2726
0
            if (idx == -1) {
2727
0
                ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID);
2728
0
                return 0;
2729
0
            }
2730
0
            ptmp = X509_PURPOSE_get0(idx);
2731
0
        }
2732
        /* If trust not set then get from purpose default */
2733
324
        if (trust == 0)
2734
324
            trust = ptmp->trust;
2735
324
    }
2736
648
    if (trust != 0) {
2737
648
        idx = X509_TRUST_get_by_id(trust);
2738
648
        if (idx == -1) {
2739
0
            ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_TRUST_ID);
2740
0
            return 0;
2741
0
        }
2742
648
    }
2743
2744
648
    if (ctx->param->purpose == 0 && purpose != 0)
2745
324
        ctx->param->purpose = purpose;
2746
648
    if (ctx->param->trust == 0 && trust != 0)
2747
324
        ctx->param->trust = trust;
2748
648
    return 1;
2749
648
}
2750
2751
X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
2752
75.5k
{
2753
75.5k
    X509_STORE_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
2754
2755
75.5k
    if (ctx == NULL)
2756
0
        return NULL;
2757
2758
75.5k
    ctx->libctx = libctx;
2759
75.5k
    if (propq != NULL) {
2760
0
        ctx->propq = OPENSSL_strdup(propq);
2761
0
        if (ctx->propq == NULL) {
2762
0
            OPENSSL_free(ctx);
2763
0
            return NULL;
2764
0
        }
2765
0
    }
2766
2767
75.5k
    return ctx;
2768
75.5k
}
2769
2770
X509_STORE_CTX *X509_STORE_CTX_new(void)
2771
7.27k
{
2772
7.27k
    return X509_STORE_CTX_new_ex(NULL, NULL);
2773
7.27k
}
2774
2775
void X509_STORE_CTX_free(X509_STORE_CTX *ctx)
2776
134k
{
2777
134k
    if (ctx == NULL)
2778
58.8k
        return;
2779
2780
75.5k
    X509_STORE_CTX_cleanup(ctx);
2781
2782
    /* libctx and propq survive X509_STORE_CTX_cleanup() */
2783
75.5k
    OPENSSL_free(ctx->propq);
2784
75.5k
    OPENSSL_free(ctx);
2785
75.5k
}
2786
2787
int X509_STORE_CTX_init_rpk(X509_STORE_CTX *ctx, X509_STORE *store, EVP_PKEY *rpk)
2788
0
{
2789
0
    if (!X509_STORE_CTX_init(ctx, store, NULL, NULL))
2790
0
        return 0;
2791
0
    ctx->rpk = rpk;
2792
0
    return 1;
2793
0
}
2794
2795
int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *store, X509 *x509,
2796
    STACK_OF(X509) *chain)
2797
70.6k
{
2798
70.6k
    if (ctx == NULL) {
2799
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
2800
0
        return 0;
2801
0
    }
2802
70.6k
    X509_STORE_CTX_cleanup(ctx);
2803
2804
70.6k
    ctx->store = store;
2805
70.6k
    ctx->cert = x509;
2806
70.6k
    ctx->untrusted = chain;
2807
70.6k
    ctx->crls = NULL;
2808
70.6k
    ctx->num_untrusted = 0;
2809
70.6k
    ctx->other_ctx = NULL;
2810
70.6k
    ctx->valid = 0;
2811
70.6k
    ctx->chain = NULL;
2812
70.6k
    ctx->error = X509_V_OK;
2813
70.6k
    ctx->explicit_policy = 0;
2814
70.6k
    ctx->error_depth = 0;
2815
70.6k
    ctx->current_cert = NULL;
2816
70.6k
    ctx->current_issuer = NULL;
2817
70.6k
    ctx->current_crl = NULL;
2818
70.6k
    ctx->current_crl_score = 0;
2819
70.6k
    ctx->current_reasons = 0;
2820
70.6k
    ctx->tree = NULL;
2821
70.6k
    ctx->parent = NULL;
2822
70.6k
    ctx->dane = NULL;
2823
70.6k
    ctx->bare_ta_signed = 0;
2824
70.6k
    ctx->rpk = NULL;
2825
    /* Zero ex_data to make sure we're cleanup-safe */
2826
70.6k
    memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2827
70.6k
    ctx->ocsp_resp = NULL;
2828
2829
    /* store->cleanup is always 0 in OpenSSL, if set must be idempotent */
2830
70.6k
    if (store != NULL)
2831
70.6k
        ctx->cleanup = store->cleanup;
2832
0
    else
2833
0
        ctx->cleanup = NULL;
2834
2835
70.6k
    if (store != NULL && store->check_issued != NULL)
2836
0
        ctx->check_issued = store->check_issued;
2837
70.6k
    else
2838
70.6k
        ctx->check_issued = check_issued;
2839
2840
70.6k
    if (store != NULL && store->get_issuer != NULL)
2841
0
        ctx->get_issuer = store->get_issuer;
2842
70.6k
    else
2843
70.6k
        ctx->get_issuer = X509_STORE_CTX_get1_issuer;
2844
2845
70.6k
    if (store != NULL && store->verify_cb != NULL)
2846
7.33k
        ctx->verify_cb = store->verify_cb;
2847
63.3k
    else
2848
63.3k
        ctx->verify_cb = null_callback;
2849
2850
70.6k
    if (store != NULL && store->verify != NULL)
2851
0
        ctx->verify = store->verify;
2852
70.6k
    else
2853
70.6k
        ctx->verify = internal_verify;
2854
2855
70.6k
    if (store != NULL && store->check_revocation != NULL)
2856
0
        ctx->check_revocation = store->check_revocation;
2857
70.6k
    else
2858
70.6k
        ctx->check_revocation = check_revocation;
2859
2860
70.6k
    if (store != NULL && store->get_crl != NULL)
2861
0
        ctx->get_crl = store->get_crl;
2862
70.6k
    else
2863
70.6k
        ctx->get_crl = NULL;
2864
2865
70.6k
    if (store != NULL && store->check_crl != NULL)
2866
0
        ctx->check_crl = store->check_crl;
2867
70.6k
    else
2868
70.6k
        ctx->check_crl = check_crl;
2869
2870
70.6k
    if (store != NULL && store->cert_crl != NULL)
2871
0
        ctx->cert_crl = store->cert_crl;
2872
70.6k
    else
2873
70.6k
        ctx->cert_crl = cert_crl;
2874
2875
70.6k
    if (store != NULL && store->check_policy != NULL)
2876
0
        ctx->check_policy = store->check_policy;
2877
70.6k
    else
2878
70.6k
        ctx->check_policy = check_policy;
2879
2880
70.6k
    if (store != NULL && store->lookup_certs != NULL)
2881
0
        ctx->lookup_certs = store->lookup_certs;
2882
70.6k
    else
2883
70.6k
        ctx->lookup_certs = X509_STORE_CTX_get1_certs;
2884
2885
70.6k
    if (store != NULL && store->lookup_crls != NULL)
2886
0
        ctx->lookup_crls = store->lookup_crls;
2887
70.6k
    else
2888
70.6k
        ctx->lookup_crls = X509_STORE_CTX_get1_crls;
2889
2890
70.6k
    ctx->param = X509_VERIFY_PARAM_new();
2891
70.6k
    if (ctx->param == NULL) {
2892
0
        ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
2893
0
        goto err;
2894
0
    }
2895
2896
    /* Inherit callbacks and flags from X509_STORE if not set use defaults. */
2897
70.6k
    if (store == NULL)
2898
0
        ctx->param->inh_flags |= X509_VP_FLAG_DEFAULT | X509_VP_FLAG_ONCE;
2899
70.6k
    else if (X509_VERIFY_PARAM_inherit(ctx->param, store->param) == 0)
2900
0
        goto err;
2901
2902
70.6k
    if (!X509_STORE_CTX_set_default(ctx, "default"))
2903
0
        goto err;
2904
2905
    /*
2906
     * XXX: For now, continue to inherit trust from VPM, but infer from the
2907
     * purpose if this still yields the default value.
2908
     */
2909
70.6k
    if (ctx->param->trust == X509_TRUST_DEFAULT) {
2910
70.6k
        int idx = X509_PURPOSE_get_by_id(ctx->param->purpose);
2911
70.6k
        X509_PURPOSE *xp = X509_PURPOSE_get0(idx);
2912
2913
70.6k
        if (xp != NULL)
2914
0
            ctx->param->trust = X509_PURPOSE_get_trust(xp);
2915
70.6k
    }
2916
2917
70.6k
    if (CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx,
2918
70.6k
            &ctx->ex_data))
2919
70.6k
        return 1;
2920
70.6k
    ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
2921
2922
0
err:
2923
    /*
2924
     * On error clean up allocated storage, if the store context was not
2925
     * allocated with X509_STORE_CTX_new() this is our last chance to do so.
2926
     */
2927
0
    X509_STORE_CTX_cleanup(ctx);
2928
0
    return 0;
2929
0
}
2930
2931
/*
2932
 * Set alternative get_issuer method: just from a STACK of trusted certificates.
2933
 * This avoids the complexity of X509_STORE where it is not needed.
2934
 */
2935
void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
2936
0
{
2937
0
    ctx->other_ctx = sk;
2938
0
    ctx->get_issuer = get1_best_issuer_other_sk;
2939
0
    ctx->lookup_certs = lookup_certs_sk;
2940
0
}
2941
2942
void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx)
2943
146k
{
2944
    /*
2945
     * We need to be idempotent because, unfortunately, free() also calls
2946
     * cleanup(), so the natural call sequence new(), init(), cleanup(), free()
2947
     * calls cleanup() for the same object twice!  Thus we must zero the
2948
     * pointers below after they're freed!
2949
     */
2950
    /* Seems to always be NULL in OpenSSL, do this at most once. */
2951
146k
    if (ctx->cleanup != NULL) {
2952
0
        ctx->cleanup(ctx);
2953
0
        ctx->cleanup = NULL;
2954
0
    }
2955
146k
    if (ctx->param != NULL) {
2956
70.6k
        if (ctx->parent == NULL)
2957
70.6k
            X509_VERIFY_PARAM_free(ctx->param);
2958
70.6k
        ctx->param = NULL;
2959
70.6k
    }
2960
146k
    X509_policy_tree_free(ctx->tree);
2961
146k
    ctx->tree = NULL;
2962
146k
    OSSL_STACK_OF_X509_free(ctx->chain);
2963
146k
    ctx->chain = NULL;
2964
146k
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE_CTX, ctx, &(ctx->ex_data));
2965
146k
    memset(&ctx->ex_data, 0, sizeof(ctx->ex_data));
2966
146k
}
2967
2968
void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth)
2969
0
{
2970
0
    X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2971
0
}
2972
2973
void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags)
2974
37.1k
{
2975
37.1k
    X509_VERIFY_PARAM_set_flags(ctx->param, flags);
2976
37.1k
}
2977
2978
void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
2979
    time_t t)
2980
0
{
2981
0
    X509_VERIFY_PARAM_set_time(ctx->param, t);
2982
0
}
2983
2984
void X509_STORE_CTX_set_current_reasons(X509_STORE_CTX *ctx,
2985
    unsigned int current_reasons)
2986
0
{
2987
0
    ctx->current_reasons = current_reasons;
2988
0
}
2989
2990
X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx)
2991
0
{
2992
0
    return ctx->cert;
2993
0
}
2994
2995
EVP_PKEY *X509_STORE_CTX_get0_rpk(const X509_STORE_CTX *ctx)
2996
0
{
2997
0
    return ctx->rpk;
2998
0
}
2999
3000
STACK_OF(X509) *X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx)
3001
0
{
3002
0
    return ctx->untrusted;
3003
0
}
3004
3005
void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
3006
0
{
3007
0
    ctx->untrusted = sk;
3008
0
}
3009
3010
void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *ctx, STACK_OF(X509) *sk)
3011
0
{
3012
0
    OSSL_STACK_OF_X509_free(ctx->chain);
3013
0
    ctx->chain = sk;
3014
0
}
3015
3016
void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
3017
    X509_STORE_CTX_verify_cb verify_cb)
3018
0
{
3019
0
    ctx->verify_cb = verify_cb;
3020
0
}
3021
3022
X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx)
3023
0
{
3024
0
    return ctx->verify_cb;
3025
0
}
3026
3027
void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
3028
    X509_STORE_CTX_verify_fn verify)
3029
0
{
3030
0
    ctx->verify = verify;
3031
0
}
3032
3033
X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx)
3034
0
{
3035
0
    return ctx->verify;
3036
0
}
3037
3038
X509_STORE_CTX_get_issuer_fn
3039
X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx)
3040
0
{
3041
0
    return ctx->get_issuer;
3042
0
}
3043
3044
X509_STORE_CTX_check_issued_fn
3045
X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx)
3046
0
{
3047
0
    return ctx->check_issued;
3048
0
}
3049
3050
X509_STORE_CTX_check_revocation_fn
3051
X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx)
3052
0
{
3053
0
    return ctx->check_revocation;
3054
0
}
3055
3056
X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx)
3057
0
{
3058
0
    return ctx->get_crl;
3059
0
}
3060
3061
void X509_STORE_CTX_set_get_crl(X509_STORE_CTX *ctx,
3062
    X509_STORE_CTX_get_crl_fn get_crl)
3063
0
{
3064
0
    ctx->get_crl = get_crl;
3065
0
}
3066
3067
X509_STORE_CTX_check_crl_fn
3068
X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx)
3069
0
{
3070
0
    return ctx->check_crl;
3071
0
}
3072
3073
X509_STORE_CTX_cert_crl_fn
3074
X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx)
3075
0
{
3076
0
    return ctx->cert_crl;
3077
0
}
3078
3079
X509_STORE_CTX_check_policy_fn
3080
X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx)
3081
0
{
3082
0
    return ctx->check_policy;
3083
0
}
3084
3085
X509_STORE_CTX_lookup_certs_fn
3086
X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx)
3087
0
{
3088
0
    return ctx->lookup_certs;
3089
0
}
3090
3091
X509_STORE_CTX_lookup_crls_fn
3092
X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx)
3093
0
{
3094
0
    return ctx->lookup_crls;
3095
0
}
3096
3097
X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx)
3098
0
{
3099
0
    return ctx->cleanup;
3100
0
}
3101
3102
X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx)
3103
0
{
3104
0
    return ctx->tree;
3105
0
}
3106
3107
int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx)
3108
0
{
3109
0
    return ctx->explicit_policy;
3110
0
}
3111
3112
int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx)
3113
0
{
3114
0
    return ctx->num_untrusted;
3115
0
}
3116
3117
int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name)
3118
107k
{
3119
107k
    const X509_VERIFY_PARAM *param;
3120
3121
107k
    param = X509_VERIFY_PARAM_lookup(name);
3122
107k
    if (param == NULL) {
3123
0
        ERR_raise_data(ERR_LIB_X509, X509_R_UNKNOWN_PURPOSE_ID, "name=%s", name);
3124
0
        return 0;
3125
0
    }
3126
107k
    return X509_VERIFY_PARAM_inherit(ctx->param, param);
3127
107k
}
3128
3129
X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx)
3130
37.4k
{
3131
37.4k
    return ctx->param;
3132
37.4k
}
3133
3134
void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param)
3135
0
{
3136
0
    X509_VERIFY_PARAM_free(ctx->param);
3137
0
    ctx->param = param;
3138
0
}
3139
3140
void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane)
3141
0
{
3142
0
    ctx->dane = dane;
3143
0
}
3144
3145
static unsigned char *dane_i2d(X509 *cert, uint8_t selector,
3146
    unsigned int *i2dlen)
3147
0
{
3148
0
    unsigned char *buf = NULL;
3149
0
    int len;
3150
3151
    /*
3152
     * Extract ASN.1 DER form of certificate or public key.
3153
     */
3154
0
    switch (selector) {
3155
0
    case DANETLS_SELECTOR_CERT:
3156
0
        len = i2d_X509(cert, &buf);
3157
0
        break;
3158
0
    case DANETLS_SELECTOR_SPKI:
3159
0
        len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &buf);
3160
0
        break;
3161
0
    default:
3162
0
        ERR_raise(ERR_LIB_X509, X509_R_BAD_SELECTOR);
3163
0
        return NULL;
3164
0
    }
3165
3166
0
    if (len < 0 || buf == NULL) {
3167
0
        ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
3168
0
        return NULL;
3169
0
    }
3170
3171
0
    *i2dlen = (unsigned int)len;
3172
0
    return buf;
3173
0
}
3174
3175
0
#define DANETLS_NONE 256 /* impossible uint8_t */
3176
3177
/* Returns -1 on internal error */
3178
static int dane_match_cert(X509_STORE_CTX *ctx, X509 *cert, int depth)
3179
0
{
3180
0
    SSL_DANE *dane = ctx->dane;
3181
0
    unsigned usage = DANETLS_NONE;
3182
0
    unsigned selector = DANETLS_NONE;
3183
0
    unsigned ordinal = DANETLS_NONE;
3184
0
    unsigned mtype = DANETLS_NONE;
3185
0
    unsigned char *i2dbuf = NULL;
3186
0
    unsigned int i2dlen = 0;
3187
0
    unsigned char mdbuf[EVP_MAX_MD_SIZE];
3188
0
    unsigned char *cmpbuf = NULL;
3189
0
    unsigned int cmplen = 0;
3190
0
    int i;
3191
0
    int recnum;
3192
0
    int matched = 0;
3193
0
    danetls_record *t = NULL;
3194
0
    uint32_t mask;
3195
3196
0
    mask = (depth == 0) ? DANETLS_EE_MASK : DANETLS_TA_MASK;
3197
3198
    /* The trust store is not applicable with DANE-TA(2) */
3199
0
    if (depth >= ctx->num_untrusted)
3200
0
        mask &= DANETLS_PKIX_MASK;
3201
3202
    /*
3203
     * If we've previously matched a PKIX-?? record, no need to test any
3204
     * further PKIX-?? records, it remains to just build the PKIX chain.
3205
     * Had the match been a DANE-?? record, we'd be done already.
3206
     */
3207
0
    if (dane->mdpth >= 0)
3208
0
        mask &= ~DANETLS_PKIX_MASK;
3209
3210
    /*-
3211
     * https://tools.ietf.org/html/rfc7671#section-5.1
3212
     * https://tools.ietf.org/html/rfc7671#section-5.2
3213
     * https://tools.ietf.org/html/rfc7671#section-5.3
3214
     * https://tools.ietf.org/html/rfc7671#section-5.4
3215
     *
3216
     * We handle DANE-EE(3) records first as they require no chain building
3217
     * and no expiration or hostname checks.  We also process digests with
3218
     * higher ordinals first and ignore lower priorities except Full(0) which
3219
     * is always processed (last).  If none match, we then process PKIX-EE(1).
3220
     *
3221
     * NOTE: This relies on DANE usages sorting before the corresponding PKIX
3222
     * usages in SSL_dane_tlsa_add(), and also on descending sorting of digest
3223
     * priorities.  See twin comment in ssl/ssl_lib.c.
3224
     *
3225
     * We expect that most TLSA RRsets will have just a single usage, so we
3226
     * don't go out of our way to cache multiple selector-specific i2d buffers
3227
     * across usages, but if the selector happens to remain the same as switch
3228
     * usages, that's OK.  Thus, a set of "3 1 1", "3 0 1", "1 1 1", "1 0 1",
3229
     * records would result in us generating each of the certificate and public
3230
     * key DER forms twice, but more typically we'd just see multiple "3 1 1"
3231
     * or multiple "3 0 1" records.
3232
     *
3233
     * As soon as we find a match at any given depth, we stop, because either
3234
     * we've matched a DANE-?? record and the peer is authenticated, or, after
3235
     * exhausting all DANE-?? records, we've matched a PKIX-?? record, which is
3236
     * sufficient for DANE, and what remains to do is ordinary PKIX validation.
3237
     */
3238
0
    recnum = (dane->umask & mask) != 0 ? sk_danetls_record_num(dane->trecs) : 0;
3239
0
    for (i = 0; matched == 0 && i < recnum; ++i) {
3240
0
        t = sk_danetls_record_value(dane->trecs, i);
3241
0
        if ((DANETLS_USAGE_BIT(t->usage) & mask) == 0)
3242
0
            continue;
3243
0
        if (t->usage != usage) {
3244
0
            usage = t->usage;
3245
3246
            /* Reset digest agility for each usage/selector pair */
3247
0
            mtype = DANETLS_NONE;
3248
0
            ordinal = dane->dctx->mdord[t->mtype];
3249
0
        }
3250
0
        if (t->selector != selector) {
3251
0
            selector = t->selector;
3252
3253
            /* Update per-selector state */
3254
0
            OPENSSL_free(i2dbuf);
3255
0
            i2dbuf = dane_i2d(cert, selector, &i2dlen);
3256
0
            if (i2dbuf == NULL)
3257
0
                return -1;
3258
3259
            /* Reset digest agility for each usage/selector pair */
3260
0
            mtype = DANETLS_NONE;
3261
0
            ordinal = dane->dctx->mdord[t->mtype];
3262
0
        } else if (t->mtype != DANETLS_MATCHING_FULL) {
3263
            /*-
3264
             * Digest agility:
3265
             *
3266
             *     <https://tools.ietf.org/html/rfc7671#section-9>
3267
             *
3268
             * For a fixed selector, after processing all records with the
3269
             * highest mtype ordinal, ignore all mtypes with lower ordinals
3270
             * other than "Full".
3271
             */
3272
0
            if (dane->dctx->mdord[t->mtype] < ordinal)
3273
0
                continue;
3274
0
        }
3275
3276
        /*
3277
         * Each time we hit a (new selector or) mtype, re-compute the relevant
3278
         * digest, more complex caching is not worth the code space.
3279
         */
3280
0
        if (t->mtype != mtype) {
3281
0
            const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
3282
3283
0
            cmpbuf = i2dbuf;
3284
0
            cmplen = i2dlen;
3285
3286
0
            if (md != NULL) {
3287
0
                cmpbuf = mdbuf;
3288
0
                if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
3289
0
                    matched = -1;
3290
0
                    break;
3291
0
                }
3292
0
            }
3293
0
        }
3294
3295
        /*
3296
         * Squirrel away the certificate and depth if we have a match.  Any
3297
         * DANE match is dispositive, but with PKIX we still need to build a
3298
         * full chain.
3299
         */
3300
0
        if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3301
0
            if (DANETLS_USAGE_BIT(usage) & DANETLS_DANE_MASK)
3302
0
                matched = 1;
3303
0
            if (matched || dane->mdpth < 0) {
3304
0
                if (!X509_up_ref(cert)) {
3305
0
                    matched = -1;
3306
0
                    break;
3307
0
                }
3308
3309
0
                X509_free(dane->mcert);
3310
0
                dane->mcert = cert;
3311
0
                dane->mdpth = depth;
3312
0
                dane->mtlsa = t;
3313
0
            }
3314
0
            break;
3315
0
        }
3316
0
    }
3317
3318
    /* Clear the one-element DER cache */
3319
0
    OPENSSL_free(i2dbuf);
3320
0
    return matched;
3321
0
}
3322
3323
/* Returns -1 on internal error */
3324
static int check_dane_issuer(X509_STORE_CTX *ctx, int depth)
3325
881
{
3326
881
    SSL_DANE *dane = ctx->dane;
3327
881
    int matched = 0;
3328
881
    X509 *cert;
3329
3330
881
    if (!DANETLS_HAS_TA(dane) || depth == 0)
3331
881
        return X509_TRUST_UNTRUSTED;
3332
3333
    /*
3334
     * Record any DANE trust anchor matches, for the first depth to test, if
3335
     * there's one at that depth. (This'll be false for length 1 chains looking
3336
     * for an exact match for the leaf certificate).
3337
     */
3338
0
    cert = sk_X509_value(ctx->chain, depth);
3339
0
    if (cert != NULL && (matched = dane_match_cert(ctx, cert, depth)) < 0)
3340
0
        return matched;
3341
0
    if (matched > 0) {
3342
0
        ctx->num_untrusted = depth - 1;
3343
0
        return X509_TRUST_TRUSTED;
3344
0
    }
3345
3346
0
    return X509_TRUST_UNTRUSTED;
3347
0
}
3348
3349
static int check_dane_pkeys(X509_STORE_CTX *ctx)
3350
0
{
3351
0
    SSL_DANE *dane = ctx->dane;
3352
0
    danetls_record *t;
3353
0
    int num = ctx->num_untrusted;
3354
0
    X509 *cert = sk_X509_value(ctx->chain, num - 1);
3355
0
    int recnum = sk_danetls_record_num(dane->trecs);
3356
0
    int i;
3357
3358
0
    for (i = 0; i < recnum; ++i) {
3359
0
        t = sk_danetls_record_value(dane->trecs, i);
3360
0
        if (t->usage != DANETLS_USAGE_DANE_TA || t->selector != DANETLS_SELECTOR_SPKI || t->mtype != DANETLS_MATCHING_FULL || X509_verify(cert, t->spki) <= 0)
3361
0
            continue;
3362
3363
        /* Clear any PKIX-?? matches that failed to extend to a full chain */
3364
0
        X509_free(dane->mcert);
3365
0
        dane->mcert = NULL;
3366
3367
        /* Record match via a bare TA public key */
3368
0
        ctx->bare_ta_signed = 1;
3369
0
        dane->mdpth = num - 1;
3370
0
        dane->mtlsa = t;
3371
3372
        /* Prune any excess chain certificates */
3373
0
        num = sk_X509_num(ctx->chain);
3374
0
        for (; num > ctx->num_untrusted; --num)
3375
0
            X509_free(sk_X509_pop(ctx->chain));
3376
3377
0
        return X509_TRUST_TRUSTED;
3378
0
    }
3379
3380
0
    return X509_TRUST_UNTRUSTED;
3381
0
}
3382
3383
/*
3384
 * Only DANE-EE and SPKI are supported
3385
 * Returns -1 on internal error
3386
 */
3387
static int dane_match_rpk(X509_STORE_CTX *ctx, EVP_PKEY *rpk)
3388
0
{
3389
0
    SSL_DANE *dane = ctx->dane;
3390
0
    danetls_record *t = NULL;
3391
0
    int mtype = DANETLS_MATCHING_FULL;
3392
0
    unsigned char *i2dbuf = NULL;
3393
0
    unsigned int i2dlen = 0;
3394
0
    unsigned char mdbuf[EVP_MAX_MD_SIZE];
3395
0
    unsigned char *cmpbuf;
3396
0
    unsigned int cmplen = 0;
3397
0
    int len;
3398
0
    int recnum = sk_danetls_record_num(dane->trecs);
3399
0
    int i;
3400
0
    int matched = 0;
3401
3402
    /* Calculate ASN.1 DER of RPK */
3403
0
    if ((len = i2d_PUBKEY(rpk, &i2dbuf)) <= 0)
3404
0
        return -1;
3405
0
    cmplen = i2dlen = (unsigned int)len;
3406
0
    cmpbuf = i2dbuf;
3407
3408
0
    for (i = 0; i < recnum; i++) {
3409
0
        t = sk_danetls_record_value(dane->trecs, i);
3410
0
        if (t->usage != DANETLS_USAGE_DANE_EE || t->selector != DANETLS_SELECTOR_SPKI)
3411
0
            continue;
3412
3413
        /* Calculate hash - keep only one around */
3414
0
        if (t->mtype != mtype) {
3415
0
            const EVP_MD *md = dane->dctx->mdevp[mtype = t->mtype];
3416
3417
0
            cmpbuf = i2dbuf;
3418
0
            cmplen = i2dlen;
3419
3420
0
            if (md != NULL) {
3421
0
                cmpbuf = mdbuf;
3422
0
                if (!EVP_Digest(i2dbuf, i2dlen, cmpbuf, &cmplen, md, 0)) {
3423
0
                    matched = -1;
3424
0
                    break;
3425
0
                }
3426
0
            }
3427
0
        }
3428
0
        if (cmplen == t->dlen && memcmp(cmpbuf, t->data, cmplen) == 0) {
3429
0
            matched = 1;
3430
0
            dane->mdpth = 0;
3431
0
            dane->mtlsa = t;
3432
0
            break;
3433
0
        }
3434
0
    }
3435
0
    OPENSSL_free(i2dbuf);
3436
0
    return matched;
3437
0
}
3438
3439
static void dane_reset(SSL_DANE *dane)
3440
0
{
3441
    /* Reset state to verify another chain, or clear after failure. */
3442
0
    X509_free(dane->mcert);
3443
0
    dane->mcert = NULL;
3444
0
    dane->mtlsa = NULL;
3445
0
    dane->mdpth = -1;
3446
0
    dane->pdpth = -1;
3447
0
}
3448
3449
/* Sadly, returns 0 also on internal error in ctx->verify_cb(). */
3450
static int check_leaf_suiteb(X509_STORE_CTX *ctx, X509 *cert)
3451
0
{
3452
0
    int err = X509_chain_check_suiteb(NULL, cert, NULL, ctx->param->flags);
3453
3454
0
    CB_FAIL_IF(err != X509_V_OK, ctx, cert, 0, err);
3455
0
    return 1;
3456
0
}
3457
3458
/* Returns -1 on internal error */
3459
static int dane_verify_rpk(X509_STORE_CTX *ctx)
3460
0
{
3461
0
    SSL_DANE *dane = ctx->dane;
3462
0
    int matched;
3463
3464
0
    dane_reset(dane);
3465
3466
    /*
3467
     * Look for a DANE record for RPK
3468
     * If error, return -1
3469
     * If found, call ctx->verify_cb(1, ctx)
3470
     * If not found call ctx->verify_cb(0, ctx)
3471
     */
3472
0
    matched = dane_match_rpk(ctx, ctx->rpk);
3473
0
    ctx->error_depth = 0;
3474
3475
0
    if (matched < 0) {
3476
0
        ctx->error = X509_V_ERR_UNSPECIFIED;
3477
0
        return -1;
3478
0
    }
3479
3480
0
    if (matched > 0)
3481
0
        ctx->error = X509_V_OK;
3482
0
    else
3483
0
        ctx->error = X509_V_ERR_DANE_NO_MATCH;
3484
3485
0
    return verify_rpk(ctx);
3486
0
}
3487
3488
/* Returns -1 on internal error */
3489
static int dane_verify(X509_STORE_CTX *ctx)
3490
0
{
3491
0
    X509 *cert = ctx->cert;
3492
0
    SSL_DANE *dane = ctx->dane;
3493
0
    int matched;
3494
0
    int done;
3495
3496
0
    dane_reset(dane);
3497
3498
    /*-
3499
     * When testing the leaf certificate, if we match a DANE-EE(3) record,
3500
     * dane_match() returns 1 and we're done.  If however we match a PKIX-EE(1)
3501
     * record, the match depth and matching TLSA record are recorded, but the
3502
     * return value is 0, because we still need to find a PKIX trust anchor.
3503
     * Therefore, when DANE authentication is enabled (required), we're done
3504
     * if:
3505
     *   + matched < 0, internal error.
3506
     *   + matched == 1, we matched a DANE-EE(3) record
3507
     *   + matched == 0, mdepth < 0 (no PKIX-EE match) and there are no
3508
     *     DANE-TA(2) or PKIX-TA(0) to test.
3509
     */
3510
0
    matched = dane_match_cert(ctx, ctx->cert, 0);
3511
0
    done = matched != 0 || (!DANETLS_HAS_TA(dane) && dane->mdpth < 0);
3512
3513
0
    if (done && !X509_get_pubkey_parameters(NULL, ctx->chain))
3514
0
        return -1;
3515
3516
0
    if (matched > 0) {
3517
        /* Callback invoked as needed */
3518
0
        if (!check_leaf_suiteb(ctx, cert))
3519
0
            return 0;
3520
        /* Callback invoked as needed */
3521
0
        if ((dane->flags & DANE_FLAG_NO_DANE_EE_NAMECHECKS) == 0 && !check_id(ctx))
3522
0
            return 0;
3523
        /* Bypass internal_verify(), issue depth 0 success callback */
3524
0
        ctx->error_depth = 0;
3525
0
        ctx->current_cert = cert;
3526
0
        return ctx->verify_cb(1, ctx);
3527
0
    }
3528
3529
0
    if (matched < 0) {
3530
0
        ctx->error_depth = 0;
3531
0
        ctx->current_cert = cert;
3532
0
        ctx->error = X509_V_ERR_OUT_OF_MEM;
3533
0
        return -1;
3534
0
    }
3535
3536
0
    if (done) {
3537
        /* Fail early, TA-based success is not possible */
3538
0
        if (!check_leaf_suiteb(ctx, cert))
3539
0
            return 0;
3540
0
        return verify_cb_cert(ctx, cert, 0, X509_V_ERR_DANE_NO_MATCH);
3541
0
    }
3542
3543
    /*
3544
     * Chain verification for usages 0/1/2.  TLSA record matching of depth > 0
3545
     * certificates happens in-line with building the rest of the chain.
3546
     */
3547
0
    return verify_chain(ctx);
3548
0
}
3549
3550
/*
3551
 * Get trusted issuer, without duplicate suppression
3552
 * Returns -1 on internal error.
3553
 */
3554
static int get1_trusted_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *cert)
3555
106k
{
3556
106k
    STACK_OF(X509) *saved_chain = ctx->chain;
3557
106k
    int ok;
3558
3559
106k
    ctx->chain = NULL;
3560
106k
    ok = ctx->get_issuer(issuer, ctx, cert);
3561
106k
    ctx->chain = saved_chain;
3562
3563
106k
    return ok;
3564
106k
}
3565
3566
/*-
3567
 * Returns -1 on internal error.
3568
 * Sadly, returns 0 also on internal error in ctx->verify_cb().
3569
 */
3570
static int build_chain(X509_STORE_CTX *ctx)
3571
69.4k
{
3572
69.4k
    SSL_DANE *dane = ctx->dane;
3573
69.4k
    int num = sk_X509_num(ctx->chain);
3574
69.4k
    STACK_OF(X509) *sk_untrusted = NULL;
3575
69.4k
    unsigned int search;
3576
69.4k
    int may_trusted = 0;
3577
69.4k
    int may_alternate = 0;
3578
69.4k
    int trust = X509_TRUST_UNTRUSTED;
3579
69.4k
    int alt_untrusted = 0;
3580
69.4k
    int max_depth;
3581
69.4k
    int ok = 0;
3582
69.4k
    int i;
3583
3584
    /* Our chain starts with a single untrusted element. */
3585
69.4k
    if (!ossl_assert(num == 1 && ctx->num_untrusted == num))
3586
0
        goto int_err;
3587
3588
215k
#define S_DOUNTRUSTED (1 << 0) /* Search untrusted chain */
3589
212k
#define S_DOTRUSTED (1 << 1) /* Search trusted store */
3590
175k
#define S_DOALTERNATE (1 << 2) /* Retry with pruned alternate chain */
3591
    /*
3592
     * Set up search policy, untrusted if possible, trusted-first if enabled,
3593
     * which is the default.
3594
     * If we're doing DANE and not doing PKIX-TA/PKIX-EE, we never look in the
3595
     * trust_store, otherwise we might look there first.  If not trusted-first,
3596
     * and alternate chains are not disabled, try building an alternate chain
3597
     * if no luck with untrusted first.
3598
     */
3599
69.4k
    search = ctx->untrusted != NULL ? S_DOUNTRUSTED : 0;
3600
69.4k
    if (DANETLS_HAS_PKIX(dane) || !DANETLS_HAS_DANE(dane)) {
3601
69.4k
        if (search == 0 || (ctx->param->flags & X509_V_FLAG_TRUSTED_FIRST) != 0)
3602
69.4k
            search |= S_DOTRUSTED;
3603
0
        else if (!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS))
3604
0
            may_alternate = 1;
3605
69.4k
        may_trusted = 1;
3606
69.4k
    }
3607
3608
    /* Initialize empty untrusted stack. */
3609
69.4k
    if ((sk_untrusted = sk_X509_new_null()) == NULL) {
3610
0
        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3611
0
        goto memerr;
3612
0
    }
3613
3614
    /*
3615
     * If we got any "Cert(0) Full(0)" trust anchors from DNS, *prepend* them
3616
     * to our working copy of the untrusted certificate stack.
3617
     */
3618
69.4k
    if (DANETLS_ENABLED(dane) && dane->certs != NULL
3619
0
        && !X509_add_certs(sk_untrusted, dane->certs, X509_ADD_FLAG_DEFAULT)) {
3620
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3621
0
        goto memerr;
3622
0
    }
3623
3624
    /*
3625
     * Shallow-copy the stack of untrusted certificates (with TLS, this is
3626
     * typically the content of the peer's certificate message) so we can make
3627
     * multiple passes over it, while free to remove elements as we go.
3628
     */
3629
69.4k
    if (!X509_add_certs(sk_untrusted, ctx->untrusted, X509_ADD_FLAG_DEFAULT)) {
3630
0
        ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
3631
0
        goto memerr;
3632
0
    }
3633
3634
    /*
3635
     * Still absurdly large, but arithmetically safe, a lower hard upper bound
3636
     * might be reasonable.
3637
     */
3638
69.4k
    if (ctx->param->depth > INT_MAX / 2)
3639
0
        ctx->param->depth = INT_MAX / 2;
3640
3641
    /*
3642
     * Try to extend the chain until we reach an ultimately trusted issuer.
3643
     * Build chains up to one longer the limit, later fail if we hit the limit,
3644
     * with an X509_V_ERR_CERT_CHAIN_TOO_LONG error code.
3645
     */
3646
69.4k
    max_depth = ctx->param->depth + 1;
3647
3648
106k
    while (search != 0) {
3649
106k
        X509 *curr, *issuer = NULL;
3650
3651
106k
        num = sk_X509_num(ctx->chain);
3652
106k
        ctx->error_depth = num - 1;
3653
        /*
3654
         * Look in the trust store if enabled for first lookup, or we've run
3655
         * out of untrusted issuers and search here is not disabled.  When we
3656
         * reach the depth limit, we stop extending the chain, if by that point
3657
         * we've not found a trust anchor, any trusted chain would be too long.
3658
         *
3659
         * The error reported to the application verify callback is at the
3660
         * maximal valid depth with the current certificate equal to the last
3661
         * not ultimately-trusted issuer.  For example, with verify_depth = 0,
3662
         * the callback will report errors at depth=1 when the immediate issuer
3663
         * of the leaf certificate is not a trust anchor.  No attempt will be
3664
         * made to locate an issuer for that certificate, since such a chain
3665
         * would be a-priori too long.
3666
         */
3667
106k
        if ((search & S_DOTRUSTED) != 0) {
3668
106k
            i = num;
3669
106k
            if ((search & S_DOALTERNATE) != 0) {
3670
                /*
3671
                 * As high up the chain as we can, look for an alternative
3672
                 * trusted issuer of an untrusted certificate that currently
3673
                 * has an untrusted issuer.  We use the alt_untrusted variable
3674
                 * to track how far up the chain we find the first match.  It
3675
                 * is only if and when we find a match, that we prune the chain
3676
                 * and reset ctx->num_untrusted to the reduced count of
3677
                 * untrusted certificates.  While we're searching for such a
3678
                 * match (which may never be found), it is neither safe nor
3679
                 * wise to preemptively modify either the chain or
3680
                 * ctx->num_untrusted.
3681
                 *
3682
                 * Note, like ctx->num_untrusted, alt_untrusted is a count of
3683
                 * untrusted certificates, not a "depth".
3684
                 */
3685
0
                i = alt_untrusted;
3686
0
            }
3687
106k
            curr = sk_X509_value(ctx->chain, i - 1);
3688
3689
            /* Note: get1_trusted_issuer() must be used even if self-signed. */
3690
106k
            ok = num > max_depth ? 0 : get1_trusted_issuer(&issuer, ctx, curr);
3691
3692
106k
            if (ok < 0) {
3693
0
                trust = -1;
3694
0
                ctx->error = X509_V_ERR_STORE_LOOKUP;
3695
0
                break;
3696
0
            }
3697
3698
106k
            if (ok > 0) {
3699
3.53k
                int self_signed = X509_self_signed(curr, 0);
3700
3701
3.53k
                if (self_signed < 0) {
3702
73
                    X509_free(issuer);
3703
73
                    goto int_err;
3704
73
                }
3705
                /*
3706
                 * Alternative trusted issuer for a mid-chain untrusted cert?
3707
                 * Pop the untrusted cert's successors and retry.  We might now
3708
                 * be able to complete a valid chain via the trust store.  Note
3709
                 * that despite the current trust store match we might still
3710
                 * fail complete the chain to a suitable trust anchor, in which
3711
                 * case we may prune some more untrusted certificates and try
3712
                 * again.  Thus the S_DOALTERNATE bit may yet be turned on
3713
                 * again with an even shorter untrusted chain!
3714
                 *
3715
                 * If in the process we threw away our matching PKIX-TA trust
3716
                 * anchor, reset DANE trust.  We might find a suitable trusted
3717
                 * certificate among the ones from the trust store.
3718
                 */
3719
3.45k
                if ((search & S_DOALTERNATE) != 0) {
3720
0
                    if (!ossl_assert(num > i && i > 0 && !self_signed)) {
3721
0
                        X509_free(issuer);
3722
0
                        goto int_err;
3723
0
                    }
3724
0
                    search &= ~S_DOALTERNATE;
3725
0
                    for (; num > i; --num)
3726
0
                        X509_free(sk_X509_pop(ctx->chain));
3727
0
                    ctx->num_untrusted = num;
3728
3729
0
                    if (DANETLS_ENABLED(dane) && dane->mdpth >= ctx->num_untrusted) {
3730
0
                        dane->mdpth = -1;
3731
0
                        X509_free(dane->mcert);
3732
0
                        dane->mcert = NULL;
3733
0
                    }
3734
0
                    if (DANETLS_ENABLED(dane) && dane->pdpth >= ctx->num_untrusted)
3735
0
                        dane->pdpth = -1;
3736
0
                }
3737
3738
3.45k
                if (!self_signed) { /* untrusted not self-signed certificate */
3739
                    /* Grow the chain by trusted issuer */
3740
3.41k
                    if (!sk_X509_push(ctx->chain, issuer)) {
3741
0
                        X509_free(issuer);
3742
0
                        ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
3743
0
                        goto memerr;
3744
0
                    }
3745
3.41k
                    if ((self_signed = X509_self_signed(issuer, 0)) < 0)
3746
0
                        goto int_err;
3747
3.41k
                } else {
3748
                    /*
3749
                     * We have a self-signed untrusted cert that has the same
3750
                     * subject name (and perhaps keyid and/or serial number) as
3751
                     * a trust anchor.  We must have an exact match to avoid
3752
                     * possible impersonation via key substitution etc.
3753
                     */
3754
46
                    if (X509_cmp(curr, issuer) != 0) {
3755
                        /* Self-signed untrusted mimic. */
3756
46
                        X509_free(issuer);
3757
46
                        ok = 0;
3758
46
                    } else { /* curr "==" issuer */
3759
                        /*
3760
                         * Replace self-signed untrusted certificate
3761
                         * by its trusted matching issuer.
3762
                         */
3763
0
                        X509_free(curr);
3764
0
                        ctx->num_untrusted = --num;
3765
0
                        (void)sk_X509_set(ctx->chain, num, issuer);
3766
0
                    }
3767
46
                }
3768
3769
                /*
3770
                 * We've added a new trusted certificate to the chain, re-check
3771
                 * trust.  If not done, and not self-signed look deeper.
3772
                 * Whether or not we're doing "trusted first", we no longer
3773
                 * look for untrusted certificates from the peer's chain.
3774
                 *
3775
                 * At this point ctx->num_trusted and num must reflect the
3776
                 * correct number of untrusted certificates, since the DANE
3777
                 * logic in check_trust() depends on distinguishing CAs from
3778
                 * "the wire" from CAs from the trust store.  In particular, the
3779
                 * certificate at depth "num" should be the new trusted
3780
                 * certificate with ctx->num_untrusted <= num.
3781
                 */
3782
3.45k
                if (ok) {
3783
3.41k
                    if (!ossl_assert(ctx->num_untrusted <= num))
3784
0
                        goto int_err;
3785
3.41k
                    search &= ~S_DOUNTRUSTED;
3786
3.41k
                    trust = check_trust(ctx, num);
3787
3.41k
                    if (trust != X509_TRUST_UNTRUSTED)
3788
3.41k
                        break;
3789
0
                    if (!self_signed)
3790
0
                        continue;
3791
0
                }
3792
3.45k
            }
3793
3794
            /*
3795
             * No dispositive decision, and either self-signed or no match, if
3796
             * we were doing untrusted-first, and alt-chains are not disabled,
3797
             * do that, by repeatedly losing one untrusted element at a time,
3798
             * and trying to extend the shorted chain.
3799
             */
3800
102k
            if ((search & S_DOUNTRUSTED) == 0) {
3801
                /* Continue search for a trusted issuer of a shorter chain? */
3802
65.9k
                if ((search & S_DOALTERNATE) != 0 && --alt_untrusted > 0)
3803
0
                    continue;
3804
                /* Still no luck and no fallbacks left? */
3805
65.9k
                if (!may_alternate || (search & S_DOALTERNATE) != 0 || ctx->num_untrusted < 2)
3806
65.9k
                    break;
3807
                /* Search for a trusted issuer of a shorter chain */
3808
0
                search |= S_DOALTERNATE;
3809
0
                alt_untrusted = ctx->num_untrusted - 1;
3810
0
            }
3811
102k
        }
3812
3813
        /*
3814
         * Try to extend chain with peer-provided untrusted certificate
3815
         */
3816
36.9k
        if ((search & S_DOUNTRUSTED) != 0) {
3817
36.9k
            num = sk_X509_num(ctx->chain);
3818
36.9k
            if (!ossl_assert(num == ctx->num_untrusted))
3819
0
                goto int_err;
3820
36.9k
            curr = sk_X509_value(ctx->chain, num - 1);
3821
36.9k
            issuer = (X509_self_signed(curr, 0) > 0 || num > max_depth) ? NULL : get0_best_issuer_sk(ctx, 0, 1 /* no_dup */, sk_untrusted, curr);
3822
36.9k
            if (issuer == NULL) {
3823
                /*
3824
                 * Once we have reached a self-signed cert or num > max_depth
3825
                 * or can't find an issuer in the untrusted list we stop looking
3826
                 * there and start looking only in the trust store if enabled.
3827
                 */
3828
36.1k
                search &= ~S_DOUNTRUSTED;
3829
36.1k
                if (may_trusted)
3830
36.1k
                    search |= S_DOTRUSTED;
3831
36.1k
                continue;
3832
36.1k
            }
3833
3834
            /* Drop this issuer from future consideration */
3835
881
            (void)sk_X509_delete_ptr(sk_untrusted, issuer);
3836
3837
            /* Grow the chain by untrusted issuer */
3838
881
            if (!X509_add_cert(ctx->chain, issuer, X509_ADD_FLAG_UP_REF))
3839
0
                goto int_err;
3840
3841
881
            ++ctx->num_untrusted;
3842
3843
            /* Check for DANE-TA trust of the topmost untrusted certificate. */
3844
881
            trust = check_dane_issuer(ctx, ctx->num_untrusted - 1);
3845
881
            if (trust == X509_TRUST_TRUSTED || trust == X509_TRUST_REJECTED)
3846
0
                break;
3847
881
        }
3848
36.9k
    }
3849
69.3k
    sk_X509_free(sk_untrusted);
3850
3851
69.3k
    if (trust < 0) /* internal error */
3852
0
        return trust;
3853
3854
    /*
3855
     * Last chance to make a trusted chain, either bare DANE-TA public-key
3856
     * signers, or else direct leaf PKIX trust.
3857
     */
3858
69.3k
    num = sk_X509_num(ctx->chain);
3859
69.3k
    if (num <= max_depth) {
3860
69.3k
        if (trust == X509_TRUST_UNTRUSTED && DANETLS_HAS_DANE_TA(dane))
3861
0
            trust = check_dane_pkeys(ctx);
3862
69.3k
        if (trust == X509_TRUST_UNTRUSTED && num == ctx->num_untrusted)
3863
65.9k
            trust = check_trust(ctx, num);
3864
69.3k
    }
3865
3866
69.3k
    switch (trust) {
3867
3.42k
    case X509_TRUST_TRUSTED:
3868
3.42k
        return 1;
3869
0
    case X509_TRUST_REJECTED:
3870
        /* Callback already issued */
3871
0
        return 0;
3872
65.9k
    case X509_TRUST_UNTRUSTED:
3873
65.9k
    default:
3874
65.9k
        switch (ctx->error) {
3875
0
        case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
3876
0
        case X509_V_ERR_CERT_NOT_YET_VALID:
3877
0
        case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
3878
0
        case X509_V_ERR_CERT_HAS_EXPIRED:
3879
0
            return 0; /* Callback already done by ossl_x509_check_cert_time() */
3880
0
        default: /* A preliminary error has become final */
3881
0
            return verify_cb_cert(ctx, NULL, num - 1, ctx->error);
3882
65.9k
        case X509_V_OK:
3883
65.9k
            break;
3884
65.9k
        }
3885
65.9k
        CB_FAIL_IF(num > max_depth,
3886
65.9k
            ctx, NULL, num - 1, X509_V_ERR_CERT_CHAIN_TOO_LONG);
3887
65.9k
        CB_FAIL_IF(DANETLS_ENABLED(dane)
3888
65.9k
                && (!DANETLS_HAS_PKIX(dane) || dane->pdpth >= 0),
3889
65.9k
            ctx, NULL, num - 1, X509_V_ERR_DANE_NO_MATCH);
3890
65.9k
        if (X509_self_signed(sk_X509_value(ctx->chain, num - 1), 0) > 0)
3891
26.7k
            return verify_cb_cert(ctx, NULL, num - 1,
3892
26.7k
                num == 1
3893
26.7k
                    ? X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
3894
26.7k
                    : X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN);
3895
39.2k
        return verify_cb_cert(ctx, NULL, num - 1,
3896
39.2k
            ctx->num_untrusted < num
3897
39.2k
                ? X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
3898
39.2k
                : X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY);
3899
69.3k
    }
3900
3901
73
int_err:
3902
73
    ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
3903
73
    ctx->error = X509_V_ERR_UNSPECIFIED;
3904
73
    sk_X509_free(sk_untrusted);
3905
73
    return -1;
3906
3907
0
memerr:
3908
0
    ctx->error = X509_V_ERR_OUT_OF_MEM;
3909
0
    sk_X509_free(sk_untrusted);
3910
0
    return -1;
3911
69.3k
}
3912
3913
STACK_OF(X509) *X509_build_chain(X509 *target, STACK_OF(X509) *certs,
3914
    X509_STORE *store, int with_self_signed,
3915
    OSSL_LIB_CTX *libctx, const char *propq)
3916
0
{
3917
0
    int finish_chain = store != NULL;
3918
0
    X509_STORE_CTX *ctx;
3919
0
    int flags = X509_ADD_FLAG_UP_REF;
3920
0
    STACK_OF(X509) *result = NULL;
3921
3922
0
    if (target == NULL) {
3923
0
        ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
3924
0
        return NULL;
3925
0
    }
3926
3927
0
    if ((ctx = X509_STORE_CTX_new_ex(libctx, propq)) == NULL)
3928
0
        return NULL;
3929
0
    if (!X509_STORE_CTX_init(ctx, store, target, finish_chain ? certs : NULL))
3930
0
        goto err;
3931
0
    if (!finish_chain)
3932
0
        X509_STORE_CTX_set0_trusted_stack(ctx, certs);
3933
0
    if (!ossl_x509_add_cert_new(&ctx->chain, target, X509_ADD_FLAG_UP_REF)) {
3934
0
        ctx->error = X509_V_ERR_OUT_OF_MEM;
3935
0
        goto err;
3936
0
    }
3937
0
    ctx->num_untrusted = 1;
3938
3939
0
    if (!build_chain(ctx) && finish_chain)
3940
0
        goto err;
3941
3942
    /* result list to store the up_ref'ed certificates */
3943
0
    if (sk_X509_num(ctx->chain) > 1 && !with_self_signed)
3944
0
        flags |= X509_ADD_FLAG_NO_SS;
3945
0
    if (!ossl_x509_add_certs_new(&result, ctx->chain, flags)) {
3946
0
        sk_X509_free(result);
3947
0
        result = NULL;
3948
0
    }
3949
3950
0
err:
3951
0
    X509_STORE_CTX_free(ctx);
3952
0
    return result;
3953
0
}
3954
3955
/*
3956
 * note that there's a corresponding minbits_table in ssl/ssl_cert.c
3957
 * in ssl_get_security_level_bits that's used for selection of DH parameters
3958
 */
3959
static const int minbits_table[] = { 80, 112, 128, 192, 256 };
3960
static const int NUM_AUTH_LEVELS = OSSL_NELEM(minbits_table);
3961
3962
/*-
3963
 * Check whether the given public key meets the security level of `ctx`.
3964
 * Returns 1 on success, 0 otherwise.
3965
 */
3966
static int check_key_level(X509_STORE_CTX *ctx, EVP_PKEY *pkey)
3967
70.6k
{
3968
70.6k
    int level = ctx->param->auth_level;
3969
3970
    /*
3971
     * At security level zero, return without checking for a supported public
3972
     * key type.  Some engines support key types not understood outside the
3973
     * engine, and we only need to understand the key when enforcing a security
3974
     * floor.
3975
     */
3976
70.6k
    if (level <= 0)
3977
52.7k
        return 1;
3978
3979
    /* Unsupported or malformed keys are not secure */
3980
17.9k
    if (pkey == NULL)
3981
61
        return 0;
3982
3983
17.8k
    if (level > NUM_AUTH_LEVELS)
3984
0
        level = NUM_AUTH_LEVELS;
3985
3986
17.8k
    return EVP_PKEY_get_security_bits(pkey) >= minbits_table[level - 1];
3987
17.9k
}
3988
3989
/*-
3990
 * Check whether the public key of `cert` meets the security level of `ctx`.
3991
 * Returns 1 on success, 0 otherwise.
3992
 */
3993
static int check_cert_key_level(X509_STORE_CTX *ctx, X509 *cert)
3994
70.6k
{
3995
70.6k
    return check_key_level(ctx, X509_get0_pubkey(cert));
3996
70.6k
}
3997
3998
/*-
3999
 * Check whether the public key of ``cert`` does not use explicit params
4000
 * for an elliptic curve.
4001
 *
4002
 * Returns 1 on success, 0 if check fails, -1 for other errors.
4003
 */
4004
static int check_curve(X509 *cert)
4005
6.96k
{
4006
6.96k
    EVP_PKEY *pkey = X509_get0_pubkey(cert);
4007
6.96k
    int ret, val;
4008
4009
    /* Unsupported or malformed key */
4010
6.96k
    if (pkey == NULL)
4011
0
        return -1;
4012
6.96k
    if (EVP_PKEY_get_id(pkey) != EVP_PKEY_EC)
4013
6.96k
        return 1;
4014
4015
2
    ret = EVP_PKEY_get_int_param(pkey,
4016
2
        OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS,
4017
2
        &val);
4018
2
    return ret == 1 ? !val : -1;
4019
6.96k
}
4020
4021
/*-
4022
 * Check whether the signature digest algorithm of ``cert`` meets the security
4023
 * level of ``ctx``.  Should not be checked for trust anchors (whether
4024
 * self-signed or otherwise).
4025
 *
4026
 * Returns 1 on success, 0 otherwise.
4027
 */
4028
static int check_sig_level(X509_STORE_CTX *ctx, X509 *cert)
4029
0
{
4030
0
    int secbits = -1;
4031
0
    int level = ctx->param->auth_level;
4032
4033
0
    if (level <= 0)
4034
0
        return 1;
4035
0
    if (level > NUM_AUTH_LEVELS)
4036
0
        level = NUM_AUTH_LEVELS;
4037
4038
0
    if (!X509_get_signature_info(cert, NULL, NULL, &secbits, NULL))
4039
0
        return 0;
4040
4041
0
    return secbits >= minbits_table[level - 1];
4042
0
}