Coverage Report

Created: 2026-10-28 06:28

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