Coverage Report

Created: 2026-07-12 07:21

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