Coverage Report

Created: 2026-10-28 06:28

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