Coverage Report

Created: 2025-12-31 06:58

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