Coverage Report

Created: 2026-02-14 07:20

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