Coverage Report

Created: 2026-04-09 06:50

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