Coverage Report

Created: 2026-07-23 06:28

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