Coverage Report

Created: 2026-10-28 06:28

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