Coverage Report

Created: 2026-04-09 06:50

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