Coverage Report

Created: 2026-07-12 07:21

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