Coverage Report

Created: 2025-12-31 06:58

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