Coverage Report

Created: 2026-02-14 07:20

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