Coverage Report

Created: 2025-06-13 06:58

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